// agent-anatomie.jsx — "Woraus ein Agent besteht": PixelKilian in der Mitte,
// die Steckbrief-Bausteine als Flip-Karten drumherum, feine Linien zum Avatar.
// Werkzeuge zeigt auf den Laptop. Klick: Karte dreht sich, wächst, erklärt sich.
// Ohne Ergebnis & Auslöser; Grenzen + Freigabe zusammengefasst.

const ANAT_COPY = {
  de: {
    kicker: 'Die Anatomie',
    title: 'Woraus ein Agent besteht',
    intro: 'Acht Bausteine machen aus einem Modell einen Kollegen. Klick auf eine Karte — im Steckbrief unten legst du genau diese Bausteine fest.',
    flipHint: 'Klicken zum Umdrehen',
  },
  en: {
    kicker: 'The anatomy',
    title: 'What an agent is made of',
    intro: 'Eight building blocks turn a model into a colleague. Click a card — the brief below is where you define exactly these.',
    flipHint: 'Click to flip',
  },
};

// side/slot steuern die Position im Desktop-Layout (4 links, 4 rechts).
// target = Punkt auf dem Avatar (Design-Koordinaten), zu dem die Linie läuft.
const ANAT_ITEMS = [
  {
    id: 'job', icon: 'flag', side: 'left', slot: 0,
    de: { label: 'Job', hint: 'Wozu ist er da?', back: 'Als [Rolle] brauche ich [Agent], damit [Ziel] — das Mandat in einem Satz, nicht die Technik. Faustregel: Steht der Satz nicht, steht der Agent nicht.' },
    en: { label: 'Job', hint: 'What is it for?', back: 'As [role] I need [agent] so that [goal] — the mandate in one sentence, not the tech. Rule of thumb: if the sentence doesn\u2019t stand, the agent doesn\u2019t either.' },
  },
  {
    id: 'ausloeser', icon: 'lightning', side: 'left', slot: 1,
    de: { label: 'Auslöser', hint: 'Wann wird er aktiv?', back: 'Neue Mail, Formular, feste Uhrzeit, Knopfdruck — der Startschuss. Entscheidet, ob du einen Chatbot oder einen Cron-Job baust. Faustregel: Kein Auslöser, kein Agent.' },
    en: { label: 'Trigger', hint: 'When does it start?', back: 'New mail, a form, a fixed time, a button press — the starting gun. Decides whether you build a chatbot or a cron job. Rule of thumb: no trigger, no agent.' },
  },
  {
    id: 'wissen', icon: 'books', side: 'left', slot: 2,
    de: { label: 'Wissen', hint: 'Was muss er kennen?', back: 'Leistungen, Preise, Tonfall, interne Regeln — das Wissen, das nicht im Modell steckt. Der Unterschied zwischen generisch und deins. Faustregel: Was ein neuer Mitarbeiter am ersten Tag bräuchte.' },
    en: { label: 'Knowledge', hint: 'What must it know?', back: 'Services, prices, tone, internal rules — the knowledge that isn\u2019t in the model. The difference between generic and yours. Rule of thumb: what a new hire would need on day one.' },
  },
  {
    id: 'werkzeuge', icon: 'wrench', side: 'left', slot: 3, toLaptop: true,
    de: { label: 'Werkzeuge', hint: 'Worauf darf er zugreifen?', back: 'Postfach, Kalender, CRM, Dateiablage — die Systeme, auf die er zugreifen darf. Faustregel: so wenig wie möglich, so viel wie nötig.' },
    en: { label: 'Tools', hint: 'What may it access?', back: 'Inbox, calendar, CRM, file storage — the systems it may access. Rule of thumb: as little as possible, as much as needed.' },
  },
  {
    id: 'aufgaben', icon: 'list-checks', side: 'right', slot: 0,
    de: { label: 'Aufgaben', hint: 'Was erledigt er konkret?', back: 'Lesen, einordnen, entwerfen, verschicken — die konkreten Handgriffe als Verben, nicht als Themen. Faustregel: Was du nicht als Tätigkeit aufschreiben kannst, kann er nicht tun.' },
    en: { label: 'Tasks', hint: 'What does it actually do?', back: 'Read, classify, draft, send — the concrete steps as verbs, not topics. Rule of thumb: what you can\u2019t write down as an activity, it can\u2019t do.' },
  },
  {
    id: 'ergebnis', icon: 'seal-check', side: 'right', slot: 1,
    de: { label: 'Ergebnis', hint: 'Woran merkst du, dass er gut war?', back: 'Ein freigabefertiger Entwurf, ein sauber getaggter Eintrag — das prüfbare Resultat. Faustregel: Beschreib das fertige Ergebnis, nicht die gute Absicht.' },
    en: { label: 'Result', hint: 'How do you know it did well?', back: 'A ready-to-approve draft, a cleanly tagged entry — the checkable result. Rule of thumb: describe the finished result, not the good intention.' },
  },
  {
    id: 'grenzen', icon: 'hand-palm', side: 'right', slot: 2,
    de: { label: 'Grenzen & Freigabe', hint: 'Was darf er allein?', back: 'Reversibles darf er allein, Verbindliches braucht Freigabe — autonom heißt nicht unkontrolliert. Faustregel: Was du nicht zurücknehmen kannst, braucht einen Menschen davor.' },
    en: { label: 'Limits & approval', hint: 'What may it do alone?', back: 'Reversible things it does alone; binding things need approval — autonomous doesn\u2019t mean uncontrolled. Rule of thumb: what you can\u2019t take back needs a human in front of it.' },
  },
  {
    id: 'datenrisiko', icon: 'lock-key', side: 'right', slot: 3, risk: true,
    de: { label: 'Datenrisiko', hint: 'Was, wenn\u2019s schiefgeht?', back: 'Mandantendaten, Gesundheits-, Zahlungsdaten — was durch ihn fließt. Das Risiko entsteht aus Wissen × Werkzeuge, nicht aus dem Feld. Faustregel: Nicht „wie sensibel“, sondern „was passiert, wenn er auf die falschen Daten losgeht“.' },
    en: { label: 'Data risk', hint: 'What if it goes wrong?', back: 'Client, health, payment data — what flows through it. The risk comes from knowledge × tools, not from the field. Rule of thumb: not “how sensitive” but “what happens if it goes at the wrong data”.' },
  },
];

