// ─── Stufengrafik (Treppe / Transformationspfad) ─────────────────────────────
// Interactive staircase inspired by the NRL Figma "Transformationspfad Treppe"
// 6 clickable steps, each representing one Überthema

const Stufengrafik = ({ onSelect, activeId }) => {
  const [hoverId, setHoverId] = React.useState(null);

  // Steps: bottom-left to top-right (ascending staircase)
  // We render 6 steps, each is a hexagonal "platform" tile + label
  // Colors match the THEMEN data

  const steps = [
    { id: 'wasserstoff', label: 'Wasserstoff\nerzeugung & -nutzung', step: 1 },
    { id: 'industrie',   label: 'Defossilisierung\nin der Industrie',    step: 2 },
    { id: 'waerme',      label: 'Nachhaltige\nWärmeerzeugung',           step: 3 },
    { id: 'mobilitaet',  label: 'Nachhaltige\nMobilität',                step: 4 },
    { id: 'netze',       label: 'Angepasste Netze\n& Infrastruktur',     step: 5 },
    { id: 'gesellschaft',label: 'Gesellschaftliche\nTeilhabe',           step: 6 },
  ];

  const themaMap = {};
  THEMEN.forEach(t => { themaMap[t.id] = t; });

  // SVG dimensions
  const W = 900, H = 480;
  // Step geometry
  const STEP_W = 132, STEP_H = 64, RISER_H = 48;
  const BASE_X = 20, BASE_Y = H - 40;
  const OVERLAP = 8; // steps overlap slightly

  // Compute each step's position (ascending left→right staircase)
  const getStep = (i) => {
    const x = BASE_X + i * (STEP_W - OVERLAP);
    const y = BASE_Y - i * (STEP_H + RISER_H) - STEP_H;
    return { x, y };
  };

  // 3D stair appearance: top face + front face + right side face
  const renderStair = (s, i) => {
    const { id, label } = s;
    const tema = themaMap[id];
    const isHover = hoverId === id;
    const isActive = activeId === id;
    const color = tema.farbe;
    const colorDark = tema.farbeText;
    const colorLight = tema.farbeHell;

    const { x, y } = getStep(i);
    const TW = STEP_W;
    const TH = STEP_H;
    const FH = RISER_H;  // front face height
    const SIDE = 28;     // right side depth
    const SK = 14;       // skew amount for 3d top
    const LIFT = isHover || isActive ? 6 : 0;

    // Top face (parallelogram)
    const topPts = [
      [x + SK, y - LIFT],
      [x + TW + SK, y - LIFT],
      [x + TW, y + TH - LIFT],
      [x, y + TH - LIFT],
    ].map(p => p.join(',')).join(' ');

    // Front face (rectangle below top)
    const frontPts = [
      [x, y + TH - LIFT],
      [x + TW, y + TH - LIFT],
      [x + TW, y + TH + FH],
      [x, y + TH + FH],
    ].map(p => p.join(',')).join(' ');

    // Right side face
    const sidePts = [
      [x + TW, y + TH - LIFT],
      [x + TW + SK, y - LIFT],
      [x + TW + SK, y + FH + SK/2],
      [x + TW, y + TH + FH],
    ].map(p => p.join(',')).join(' ');

    // Number badge position (on top face center)
    const badgeCX = x + SK/2 + TW/2;
    const badgeCY = y + TH/2 - LIFT - 4;

    // Label position (below front face)
    const labelLines = label.split('\n');
    const labelX = x + TW/2;
    const labelY = y + TH + FH + 16;

    const alpha = isHover || isActive ? 1 : 0.88;

    return (
      <g
        key={id}
        style={{ cursor: 'pointer' }}
        onClick={() => onSelect(id)}
        onMouseEnter={() => setHoverId(id)}
        onMouseLeave={() => setHoverId(null)}
        role="button"
        aria-label={label.replace('\n', ' ')}
        tabIndex={0}
        onKeyDown={e => e.key === 'Enter' && onSelect(id)}
      >
        {/* Shadow */}
        <ellipse
          cx={x + TW/2 + SK/2}
          cy={y + TH + FH + 4}
          rx={TW * 0.48}
          ry={6}
          fill="rgba(0,0,0,0.08)"
        />
        {/* Right side */}
        <polygon points={sidePts} fill={colorDark} opacity={alpha * 0.8} />
        {/* Front face */}
        <polygon points={frontPts} fill={colorDark} opacity={alpha} />
        {/* Highlight line on front */}
        <line
          x1={x} y1={y + TH - LIFT}
          x2={x + TW} y2={y + TH - LIFT}
          stroke="rgba(255,255,255,0.3)" strokeWidth={1.5}
        />
        {/* Top face */}
        <polygon points={topPts} fill={isActive ? color : (isHover ? color : colorLight)} opacity={alpha} />
        {/* Top face inner glow for active */}
        {isActive && (
          <polygon points={topPts} fill="rgba(255,255,255,0.15)" />
        )}
        {/* Number circle */}
        <circle cx={badgeCX - 28} cy={badgeCY} r={12} fill={isActive ? '#fff' : colorDark} opacity={0.9} />
        <text x={badgeCX - 28} y={badgeCY + 4.5} textAnchor="middle"
          fontFamily="Nunito Sans, Arial, sans-serif" fontWeight="700" fontSize="11"
          fill={isActive ? colorDark : '#fff'}>
          {i + 1}
        </text>
        {/* Label below */}
        {labelLines.map((line, li) => (
          <text key={li}
            x={labelX} y={labelY + li * 16}
            textAnchor="middle"
            fontFamily="Nunito Sans, Arial, sans-serif"
            fontWeight={isActive || isHover ? '700' : '600'}
            fontSize="11.5"
            fill={isActive ? colorDark : (isHover ? colorDark : '#434343')}
          >
            {line}
          </text>
        ))}
        {/* Active indicator dot */}
        {isActive && (
          <circle cx={labelX} cy={labelY + labelLines.length * 16 + 6} r={3} fill={color} />
        )}
      </g>
    );
  };

  return (
    <div style={sfS.wrapper}>
      {/* Left label block */}
      <div style={sfS.leftLabels}>
        <div style={sfS.statusQuo}>
          <div style={sfS.sqTitle}>Energiesystem<br />Status Quo</div>
          <div style={sfS.sqLine}></div>
        </div>
        <div style={sfS.nrlLabel}>
          <div style={sfS.nrlTitle}>NRL-Transformationspfad</div>
          <div style={sfS.nrlSub}>Gesamtsystemische Betrachtung von<br />Querschnittsthemen und Erfolgsfaktoren</div>
        </div>
      </div>

      {/* SVG Staircase */}
      <div style={sfS.svgWrap}>
        <svg viewBox={`0 0 ${W} ${H}`} style={sfS.svg} aria-label="Transformationspfad Stufengrafik">
          {/* Background light band (the "path" ribbon) */}
          <defs>
            <linearGradient id="ribbonGrad" x1="0%" y1="100%" x2="100%" y2="0%">
              <stop offset="0%" stopColor="#AACEDE" stopOpacity="0.18" />
              <stop offset="100%" stopColor="#569EBE" stopOpacity="0.08" />
            </linearGradient>
            <linearGradient id="pinkRibbon" x1="0%" y1="100%" x2="100%" y2="0%">
              <stop offset="0%" stopColor="#E296B3" stopOpacity="0.15" />
              <stop offset="100%" stopColor="#CF5782" stopOpacity="0.08" />
            </linearGradient>
          </defs>

          {/* Ribbon background path */}
          <polygon
            points={`20,${H-10} ${W-20},60 ${W-20},160 20,${H-10+60}`}
            fill="url(#ribbonGrad)"
          />
          <polygon
            points={`20,${H-80} ${W-20},20 ${W-20},70 20,${H-30}`}
            fill="url(#pinkRibbon)"
          />

          {/* Top labels */}
          <text x={W - 20} y={32} textAnchor="end"
            fontFamily="Nunito Sans, Arial, sans-serif" fontWeight="700" fontSize="13" fill="#46829C">
            Weg zur Klimaneutralität
          </text>
          <text x={W - 20} y={50} textAnchor="end"
            fontFamily="Nunito Sans, Arial, sans-serif" fontWeight="700" fontSize="13" fill="#46829C">
            bis 2045
          </text>

          {/* Ergebnis NRL label */}
          <text x={240} y={100} textAnchor="middle"
            fontFamily="Nunito Sans, Arial, sans-serif" fontWeight="700" fontSize="12" fill="#569EBE">
            Ergebnis
          </text>
          <text x={240} y={116} textAnchor="middle"
            fontFamily="Nunito Sans, Arial, sans-serif" fontWeight="700" fontSize="12" fill="#569EBE">
            NRL 2026
          </text>

          {/* Render steps back-to-front (higher index = higher on screen, render first for proper layering) */}
          {steps.map((s, i) => renderStair(s, i)).reverse()}

          {/* Hover/click instruction */}
          <text x={W/2} y={H - 6} textAnchor="middle"
            fontFamily="Nunito Sans, Arial, sans-serif" fontSize="11" fill="#9AABB2">
            Klicken Sie auf ein Thema, um die Ergebnisse zu erkunden
          </text>
        </svg>
      </div>
    </div>
  );
};

