// ============================================================
// extras.jsx — cookie modal, terminal easter egg
// ============================================================

// ------------------------------------------------------------
// CookieNoticeModal — clinical legal-speak with sealed-bid clause
// ------------------------------------------------------------
function CookieNoticeModal({ onAccept }) {
  return (
    <div className="cookie-shroud">
      <div className="cookie-modal">
        <span className="corner tl" style={{position:"absolute", width:10, height:10, top:-1, left:-1, borderRight:0, borderBottom:0, border:"1px solid var(--phosphor-700)"}}/>
        <span className="corner tr" style={{position:"absolute", width:10, height:10, top:-1, right:-1, borderLeft:0, borderBottom:0, border:"1px solid var(--phosphor-700)"}}/>
        <span className="corner bl" style={{position:"absolute", width:10, height:10, bottom:-1, left:-1, borderRight:0, borderTop:0, border:"1px solid var(--phosphor-700)"}}/>
        <span className="corner br" style={{position:"absolute", width:10, height:10, bottom:-1, right:-1, borderLeft:0, borderTop:0, border:"1px solid var(--phosphor-700)"}}/>

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 18 }}>
          <span className="eyebrow" style={{ color: "var(--amber-500)" }}>COOKIE NOTICE</span>
        </div>

        <h2 style={{
          fontFamily: "var(--font-display)", fontSize: 28, fontWeight: 700,
          letterSpacing: "0.04em", textTransform: "uppercase",
          margin: "0 0 18px", color: "var(--bone-100)", lineHeight: 1.1,
        }}>
          We use a minimal session cookie.
        </h2>

        <p style={{ margin: "0 0 18px", color: "var(--steel-100)", fontSize: 13, lineHeight: 1.65, fontFamily: "var(--font-mono)", letterSpacing: "0.02em" }}>
          This site stores a session identifier in your browser to remember
          your preferences. We don't use third-party analytics or advertising
          trackers.
        </p>

        <div style={{ display: "flex", gap: 12, justifyContent: "flex-end" }}>
          <a className="btn solid" onClick={onAccept}>Got it</a>
        </div>
      </div>
    </div>
  );
}

