/* === AetherSort animated thumbnail ===
   Files appear in _eingang, get classified by Claude (badge),
   then animate to their target folder. Loops. */

const AETHER_FILES = [
  { name: "Mietvertrag_2025.pdf",    folder: "Mietverträge/2025", row: 2, color: "var(--accent)" },
  { name: "Strom_Vattenfall.pdf",     folder: "Nebenkosten/Strom",  row: 5, color: "var(--accent)" },
  { name: "Wasser_BWB.pdf",           folder: "Nebenkosten/Wasser", row: 6, color: "var(--accent)" },
  { name: "Rechnung_Hausmeister.pdf", folder: "Rechnungen",         row: 7, color: "var(--accent)" },
  { name: "Mietvertrag_Müller.pdf",   folder: "Mietverträge/2024", row: 1, color: "var(--accent)" },
];

const AetherSortAnim = () => {
  const [activeIdx, setActiveIdx] = React.useState(-1);
  const [phase, setPhase] = React.useState("idle"); // idle | scanning | flying | done
  const [counts, setCounts] = React.useState({ 1: 14, 2: 22, 5: 0, 6: 0, 7: 0 });
  const [inboxCount, setInboxCount] = React.useState(5);

  React.useEffect(() => {
    let canceled = false;
    let t1, t2, t3;

    const runOne = (i) => {
      if (canceled) return;
      setActiveIdx(i);
      setPhase("scanning");
      t1 = setTimeout(() => {
        if (canceled) return;
        setPhase("flying");
        t2 = setTimeout(() => {
          if (canceled) return;
          // Increment target folder counter, decrement inbox
          const f = AETHER_FILES[i];
          setCounts((c) => ({ ...c, [f.row]: (c[f.row] || 0) + 1 }));
          setInboxCount((n) => Math.max(0, n - 1));
          setPhase("done");
          t3 = setTimeout(() => {
            if (canceled) return;
            const next = i + 1;
            if (next < AETHER_FILES.length) {
              runOne(next);
            } else {
              // restart loop after a beat
              setTimeout(() => {
                if (canceled) return;
                setCounts({ 1: 14, 2: 22, 5: 0, 6: 0, 7: 0 });
                setInboxCount(5);
                setActiveIdx(-1);
                setPhase("idle");
                setTimeout(() => !canceled && runOne(0), 600);
              }, 1200);
            }
          }, 250);
        }, 900);
      }, 700);
    };

    const startTimer = setTimeout(() => runOne(0), 500);
    return () => {
      canceled = true;
      clearTimeout(startTimer);
      clearTimeout(t1);
      clearTimeout(t2);
      clearTimeout(t3);
    };
  }, []);

  // Folder rows — index = row in tree
  const treeRows = [
    { kind: "label", text: "~/Aktenschrank/", muted: true },
    { kind: "folder", text: "├─ Mietverträge/" },
    { kind: "sub",    text: "│  ├─ 2024/", row: 1 },
    { kind: "sub",    text: "│  └─ 2025/", row: 2 },
    { kind: "folder", text: "├─ Nebenkosten/" },
    { kind: "sub",    text: "│  ├─ Strom/",  row: 5 },
    { kind: "sub",    text: "│  └─ Wasser/", row: 6 },
    { kind: "folder", text: "├─ Rechnungen/", row: 7 },
  ];

  // Geometry constants (relative to thumb 400x300 viewBox-ish)
  const lineH = 18;
  const treeTop = 30;
  const treeLeft = 24;
  const inboxX = 250;
  const inboxY = 220;

  return (
    <div style={{
      position: "absolute", inset: 0,
      background: "var(--bg)",
      overflow: "hidden",
      fontFamily: "var(--font-mono)",
      fontSize: 10,
      color: "var(--fg)",
    }}>
      {/* TREE */}
      <div style={{ position: "absolute", top: treeTop, left: treeLeft, lineHeight: `${lineH}px` }}>
        {treeRows.map((r, idx) => {
          const isTarget = phase === "flying" && activeIdx >= 0 && AETHER_FILES[activeIdx].row === r.row;
          const isLanded = phase === "done" && activeIdx >= 0 && AETHER_FILES[activeIdx].row === r.row;
          const highlight = isTarget || isLanded;
          return (
            <div key={idx} style={{
              color: r.muted ? "var(--fg-muted)" : "var(--fg)",
              paddingLeft: r.kind === "sub" ? 0 : 0,
              transition: "color 240ms",
              ...(highlight && {
                color: "var(--accent)",
              }),
            }}>
              {r.text}
              {r.row != null && (
                <span style={{
                  color: highlight ? "var(--accent)" : "var(--fg-muted)",
                  marginLeft: 8,
                  fontWeight: highlight ? 700 : 400,
                  transition: "all 200ms",
                }}>
                  ● {counts[r.row] || 0}
                </span>
              )}
              {/* Pulse on landing */}
              {isLanded && (
                <span style={{
                  display: "inline-block",
                  marginLeft: 8,
                  width: 6, height: 6,
                  borderRadius: "50%",
                  background: "var(--accent)",
                  animation: "aetherPulse 600ms ease-out",
                }} />
              )}
            </div>
          );
        })}
      </div>

      {/* INBOX */}
      <div style={{
        position: "absolute",
        bottom: 14, left: 24,
        display: "flex", alignItems: "center", gap: 6,
      }}>
        <span style={{
          background: inboxCount > 0 ? "var(--accent)" : "var(--fg-muted)",
          color: "var(--bg)",
          padding: "1px 5px",
          fontWeight: 600,
          transition: "background 240ms",
        }}>_eingang/</span>
        <span style={{ color: "var(--fg-muted)" }}>{inboxCount}</span>
      </div>

      {/* FILE — current in flight */}
      {AETHER_FILES.map((f, i) => {
        if (i !== activeIdx) return null;
        // Start position (inbox), end position (target tree row)
        const startX = inboxX;
        const startY = inboxY;
        // approximate target row Y in tree
        const targetY = treeTop + lineH * (f.row + 0.1) - 4;
        const targetX = treeLeft + 80;

        const isFlying = phase === "flying";
        const isDone   = phase === "done";

        const x = isFlying || isDone ? targetX : startX;
        const y = isFlying || isDone ? targetY : startY;
        const opacity = phase === "scanning" ? 1 : isFlying ? 1 : isDone ? 0 : 1;
        const scale = isDone ? 0.4 : 1;

        return (
          <div key={i} style={{
            position: "absolute",
            left: x, top: y,
            transform: `translate(0,0) scale(${scale})`,
            transformOrigin: "left center",
            opacity,
            transition: "left 820ms cubic-bezier(0.7, 0, 0.2, 1), top 820ms cubic-bezier(0.6, -0.1, 0.2, 1), opacity 280ms ease-out, transform 320ms ease-out",
            display: "flex",
            alignItems: "center",
            gap: 6,
            background: "var(--bg)",
            border: "1px solid var(--accent)",
            padding: "4px 7px",
            zIndex: 5,
            boxShadow: "0 6px 16px -4px rgba(15,15,14,0.18)",
            whiteSpace: "nowrap",
          }}>
            {/* file glyph */}
            <svg width="9" height="11" viewBox="0 0 9 11" style={{ flexShrink: 0 }}>
              <path d="M0 0 H6 L9 3 V11 H0 Z" fill="var(--accent)" opacity="0.18" />
              <path d="M0 0 H6 L9 3 V11 H0 Z M6 0 V3 H9" stroke="var(--accent)" strokeWidth="0.8" fill="none" />
            </svg>
            <span style={{ color: "var(--fg)", fontSize: 9 }}>{f.name}</span>
          </div>
        );
      })}

      {/* CLAUDE BADGE — appears during scanning */}
      {phase === "scanning" && activeIdx >= 0 && (
        <div style={{
          position: "absolute",
          left: inboxX,
          top: inboxY - 28,
          display: "flex",
          alignItems: "center",
          gap: 5,
          padding: "3px 6px",
          background: "var(--fg)",
          color: "var(--bg)",
          fontSize: 8,
          letterSpacing: "0.08em",
          textTransform: "uppercase",
          fontWeight: 600,
          animation: "aetherFade 700ms ease-out",
          zIndex: 6,
          whiteSpace: "nowrap",
        }}>
          <span style={{
            width: 5, height: 5, borderRadius: "50%",
            background: "var(--accent)",
            animation: "aetherBlink 600ms ease-in-out infinite",
          }} />
          <span>Claude · klassifiziert →</span>
          <span style={{ color: "var(--accent)" }}>{AETHER_FILES[activeIdx].folder}</span>
        </div>
      )}

      {/* SCAN BEAM during scanning */}
      {phase === "scanning" && (
        <div style={{
          position: "absolute",
          left: inboxX - 4, top: inboxY - 2,
          width: 200, height: 16,
          background: "linear-gradient(90deg, transparent, var(--accent), transparent)",
          opacity: 0.35,
          animation: "aetherScan 700ms ease-in-out",
          pointerEvents: "none",
          zIndex: 4,
        }} />
      )}

      {/* Footer label */}
      <div style={{
        position: "absolute", bottom: 14, right: 14,
        fontSize: 9, color: "var(--fg-muted)",
        letterSpacing: "0.08em", textTransform: "uppercase",
      }}>
        claude-haiku · lokal
      </div>
    </div>
  );
};

window.AetherSortAnim = AetherSortAnim;