// ── Desktop-Geometrie (Design-Koordinaten, wird als Ganzes skaliert) ──
const ANAT_W = 936;
const ANAT_H = 720;
const ANAT_CARD_W = 250;
const ANAT_CARD_H = 150;
const ANAT_ROWS_Y = [0, 190, 380, 570];
// Avatar: PixelKilian size 260 → 260×232, zentriert
const ANAT_AV_SIZE = 260;
const ANAT_AV_W = ANAT_AV_SIZE;
const ANAT_AV_H = Math.round(ANAT_AV_SIZE * 880 / 985);
const ANAT_AV_X = (ANAT_W - ANAT_AV_W) / 2;   // 338
const ANAT_AV_Y = (ANAT_H - ANAT_AV_H) / 2;   // 244

// Linien-Ziele auf dem Avatar. Laptop sitzt im Bild bei ~x 60–95 %, y 68–92 %.
const ANAT_TARGETS = {
  job:         [ANAT_AV_X + ANAT_AV_W * 0.36, ANAT_AV_Y + ANAT_AV_H * 0.18],
  ausloeser:   [ANAT_AV_X + ANAT_AV_W * 0.26, ANAT_AV_Y + ANAT_AV_H * 0.42],
  wissen:      [ANAT_AV_X + ANAT_AV_W * 0.24, ANAT_AV_Y + ANAT_AV_H * 0.64],
  werkzeuge:   [ANAT_AV_X + ANAT_AV_W * 0.60, ANAT_AV_Y + ANAT_AV_H * 0.88], // Laptop (Tastatur-Seite)
  aufgaben:    [ANAT_AV_X + ANAT_AV_W * 0.62, ANAT_AV_Y + ANAT_AV_H * 0.16],
  ergebnis:    [ANAT_AV_X + ANAT_AV_W * 0.80, ANAT_AV_Y + ANAT_AV_H * 0.40],
  grenzen:     [ANAT_AV_X + ANAT_AV_W * 0.82, ANAT_AV_Y + ANAT_AV_H * 0.62],
  datenrisiko: [ANAT_AV_X + ANAT_AV_W * 0.90, ANAT_AV_Y + ANAT_AV_H * 0.78], // Laptop (Bildschirm)
};

function anatCardPos(item) {
  const x = item.side === 'left' ? 0 : ANAT_W - ANAT_CARD_W;
  const y = ANAT_ROWS_Y[item.slot];
  return { x, y };
}