// ------------------------------------------------------------
// Terminal Easter Egg — fixed bottom-right; activated by `~` or button
// ------------------------------------------------------------
function TerminalEgg({ afterhours, setAfterhours }) {
  const [open, setOpen] = React.useState(false);
  const [lines, setLines] = React.useState([
    { t: "FL-OS / OPERATOR CONSOLE · REV 4.12.0", c: "amber" },
    { t: "Authenticated as: GUEST (read-only)", c: "muted" },
    { t: "Type 'help' for command list.", c: "muted" },
    { t: "", c: "muted" },
  ]);
  const [input, setInput] = React.useState("");
  const inputRef = React.useRef(null);
  const scrollRef = React.useRef(null);

  // Keyboard toggle
  React.useEffect(() => {
    const k = (e) => {
      if (e.key === "`" || e.key === "~") {
        if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA") return;
        e.preventDefault();
        setOpen(o => !o);
      }
      if (e.key === "Escape") setOpen(false);
    };
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, []);

  React.useEffect(() => {
    if (open && inputRef.current) setTimeout(() => inputRef.current.focus(), 60);
  }, [open]);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [lines]);

  const print = (t, c="phos") => setLines(L => [...L, { t, c }]);

  const handle = (raw) => {
    const cmd = raw.trim();
    setLines(L => [...L, { t: "guest@FL-OS > " + cmd, c: "input" }]);
    if (!cmd) return;
    const [c, ...args] = cmd.toLowerCase().split(/\s+/);

    if (c === "help") {
      print("Available commands:", "amber");
      print("  help                              — this list");
      print("  whoami                            — current operator");
      print("  status                            — facility status");
      print("  ls                                — catalogue entries");
      print("  cat <code>                        — inspect a catalogue entry");
      print("  ping <host>                       — reachability check");
      print("  uptime                            — system uptime");
      print("  date                              — local time");
      print("  motd                              — message of the day");
      print("  afterhours                        — toggle dark accent mode");
      print("  clear                             — clear terminal");
      print("  exit                              — close console");
    } else if (c === "clear") {
      setLines([]);
    } else if (c === "exit") {
      setOpen(false);
    } else if (c === "whoami") {
      print("guest (uid=1000, gid=1000, groups=read-only)");
    } else if (c === "uptime") {
      print("up 412 days, 06:14:22, load: 0.42 0.38 0.36 — nominal");
    } else if (c === "date") {
      print(new Date().toString());
    } else if (c === "status") {
      print("Model           Class    Envelope     Status", "amber");
      print("model-01        0        +0.0 K       NOMINAL", "phos");
      print("model-02        0        +0.1 K       NOMINAL", "phos");
      print("model-aa        3        +0.3 K       NOMINAL", "phos");
    } else if (c === "ls") {
      ["FL-MHA", "FL-CLM", "FL-CHP", "FL-AMB"].forEach((n,i) => {
        print(`  ${String(i+1).padStart(2,"0")}  ${n}`, "phos");
      });
    } else if (c === "cat") {
      const code = (args[0] || "").toUpperCase();
      if (code === "FL-MHA") { print("FL-MHA / L · Modular hairpin assembly line · lead: as appropriate · rev B"); }
      else if (code === "FL-CLM") { print("FL-CLM / S · Closed-loop req-output sim · lead: to be confirmed · rev A"); }
      else if (code === "FL-CHP") { print("FL-CHP / R · CHP winding rapid prototype set · lead: upon agreement · rev B"); }
      else if (code === "FL-AMB") { print("FL-AMB / B · Bifilar AMB coils · lead: subject to scope · rev A"); }
      else {
        print(`cat: ${code || "?"}: catalogue entry not found.`, "hazard");
      }
    } else if (c === "ping") {
      const host = args[0] || "fusionaria.cl";
      print(`PING ${host}: 56 data bytes`);
      print(`64 bytes from ${host}: icmp_seq=0 ttl=64 time=0.428 ms`, "phos");
      print(`64 bytes from ${host}: icmp_seq=1 ttl=64 time=0.402 ms`, "phos");
      print(`64 bytes from ${host}: icmp_seq=2 ttl=64 time=0.415 ms`, "phos");
      print(`--- ${host} ping statistics ---`, "amber");
      print(`3 packets transmitted, 3 received, 0% packet loss`, "amber");
    } else if (c === "motd") {
      print("// MESSAGE OF THE DAY", "amber");
      print('"Building better machines."', "phos");
    } else if (c === "afterhours") {
      setAfterhours(a => !a);
      print(afterhours ? "Dark accent mode off." : "Dark accent mode on.", "phos");
    } else {
      print(`-fl-os: ${c}: command not found`, "hazard");
    }
  };

  const onKey = (e) => {
    if (e.key === "Enter") {
      handle(input);
      setInput("");
    }
  };

  const colorFor = (c) => ({
    phos: "var(--phosphor-500)", amber: "var(--amber-500)",
    muted: "var(--fg-muted)", hazard: "var(--hazard-red)",
    anom: "var(--offspec-500)", input: "var(--bone-100)",
  }[c] || "var(--phosphor-500)");

  return (
    <>
      {/* trigger bubble */}
      {!open && (
        <button onClick={() => setOpen(true)}
                style={{
                  position: "fixed", bottom: 18, left: 18, zIndex: 8000,
                  width: 44, height: 44,
                  background: "var(--black-200)",
                  border: "1px solid var(--phosphor-700)",
                  color: "var(--phosphor-500)",
                  fontFamily: "var(--font-mono)", fontSize: 18,
                  cursor: "pointer", padding: 0,
                  boxShadow: "0 0 8px #33ff6633",
                }} title="Open FL-OS console (press ~)">
          ▣
        </button>
      )}

      {open && (
        <div style={{
          position: "fixed", left: 18, bottom: 18, zIndex: 8500,
          width: 560, height: 380,
          background: "var(--black-100)",
          border: "1px solid var(--phosphor-700)",
          boxShadow: "0 0 40px #33ff6633, inset 0 0 24px #00000099",
          display: "flex", flexDirection: "column",
          fontFamily: "var(--font-terminal)",
        }}>
          {/* title bar */}
          <div style={{
            background: "var(--black-200)", borderBottom: "1px solid var(--phosphor-700)",
            padding: "6px 12px", display: "flex", justifyContent: "space-between", alignItems: "center",
            fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.22em",
            textTransform: "uppercase", color: "var(--fg-muted)",
          }}>
            <span>FL-OS · tty 0 · guest@███████:~$</span>
            <div style={{ display: "flex", gap: 6 }}>
              <button onClick={() => setLines([])}
                      style={{ background: "transparent", border: "1px solid var(--border-default)", color: "var(--fg-muted)", padding: "1px 6px", cursor: "pointer", fontSize: 10 }}>CLR</button>
              <button onClick={() => setOpen(false)}
                      style={{ background: "transparent", border: "1px solid var(--border-default)", color: "var(--hazard-red)", padding: "1px 6px", cursor: "pointer", fontSize: 10 }}>✕</button>
            </div>
          </div>

          {/* body */}
          <div ref={scrollRef} onClick={() => inputRef.current?.focus()}
               style={{
                 flex: 1, overflowY: "auto", padding: 12,
                 fontFamily: "var(--font-terminal)", fontSize: 18, lineHeight: 1.2,
                 color: "var(--phosphor-500)", textShadow: "0 0 4px #33ff6699",
                 background: "radial-gradient(ellipse at center, #001a0533, transparent 70%), var(--black-100)",
                 position: "relative",
               }}>
            {lines.map((l, i) => (
              <div key={i} style={{ color: colorFor(l.c), whiteSpace: "pre-wrap" }}>
                {l.t || "\u00A0"}
              </div>
            ))}
            {/* scanline overlay inside the term */}
            <div style={{ position: "absolute", inset: 0, pointerEvents: "none",
                          background: "var(--scanline-bg)", opacity: 0.5, mixBlendMode: "multiply" }}/>
          </div>

          {/* input */}
          <div style={{ borderTop: "1px solid var(--phosphor-700)", padding: "6px 12px",
                        display: "flex", alignItems: "center", gap: 6,
                        background: "var(--black-050)" }}>
            <span style={{ color: "var(--phosphor-500)", fontFamily: "var(--font-terminal)", fontSize: 18, textShadow: "0 0 4px #33ff6699" }}>guest@FL-OS &gt;</span>
            <input ref={inputRef} value={input} onChange={e => setInput(e.target.value)} onKeyDown={onKey}
                   spellCheck={false} autoComplete="off"
                   style={{
                     flex: 1, background: "transparent", border: 0, outline: "none",
                     color: "var(--phosphor-500)", textShadow: "0 0 4px #33ff6699",
                     fontFamily: "var(--font-terminal)", fontSize: 18, padding: 0,
                     caretColor: "var(--phosphor-500)",
                   }}/>
          </div>
        </div>
      )}
    </>
  );
}

Object.assign(window, { CookieNoticeModal, TerminalEgg });
