// Position — first-person, earned-authority narrative.
// The 18 years as preparation, not pedigree.
function Position() {
  const { lang } = React.useContext(window.LangContext);
  const { isMobile, isTablet } = window.useBreakpoint();
  const [vw, setVw] = React.useState(window.innerWidth);
  React.useEffect(() => {
    const h = () => setVw(window.innerWidth);
    window.addEventListener('resize', h, { passive: true });
    return () => window.removeEventListener('resize', h);
  }, []);
  const [refH2, visH2] = window.useReveal();
  const [refStats, visStats] = window.useReveal({ threshold: 0.08 });
  const [refDiagram, visDiagram] = window.useReveal({ threshold: 0.15 });

  const statConfig = [
    { target: 18,  fmt: function(n) { return String(n); } },
    { target: 11,  fmt: function(n) { return String(n); } },
    { target: 100, fmt: function(n) { return n + "+"; } },
    { target: 1,   fmt: function(n) { return (n < 10 ? "0" : "") + n; } },
  ];
  const [animCounts, setAnimCounts] = React.useState([0, 0, 0, 0]);

  React.useEffect(function() {
    if (!visStats) { setAnimCounts([0, 0, 0, 0]); return; }
    var dur = 1800, startTime = null;
    var targets = [18, 11, 100, 1];
    function step(ts) {
      if (!startTime) startTime = ts;
      var progress = Math.min((ts - startTime) / dur, 1);
      var eased = 1 - Math.pow(1 - progress, 3);
      setAnimCounts(targets.map(function(t) { return Math.round(eased * t); }));
      if (progress < 1) requestAnimationFrame(step);
    }
    var raf = requestAnimationFrame(step);
    return function() { cancelAnimationFrame(raf); };
  }, [visStats]);

  const en = {
    eyebrow: "07 · Position",
    h2line1: "Between domain,",
    h2line2: "technology, and leadership.",
    subtitle: "My strength is understanding and translating between these levels.",
    body1: "What users need, what domain teams know, what IT must secure, what developers can build, and which decisions leadership needs to make.",
    body3: "Live production is an extreme form of systems thinking: zero fault tolerance, real-time decisions, all departments that need to work simultaneously.",
    body4: "That is exactly what AI systems in production require: they need to work under pressure, be understood by people with different backgrounds — and still deliver clear results.",
    body5: "That creates a workflow that makes sense for everyone and actually works.",
    pills: ["Systems Thinking", "Technical Conception", "Custom UI & Interaction", "Interactive Live Systems"],
    bridgeLabel: "The bridge, in plain terms",
    bridge: [
      { before: "Director",       after: "Management",        label: "Outcomes &amp; intent" },
      { before: "Creatives",      after: "Domain experts",    label: "How the work actually happens" },
      { before: "Tech department", after: "IT &amp; engineering", label: "What the stack can safely carry" },
      { before: "Show safety",    after: "Legal &amp; governance", label: "What must be auditable, by when" },
    ],
    thenLabel: "Then",
    nowLabel: "Now",
    nodes: ["Domain", "IT", "Development", "Management", "Project Lead", "Users"],
    stats: [
      ["18",   "Years in live production"],
      ["11",   "Years leading motion & interactive development"],
      ["100+", "Productions delivered under live conditions"],
      ["01",   "Focus: systems built for production"],
    ],
  };

  const de = {
    eyebrow: "07 · Positionierung",
    h2line1: "Zwischen Fachbereich,",
    h2line2: "Technik und Führung.",
    subtitle: "Meine Stärke ist es, die unterschiedlichen Sprachen dieser Ebenen zu verstehen und zu übersetzen.",
    body1: "Was Nutzer brauchen, was Fachbereiche wissen, was IT absichern muss, was Entwickler umsetzen können und welche Entscheidungen das Management treffen muss.",
    body3: "Live-Produktion ist eine Extremform von Systemdenken: Keine Fehlertoleranz, Entscheidungen in Echtzeit, alle Gewerke, die gleichzeitig funktionieren müssen.",
    body4: "Genau das ist die Anforderung an KI-Systeme im Betrieb: Sie müssen unter Druck funktionieren, von Menschen mit unterschiedlichem Hintergrund verstanden werden — und trotzdem klare Ergebnisse liefern.",
    body5: "So entsteht ein Ablauf, der für alle sinnvoll ist und funktioniert.",
    pills: ["Systemdenken", "Technische Konzeption", "Custom UI & Interaction", "Interaktive Live-Systeme"],
    bridgeLabel: "Die Verbindung, in klaren Worten",
    bridge: [
      { before: "Regie",        after: "Management",           label: "Ziele &amp; Absichten" },
      { before: "Kreative",     after: "Fachexperten",         label: "Wie Arbeit wirklich funktioniert" },
      { before: "Technik",      after: "IT &amp; Engineering", label: "Was der Stack leisten kann" },
      { before: "Show-Sicherheit", after: "Legal &amp; Governance", label: "Was dokumentiert werden muss" },
    ],
    thenLabel: "Damals",
    nowLabel: "Heute",
    nodes: ["Fachbereich", "IT", "Entwicklung", "Management", "Projektleitung", "Nutzer"],
    stats: [
      ["18",   "Jahre in Event-Produktion"],
      ["11",   "Jahre Interactive-Entwicklung"],
      ["100+", "Produktionen unter Live-Bedingungen realisiert"],
      ["01",   "Fokus: Systeme, die in der Produktion funktionieren"],
    ],
  };

  const t = lang === 'de' ? de : en;

  return (
    <section id="position" style={{
      position: "relative",
      padding: isMobile ? "80px 24px 80px" : isTablet ? "80px 40px 80px 40px" : "220px 80px 220px 120px",
      borderBottom: "1px solid #2d2d38",
      overflow: "hidden",
    }}>
      {/* Blob-iridescent as background gravity */}
      <img src={(window.__resources && window.__resources.blobIridescent) || "assets/blob-iridescent.png"} alt="" aria-hidden="true" style={{
        position: "absolute",
        right: isMobile ? "-440px" : "-280px", top: "8%",
        width: "759px", height: "759px",
        objectFit: "contain",
        pointerEvents: "none",
        opacity: isMobile ? 0.3 : 0.4,
        filter: "drop-shadow(0 30px 80px rgba(92,53,204,0.30))",
        zIndex: 0,
      }} />

      <div style={{
        position: "absolute",
        top: 80,
        right: isMobile ? 16 : 80,
        fontFamily: "Montserrat", fontWeight: 200,
        fontSize: (isMobile || isTablet) ? 80 : 200, lineHeight: 1, color: "#1f1f27",
        letterSpacing: "-0.04em", pointerEvents: "none", zIndex: 1,
      }}>07</div>

      <div style={{ position: "relative", maxWidth: 1280, margin: "0 auto", zIndex: 2 }}>
        <div style={{ display: "flex", gap: 24, alignItems: "center", marginBottom: 64 }}>
          <div style={{ width: 40, height: 1, background: "#4a4a5a" }}></div>
          <span className="label label--wide" style={{ color: "#a8a8b8" }}>
            {t.eyebrow}
          </span>
        </div>

        <h2 ref={refH2} className={!isMobile ? `reveal${visH2 ? " visible" : ""}` : ""} style={{
          fontFamily: "Montserrat", fontWeight: 200,
          fontSize: "clamp(40px, 5.4vw, 88px)",
          lineHeight: 1.04, letterSpacing: "-0.025em",
          color: "#ffffff", margin: 0,
          maxWidth: 1100,
        }}>
          {t.h2line1}<br/>
          <span style={{ color: "#8e8ea8" }}>{t.h2line2}</span>
        </h2>

        <div style={{ display: "grid", gridTemplateColumns: (isMobile || isTablet) ? "1fr" : "1fr 1fr", gap: (isMobile || isTablet) ? 48 : 100, marginTop: (isMobile || isTablet) ? 48 : 100, alignItems: "end" }}>

          {/* Left: key sentence + body + pills */}
          <div>
            <p style={{ fontFamily: "Montserrat", fontWeight: 200, fontSize: "clamp(22px, 2vw, 28px)", lineHeight: 1.3, color: "#ffffff", margin: "0 0 24px", letterSpacing: "-0.015em" }}>
              {t.subtitle}
            </p>
            <p style={{ fontFamily: "Montserrat", fontWeight: 300, fontSize: 16, lineHeight: 1.75, color: "#a8a8b8", margin: "0 0 24px" }}>
              {t.body1}
            </p>
            <p style={{ fontFamily: "Montserrat", fontWeight: 300, fontSize: 15, lineHeight: 1.75, color: "#8080a0", margin: "0 0 24px" }}>
              {t.body2}
            </p>
            {t.body3 && (
              <p style={{ fontFamily: "Montserrat", fontWeight: 300, fontSize: 15, lineHeight: 1.75, color: "#8080a0", margin: "0 0 24px" }}>
                {t.body3}
              </p>
            )}
            {t.body4 && (
              <p style={{ fontFamily: "Montserrat", fontWeight: 300, fontSize: 15, lineHeight: 1.75, color: "#8080a0", margin: "0 0 24px" }}>
                {t.body4}
              </p>
            )}
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 48 }}>
              {t.pills.map(p => (
                <span key={p} className="pill">{p}</span>
              ))}
            </div>
          </div>

          {/* Right: stakeholder network — rich circular diagram */}
          <div ref={refDiagram} style={{ paddingTop: 0 }}>
            {(() => {
              const cx = 550, cy = 390, R = 246, nodeR = 43, innerR = 91, arrowSz = 6;
              const angles = [0,1,2,3,4,5].map(i => -Math.PI/2 + i * Math.PI * 2 / 6);
              const pts = angles.map(a => ({ x: cx + R * Math.cos(a), y: cy + R * Math.sin(a) }));
              const colors = ['#06b6d4','#8b5cf6','#f97316','#eab308','#22c55e','#0db8cc'];
              const adjPairs = [[0,1],[1,2],[2,3],[3,4],[4,5],[5,0]];

              const nodeData = lang === 'de' ? [
                { label: "Fachbereich",   sub: ["Prozesse verstehen.", "Domänenwissen kennen."] },
                { label: "IT",            sub: ["Machbarkeit prüfen.", "Sicherheit gewährleisten."] },
                { label: "Entwicklung",   sub: ["Anforderungen strukturieren.", "Bauplan schaffen."] },
                { label: "Management",    sub: ["Entscheidungen treffen.", "Wert schaffen."] },
                { label: "Projektleitung",sub: ["Ablauf steuern.", "Ergebnisse liefern."] },
                { label: "Nutzer",        sub: ["Intuitiv nutzbar machen.", "Alltag erleichtern."] },
              ] : [
                { label: "Domain",        sub: ["Understand processes.", "Know the domain."] },
                { label: "IT",            sub: ["Check feasibility.", "Ensure security."] },
                { label: "Development",   sub: ["Structure requirements.", "Create blueprint."] },
                { label: "Management",    sub: ["Make decisions.", "Create value."] },
                { label: "Project Lead",  sub: ["Manage workflow.", "Deliver outcomes."] },
                { label: "Users",         sub: ["Make it intuitive.", "Ease daily work."] },
              ];

              const centerText = lang === 'de' ? ["KLARHEIT", "VERBINDET"] : ["CLARITY", "CONNECTS"];
              const lc = [
                { anchor: "middle", lx: pts[0].x,              ly: pts[0].y - nodeR - 24 },
                { anchor: "start",  lx: pts[1].x + nodeR + 16, ly: pts[1].y - 14 },
                { anchor: "start",  lx: pts[2].x + nodeR + 16, ly: pts[2].y - 14 },
                { anchor: "middle", lx: pts[3].x,              ly: pts[3].y + nodeR + 32 },
                { anchor: "end",    lx: pts[4].x - nodeR - 16, ly: pts[4].y - 14 },
                { anchor: "end",    lx: pts[5].x - nodeR - 16, ly: pts[5].y - 14 },
              ];

              const icon = (i, col) => {
                const s = { stroke: col, fill: "none", strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round" };
                if (i === 0) return <g>
                  <rect x="-5" y="-12" width="10" height="7" rx="1.5" {...s}/>
                  <path d="M 0 -5 L 0 0 M -7 0 L 7 0 M -7 0 L -7 4 M 7 0 L 7 4" {...s}/>
                  <rect x="-11" y="4" width="8" height="6" rx="1.5" {...s}/>
                  <rect x="3" y="4" width="8" height="6" rx="1.5" {...s}/>
                </g>;
                if (i === 1) return <g>
                  <rect x="-10" y="-9" width="20" height="8" rx="2" {...s}/>
                  <circle cx="5.5" cy="-5" r="2" fill={col} stroke="none"/>
                  <rect x="-10" y="1" width="20" height="8" rx="2" {...s}/>
                  <circle cx="5.5" cy="5" r="2" fill={col} stroke="none"/>
                  <line x1="-6" y1="-5" x2="-2" y2="-5" {...s}/>
                  <line x1="-6" y1="5" x2="-2" y2="5" {...s}/>
                </g>;
                if (i === 2) return <g>
                  <polyline points="-5,-7 -10,0 -5,7" stroke={col} fill="none" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                  <polyline points="5,-7 10,0 5,7" stroke={col} fill="none" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                  <line x1="3" y1="-8" x2="-3" y2="8" stroke={col} strokeWidth="1.8" strokeLinecap="round"/>
                </g>;
                if (i === 3) return <g>
                  <rect x="-11" y="0" width="6" height="9" rx="1" fill={col} opacity="0.65"/>
                  <rect x="-3" y="-5" width="6" height="14" rx="1" fill={col} opacity="0.82"/>
                  <rect x="5" y="-10" width="6" height="19" rx="1" fill={col}/>
                </g>;
                if (i === 4) return <g>
                  <rect x="-9" y="-10" width="18" height="20" rx="2" {...s}/>
                  <rect x="-4" y="-13" width="8" height="5" rx="2" {...s}/>
                  <line x1="-5" y1="-3" x2="5" y2="-3" {...s}/>
                  <line x1="-5" y1="1" x2="2" y2="1" {...s}/>
                  <line x1="-5" y1="5" x2="5" y2="5" {...s}/>
                </g>;
                return <g>
                  <circle cx="0" cy="-5" r="5" {...s}/>
                  <path d="M -10 11 C -10 3 10 3 10 11" {...s}/>
                </g>;
              };

              // Convert SVG coords to % of viewBox (viewBox: "0 -30 1100 830")
              const toP = (x, y) => ({
                left: `${(x / 1100 * 100).toFixed(2)}%`,
                top:  `${((y + 30) / 830 * 100).toFixed(2)}%`,
              });
              const labelTransforms = [
                "translateX(-50%) translateY(-100%)", // 0 top — bottom of div sits at coord
                "translateY(-50%)",                   // 1 right-top — vertically centered
                "translateY(-50%)",                   // 2 right-bottom
                "translateX(-50%)",                   // 3 bottom — top of div sits at coord
                "translateX(-100%) translateY(-50%)", // 4 left-bottom
                "translateX(-100%) translateY(-50%)", // 5 left-top
              ];
              const labelAligns = ["center","left","left","center","right","right"];

              return (
                <div style={{ position: "relative", overflow: "visible" }}>
                  <svg viewBox="0 -30 1100 830" style={{ width: "100%", display: "block" }}>
                    <defs>
                      {adjPairs.map(([i,j], k) => (
                        <linearGradient key={k} id={`pg${k}`}
                          x1={pts[i].x} y1={pts[i].y} x2={pts[j].x} y2={pts[j].y}
                          gradientUnits="userSpaceOnUse">
                          <stop offset="0%"   stopColor={colors[i]} stopOpacity="0.9"/>
                          <stop offset="100%" stopColor={colors[j]} stopOpacity="0.9"/>
                        </linearGradient>
                      ))}
                      <radialGradient id="cg" cx="50%" cy="50%" r="50%">
                        <stop offset="0%"   stopColor="#0db8cc" stopOpacity="0.22"/>
                        <stop offset="55%"  stopColor="#0a3a5c" stopOpacity="0.15"/>
                        <stop offset="100%" stopColor="#0f0f12" stopOpacity="0"/>
                      </radialGradient>
                    </defs>

                    <g style={{ opacity: visDiagram ? 1 : 0, transition: visDiagram ? 'opacity 1.0s ease-out 0s' : 'opacity 0s' }}>
                      <circle cx={cx} cy={cy} r={innerR + 30} fill="url(#cg)"/>
                      <circle cx={cx} cy={cy} r={innerR}      fill="rgba(13,184,204,0.04)" stroke="rgba(13,184,204,0.10)" strokeWidth="1"/>
                      <circle cx={cx} cy={cy} r={innerR - 16} fill="rgba(13,184,204,0.07)" stroke="rgba(13,184,204,0.15)" strokeWidth="1"/>
                      <circle cx={cx} cy={cy} r={innerR - 30} fill="rgba(13,184,204,0.12)" stroke="rgba(13,184,204,0.22)" strokeWidth="1"/>
                      <circle cx={cx} cy={cy} r={innerR - 42} fill="rgba(13,184,204,0.19)" stroke="rgba(13,184,204,0.32)" strokeWidth="1"/>
                    </g>

                    {pts.map((p, i) => {
                      const dx = p.x - cx, dy = p.y - cy;
                      const len = Math.sqrt(dx*dx + dy*dy);
                      const nx = dx/len, ny = dy/len;
                      const x1 = cx + nx * innerR, y1 = cy + ny * innerR;
                      const x2 = p.x - nx * (nodeR + 3), y2 = p.y - ny * (nodeR + 3);
                      const px = -ny * arrowSz * 0.55, py = nx * arrowSz * 0.55;
                      return (
                        <g key={i} style={{ opacity: visDiagram ? 1 : 0, transition: visDiagram ? `opacity 0.55s ease-out ${0.2 + i * 0.09}s` : 'opacity 0s' }}>
                          <line x1={x1} y1={y1} x2={x2} y2={y2}
                            stroke={colors[i]} strokeWidth="1.2" strokeDasharray="4 4" opacity="0.45"/>
                          <polygon
                            points={`${x2},${y2} ${x2-nx*arrowSz*1.4+px},${y2-ny*arrowSz*1.4+py} ${x2-nx*arrowSz*1.4-px},${y2-ny*arrowSz*1.4-py}`}
                            fill={colors[i]} opacity="0.6"/>
                        </g>
                      );
                    })}

                    {adjPairs.map(([i,j], k) => (
                      <path key={k}
                        d={`M ${pts[i].x} ${pts[i].y} A ${R} ${R} 0 0 1 ${pts[j].x} ${pts[j].y}`}
                        fill="none" stroke={`url(#pg${k})`} strokeWidth="2.5"
                        style={{ opacity: visDiagram ? 1 : 0, transition: visDiagram ? `opacity 0.6s ease-out ${0.65 + k * 0.07}s` : 'opacity 0s' }}/>
                    ))}

                    {pts.map((p, i) => (
                      <g key={i} transform={`translate(${p.x},${p.y})`}
                         style={{ opacity: visDiagram ? 1 : 0, transition: visDiagram ? `opacity 0.7s ease-out ${0.3 + i * 0.1}s` : 'opacity 0s' }}>
                        <circle r={nodeR + 7} fill={colors[i]} opacity="0.07"/>
                        <circle r={nodeR} fill="rgba(8,10,22,0.95)" stroke={colors[i]} strokeWidth="1.8"/>
                        {icon(i, colors[i])}
                      </g>
                    ))}

                    <text x={cx} y={cy - 9} textAnchor="middle"
                      fill="#b0ecf5" fontFamily="Montserrat, sans-serif"
                      fontSize="17" fontWeight="600" letterSpacing="0.20em"
                      style={{ opacity: visDiagram ? 1 : 0, transition: visDiagram ? 'opacity 0.7s ease-out 0.55s' : 'opacity 0s' }}>
                      {centerText[0]}
                    </text>
                    <text x={cx} y={cy + 12} textAnchor="middle"
                      fill="#b0ecf5" fontFamily="Montserrat, sans-serif"
                      fontSize="17" fontWeight="600" letterSpacing="0.20em"
                      style={{ opacity: visDiagram ? 1 : 0, transition: visDiagram ? 'opacity 0.7s ease-out 0.60s' : 'opacity 0s' }}>
                      {centerText[1]}
                    </text>
                  </svg>

                  {/* HTML labels — full HD only; laptop and below get legend grid */}
                  {!isMobile && !isTablet && vw >= 1440 && lc.map((l, i) => (
                    <div key={i} style={{
                      position: "absolute",
                      ...toP(l.lx, l.ly),
                      transform: labelTransforms[i],
                      textAlign: labelAligns[i],
                      pointerEvents: "none",
                    }}>
                      <div style={{
                        fontFamily: "Montserrat", fontWeight: 600,
                        fontSize: 14, color: colors[i],
                        letterSpacing: "0.04em", lineHeight: 1.3,
                        whiteSpace: "nowrap",
                      }}>{nodeData[i].label}</div>
                      {nodeData[i].sub.map((s, si) => (
                        <div key={si} style={{
                          fontFamily: "Montserrat", fontWeight: 300,
                          fontSize: 13, color: "#7a7a8e",
                          lineHeight: 1.5, whiteSpace: "nowrap",
                        }}>{s}</div>
                      ))}
                    </div>
                  ))}
                </div>
              );
            })()}

            {/* Node legend — mobile, tablet, and laptop (below Full HD) */}
            {(isMobile || isTablet || vw < 1440) && (() => {
              const colors = ['#06b6d4','#8b5cf6','#f97316','#eab308','#22c55e','#0db8cc'];
              const nodeData = lang === 'de' ? [
                { label: "Fachbereich" }, { label: "IT" }, { label: "Entwicklung" },
                { label: "Management" }, { label: "Projektleitung" }, { label: "Nutzer" },
              ] : [
                { label: "Domain" }, { label: "IT" }, { label: "Development" },
                { label: "Management" }, { label: "Project Lead" }, { label: "Users" },
              ];
              return (
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "10px 8px", marginTop: 20 }}>
                  {nodeData.map((nd, i) => (
                    <div key={i} style={{
                      fontFamily: "Montserrat", fontWeight: 600,
                      fontSize: 11, color: colors[i],
                      letterSpacing: "0.05em", textAlign: "center",
                    }}>{nd.label}</div>
                  ))}
                </div>
              );
            })()}
          </div>
        </div>

        {/* Stats strip */}
        <div ref={refStats} className={!isMobile ? `reveal-stagger${visStats ? " visible" : ""}` : ""} style={{
          display: "grid", gridTemplateColumns: (isMobile || isTablet) ? "repeat(2, 1fr)" : "repeat(4, 1fr)", gap: (isMobile || isTablet) ? 32 : 48,
          marginTop: (isMobile || isTablet) ? 64 : 140, paddingTop: 56, borderTop: "1px solid #2d2d38",
        }}>
          {t.stats.map(([n, l], idx) => (
            <div key={n} className={!isMobile ? "reveal-item" : ""}>
              <div style={{ fontFamily: "Montserrat", fontWeight: 200, fontSize: isMobile ? 48 : 64, color: "#ffffff", letterSpacing: "-0.025em", lineHeight: 1 }}>
                {statConfig[idx].fmt(animCounts[idx])}
              </div>
              <div className="label label--wide" style={{ color: "#8080a0", marginTop: 14 }}>
                {l}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

window.Position = Position;