function anatLine(item) {
  const { x, y } = anatCardPos(item);
  const ax = item.side === 'left' ? x + ANAT_CARD_W : x;
  const ay = y + ANAT_CARD_H / 2;
  const [tx, ty] = ANAT_TARGETS[item.id];
  const mx = (ax + tx) / 2;
  return { d: `M ${ax} ${ay} Q ${mx} ${ay}, ${tx} ${ty}`, tx, ty };
}

// ── Eine Flip-Karte ──────────────────────────────────────────
function AnatCard({ item, lang, accent, active, onToggle, flipHint, style = {}, growScale = 1.24 }) {
  const c = item[lang];
  return (
    <button
      onClick={onToggle}
      aria-expanded={active}
      className="anat-card"
      style={{
        display: 'block', width: ANAT_CARD_W, height: ANAT_CARD_H,
        background: 'transparent', border: 'none', padding: 0, margin: 0,
        cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
        perspective: 900,
        zIndex: active ? 6 : 2,
        transform: active ? `scale(${growScale})` : 'none',
        transition: 'transform 480ms cubic-bezier(.2,.7,.2,1)',
        ...style,
      }}
    >
      <span className="anat-inner" style={{
        position: 'absolute', inset: 0, display: 'block',
        transformStyle: 'preserve-3d',
        transition: 'transform 480ms cubic-bezier(.2,.7,.2,1)',
        transform: active ? 'rotateY(180deg)' : 'none',
      }}>
        {/* Vorderseite */}
        <span className="anat-face" style={{
          position: 'absolute', inset: 0, backfaceVisibility: 'hidden', WebkitBackfaceVisibility: 'hidden',
          background: '#fff', border: `1px solid ${item.risk ? KS.deepRed : KS.border}`, borderRadius: 12,
          padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 13,
          boxShadow: '0 4px 16px -12px rgba(73,70,72,0.25)',
        }}>
          <span style={{
            width: 38, height: 38, borderRadius: 9, background: KS.offwhite, color: accent,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 19, flexShrink: 0,
          }}><Icon name={item.icon} /></span>
          <span style={{ flex: 1, minWidth: 0 }}>
            <span style={{ display: 'block', fontWeight: 700, fontSize: 15.5, color: KS.black, letterSpacing: -0.3 }}>{c.label}</span>
            <span style={{ display: 'block', fontFamily: KSFonts.mono, fontSize: 10.5, color: KS.muted, letterSpacing: 0.3, marginTop: 3 }}>{c.hint}</span>
          </span>
          <span aria-hidden="true" title={flipHint} style={{
            fontFamily: KSFonts.mono, fontSize: 16, color: KS.muted, lineHeight: 1,
            alignSelf: 'flex-start', marginTop: 2,
          }}>+</span>
        </span>
        {/* Rückseite */}
        <span className="anat-face" style={{
          position: 'absolute', inset: 0, backfaceVisibility: 'hidden', WebkitBackfaceVisibility: 'hidden',
          transform: 'rotateY(180deg)',
          background: KS.charcoal, border: `1px solid ${KS.charcoal}`, borderRadius: 12,
          padding: '13px 16px', display: 'flex', flexDirection: 'column', gap: 6,
          boxShadow: '0 18px 40px -18px rgba(73,70,72,0.55)',
        }}>
          <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
            <span style={{ fontFamily: KSFonts.mono, fontSize: 9.5, letterSpacing: 1, textTransform: 'uppercase', color: accent }}>{c.label}</span>
            <span aria-hidden="true" style={{ fontFamily: KSFonts.mono, fontSize: 15, color: 'rgba(248,247,246,0.55)', lineHeight: 1, transform: 'rotate(45deg)', display: 'inline-block' }}>+</span>
          </span>
          <span style={{ fontSize: 11, lineHeight: 1.45, color: 'rgba(248,247,246,0.92)', textWrap: 'pretty' }}>{c.back}</span>
        </span>
      </span>
    </button>
  );
}