const sfS = {
  wrapper: {
    display: 'flex',
    alignItems: 'flex-end',
    gap: 0,
    width: '100%',
    maxWidth: 1100,
    margin: '0 auto',
    position: 'relative',
  },
  leftLabels: {
    flexShrink: 0,
    width: 180,
    paddingBottom: 60,
    display: 'flex',
    flexDirection: 'column',
    gap: 24,
    paddingRight: 16,
  },
  statusQuo: {
    display: 'flex',
    flexDirection: 'column',
    gap: 6,
  },
  sqTitle: {
    fontFamily: "'Nunito Sans', Arial, sans-serif",
    fontSize: 15,
    fontWeight: 800,
    color: '#1A1C1D',
    lineHeight: 1.3,
  },
  sqLine: {
    width: 32,
    height: 2,
    background: '#569EBE',
    borderRadius: 1,
  },
  nrlLabel: {
    display: 'flex',
    flexDirection: 'column',
    gap: 6,
  },
  nrlTitle: {
    fontFamily: "'Nunito Sans', Arial, sans-serif",
    fontSize: 13,
    fontWeight: 700,
    color: '#46829C',
  },
  nrlSub: {
    fontFamily: "'Nunito Sans', Arial, sans-serif",
    fontSize: 11,
    color: '#7A8A90',
    lineHeight: 1.5,
  },
  svgWrap: {
    flex: 1,
    minWidth: 0,
  },
  svg: {
    width: '100%',
    height: 'auto',
    display: 'block',
    overflow: 'visible',
  },
};

Object.assign(window, { Stufengrafik });