// ── Sektion ──────────────────────────────────────────────────
function AgentAnatomie({ lang, accent, mobile }) {
  const t = ANAT_COPY[lang];
  const [active, setActive] = React.useState(null);
  const toggle = (id) => setActive(a => (a === id ? null : id));

  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') setActive(null); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, []);

  // Skalierung des Desktop-Diagramms auf die Containerbreite
  const outerRef = React.useRef(null);
  const [scale, setScale] = React.useState(1);
  React.useEffect(() => {
    const measure = () => {
      if (outerRef.current) setScale(Math.min(1, outerRef.current.clientWidth / ANAT_W));
    };
    measure();
    window.addEventListener('resize', measure);
    return () => window.removeEventListener('resize', measure);
  }, [mobile]);

  const wrap = { maxWidth: 1000, margin: '0 auto', padding: mobile ? '0 20px' : '0 32px' };

  return (
    <section style={{ ...wrap, padding: mobile ? '84px 20px' : '132px 32px', paddingTop: 0 }}>
      <style>{ANAT_CSS}</style>
      <div style={{ fontFamily: KSFonts.mono, fontSize: 11, letterSpacing: 1.5, textTransform: 'uppercase', color: accent, marginBottom: 28 }}>{t.kicker}</div>
      <h2 style={{ fontSize: mobile ? 30 : 40, fontWeight: 800, letterSpacing: -1.2, lineHeight: 1.05, color: KS.black, margin: 0, marginBottom: 14, textWrap: 'balance' }}>{t.title}</h2>
      <p style={{ fontSize: mobile ? 15 : 16.5, lineHeight: 1.6, color: KS.charcoal, margin: 0, maxWidth: 560, textWrap: 'pretty' }}>{t.intro}</p>

      {mobile ? (
        // ── Mobil: Avatar oben, Karten gestapelt, gleiche Flip-Interaktion ──
        <div style={{ marginTop: 36 }}>
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 24 }}>
            <PixelKilian size={150} idle flicker />
          </div>
          <div style={{ display: 'grid', gap: 12 }}>
            {ANAT_ITEMS.map(item => (
              <AnatCard
                key={item.id} item={item} lang={lang} accent={accent}
                active={active === item.id} onToggle={() => toggle(item.id)}
                flipHint={t.flipHint} growScale={1.04}
                style={{ position: 'relative', width: '100%' }}
              />
            ))}
          </div>
        </div>
      ) : (
        // ── Desktop: Diagramm mit Linien ──
        <div ref={outerRef} style={{ marginTop: 20, height: ANAT_H * scale }}>
          <div style={{
            position: 'relative', width: ANAT_W, height: ANAT_H,
            transform: `scale(${scale})`, transformOrigin: 'top left',
          }}>
            {/* Avatar */}
            <div style={{ position: 'absolute', left: ANAT_AV_X, top: ANAT_AV_Y, zIndex: 1 }}>
              <PixelKilian size={ANAT_AV_SIZE} idle flicker />
            </div>
            {/* Feine Linien */}
            <svg
              width={ANAT_W} height={ANAT_H} viewBox={`0 0 ${ANAT_W} ${ANAT_H}`}
              style={{ position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none', overflow: 'visible' }}
              aria-hidden="true"
            >
              {ANAT_ITEMS.map(item => {
                const { d, tx, ty } = anatLine(item);
                const on = active === item.id;
                return (
                  <g key={item.id}>
                    <path d={d} fill="none"
                      stroke={on ? accent : KS.charcoal}
                      strokeWidth={on ? 1.6 : 1}
                      strokeOpacity={on ? 0.9 : 0.22}
                      style={{ transition: 'stroke 240ms ease, stroke-opacity 240ms ease, stroke-width 240ms ease' }}
                    />
                    <circle cx={tx} cy={ty} r={3}
                      fill={on ? accent : KS.charcoal}
                      fillOpacity={on ? 1 : 0.35}
                      style={{ transition: 'fill 240ms ease, fill-opacity 240ms ease' }}
                    />
                  </g>
                );
              })}
            </svg>
            {/* Karten */}
            {ANAT_ITEMS.map(item => {
              const { x, y } = anatCardPos(item);
              return (
                <AnatCard
                  key={item.id} item={item} lang={lang} accent={accent}
                  active={active === item.id} onToggle={() => toggle(item.id)}
                  flipHint={t.flipHint}
                  style={{ position: 'absolute', left: x, top: y }}
                />
              );
            })}
          </div>
        </div>
      )}
    </section>
  );
}

const ANAT_CSS = `
.anat-card:hover { z-index: 5; }
.anat-card:not([aria-expanded="true"]):hover { transform: translateY(-2px); }
.anat-card:focus-visible { outline: 2px solid ${KS.coral}; outline-offset: 3px; border-radius: 12px; }
@media (prefers-reduced-motion: reduce) {
  .anat-card, .anat-inner { transition: none !important; }
}
`;

Object.assign(window, { AgentAnatomie });
