// Terminal easter egg + Tweaks panel + Main App

const { useState: useS3, useEffect: useE3, useRef: useR3 } = React;

// =========================================================
// Terminal easter egg (press "/")
// =========================================================
function Terminal({ open, onClose, data, lang }) {
  const [history, setHistory] = useS3([
    { type: "out", text: "ayoub@portfolio:~$ welcome" },
    { type: "acc", text: "Type `help` for available commands. ESC to close." },
  ]);
  const [input, setInput] = useS3("");
  const inputRef = useR3(null);
  const bodyRef = useR3(null);

  useE3(() => {
    if (open && inputRef.current) inputRef.current.focus();
  }, [open]);

  useE3(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [history]);

  useE3(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  const run = (cmd) => {
    const out = [{ type: "cmd", text: cmd }];
    const c = cmd.trim().toLowerCase();
    if (!c) {
      // skip
    } else if (c === "help") {
      out.push({ type: "out", text: "Available commands:" });
      out.push({ type: "out", text: "  whoami        — about me" });
      out.push({ type: "out", text: "  ls projects   — list projects" });
      out.push({ type: "out", text: "  cat <project> — show project details" });
      out.push({ type: "out", text: "  skills        — top skills" });
      out.push({ type: "out", text: "  contact       — how to reach me" });
      out.push({ type: "out", text: "  resume        — download resume" });
      out.push({ type: "out", text: "  date          — current time" });
      out.push({ type: "out", text: "  clear         — clear screen" });
      out.push({ type: "out", text: "  sudo hire-me  — surprise" });
    } else if (c === "whoami") {
      out.push({ type: "out", text: "Ayoub Alouane · Data Engineer & Full-Stack Builder" });
      out.push({ type: "out", text: "ENSET Mohammedia · Big Data & Cloud Computing · 2024–present" });
    } else if (c === "ls projects" || c === "ls") {
      data.projects.forEach(p => out.push({ type: "out", text: `  ${p.name.padEnd(20)} ${p.stack.join(", ")}` }));
    } else if (c.startsWith("cat ")) {
      const name = c.slice(4).trim();
      const p = data.projects.find(x => x.name.toLowerCase().includes(name) || x.id === name);
      if (p) {
        out.push({ type: "acc", text: `── ${p.name} ──` });
        out.push({ type: "out", text: p.tagline[lang] });
        out.push({ type: "out", text: `stack: ${p.stack.join(" · ")}` });
      } else {
        out.push({ type: "err", text: `cat: ${name}: no such project` });
      }
    } else if (c === "skills") {
      data.skills.slice(0, 3).forEach(cat => {
        out.push({ type: "acc", text: cat.category[lang] });
        cat.items.slice(0, 5).forEach(it => {
          const bars = "█".repeat(Math.floor(it.level / 10)) + "░".repeat(10 - Math.floor(it.level / 10));
          out.push({ type: "out", text: `  ${it.name.padEnd(16)} ${bars} ${it.level}` });
        });
      });
    } else if (c === "contact" || c === "email") {
      out.push({ type: "out", text: `email:    ${data.meta.email}` });
      out.push({ type: "out", text: `github:   ${data.meta.github}` });
      out.push({ type: "out", text: `linkedin: ${data.meta.linkedin}` });
    } else if (c === "resume" || c === "cv") {
      out.push({ type: "out", text: "Opening résumé..." });
      window.open("uploads/Ayoub-Resume.v4.pdf", "_blank");
    } else if (c === "date") {
      out.push({ type: "out", text: new Date().toString() });
    } else if (c === "clear" || c === "cls") {
      setHistory([]); setInput(""); return;
    } else if (c === "sudo hire-me") {
      out.push({ type: "acc", text: "Permission granted ✓" });
      out.push({ type: "out", text: `Reach out to ${data.meta.email} or use the contact section.` });
    } else if (c === "exit" || c === "q" || c === "quit") {
      onClose(); return;
    } else {
      out.push({ type: "err", text: `command not found: ${c}. Try \`help\`.` });
    }
    setHistory(h => [...h, ...out]);
    setInput("");
  };

  if (!open) return null;
  return (
    <div className="terminal-overlay" onClick={onClose}>
      <div className="terminal" onClick={(e) => e.stopPropagation()}>
        <div className="terminal-head">
          <span className="dot r"></span>
          <span className="dot y"></span>
          <span className="dot g"></span>
          <span className="title">ayoub@portfolio · ~/zsh</span>
        </div>
        <div className="terminal-body" ref={bodyRef}>
          {history.map((l, i) => (
            <div key={i} className={`terminal-line ${l.type}`}>{l.text}</div>
          ))}
          <div className="terminal-input-row">
            <span>λ</span>
            <input
              ref={inputRef}
              className="terminal-input"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") run(input); }}
              spellCheck={false}
              autoFocus
            />
          </div>
        </div>
      </div>
    </div>
  );
}

// =========================================================
// Tweaks panel
// =========================================================
function PortfolioTweaks() {
  // Only render if running inside the editor (parented in an iframe).
  // When the file is hosted standalone, this stays hidden so end users can't tweak.
  const inEditor = typeof window !== "undefined" && window.parent && window.parent !== window;
  if (!inEditor) return null;

  const [tweaks, setTweak] = useTweaks(window.PORTFOLIO_TWEAKS_DEFAULTS || {
    theme: "light",
    accent: "lime",
    fontPair: "modern",
    density: "cozy",
    motion: 1,
    heroVariant: "default",
  });

  // Apply tweaks to <html>
  useE3(() => {
    const root = document.documentElement;
    root.setAttribute("data-theme", tweaks.theme);
    root.setAttribute("data-accent", tweaks.accent);
    root.setAttribute("data-fontpair", tweaks.fontPair);
    root.setAttribute("data-density", tweaks.density);
    root.setAttribute("data-motion", tweaks.motion);
    root.setAttribute("data-hero", tweaks.heroVariant);
    // Notify the rest of the app
    window.__PORTFOLIO_TWEAKS = tweaks;
    window.dispatchEvent(new CustomEvent("portfolio:tweaks", { detail: tweaks }));
  }, [tweaks]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Theme">
        <TweakRadio
          label="Mode"
          value={tweaks.theme}
          onChange={(v) => setTweak("theme", v)}
          options={[{ value: "light", label: "Light" }, { value: "dark", label: "Dark" }]}
        />
        <TweakSelect
          label="Accent"
          value={tweaks.accent}
          onChange={(v) => setTweak("accent", v)}
          options={[
            { value: "lime", label: "Lime (default)" },
            { value: "cyan", label: "Cyan" },
            { value: "amber", label: "Amber" },
            { value: "magenta", label: "Magenta" },
            { value: "violet", label: "Violet" },
          ]}
        />
      </TweakSection>

      <TweakSection title="Typography">
        <TweakSelect
          label="Font pairing"
          value={tweaks.fontPair}
          onChange={(v) => setTweak("fontPair", v)}
          options={[
            { value: "modern", label: "Inter Tight + Inter" },
            { value: "editorial", label: "Instrument Serif + Inter" },
            { value: "techno", label: "JetBrains Mono + Inter" },
            { value: "grotesk", label: "Space Grotesk" },
          ]}
        />
      </TweakSection>

      <TweakSection title="Layout">
        <TweakRadio
          label="Density"
          value={tweaks.density}
          onChange={(v) => setTweak("density", v)}
          options={[
            { value: "compact", label: "Compact" },
            { value: "cozy", label: "Cozy" },
            { value: "comfortable", label: "Comfy" },
          ]}
        />
        <TweakSelect
          label="Hero variant"
          value={tweaks.heroVariant}
          onChange={(v) => setTweak("heroVariant", v)}
          options={[
            { value: "default", label: "Portrait + stats (default)" },
            { value: "stats", label: "Stats-led / oversized name" },
            { value: "manifesto", label: "Manifesto / serif" },
          ]}
        />
      </TweakSection>

      <TweakSection title="Motion">
        <TweakSlider
          label="Animation intensity"
          value={tweaks.motion}
          onChange={(v) => setTweak("motion", v)}
          min={0}
          max={2}
          step={0.25}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

// =========================================================
// Main App
// =========================================================
function App() {
  const data = window.PORTFOLIO_DATA;
  const [lang, setLang] = useS3(() => localStorage.getItem("portfolio:lang") || "en");
  const [theme, setThemeState] = useS3(() => document.documentElement.getAttribute("data-theme") || "light");
  const [terminalOpen, setTerminalOpen] = useS3(false);

  const ui = data.ui[lang];

  useE3(() => {
    localStorage.setItem("portfolio:lang", lang);
    document.documentElement.setAttribute("lang", lang);
  }, [lang]);

  // Hook theme button to tweak system
  const setTheme = (t) => {
    setThemeState(t);
    document.documentElement.setAttribute("data-theme", t);
    // Also persist via tweaks bridge if available
    if (window.parent !== window) {
      window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { theme: t } }, "*");
    }
  };

  // Listen to tweaks changes for theme keep-in-sync
  useE3(() => {
    const onTweaks = (e) => {
      if (e.detail && e.detail.theme && e.detail.theme !== theme) {
        setThemeState(e.detail.theme);
      }
    };
    window.addEventListener("portfolio:tweaks", onTweaks);
    return () => window.removeEventListener("portfolio:tweaks", onTweaks);
  }, [theme]);

  // Terminal hotkey: "/"
  useE3(() => {
    const onKey = (e) => {
      const tag = (e.target && e.target.tagName) || "";
      if (e.key === "/" && tag !== "INPUT" && tag !== "TEXTAREA") {
        e.preventDefault();
        setTerminalOpen(true);
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  return (
    <div className="app">
      <BackgroundGrid />
      <CustomCursor />
      <Topbar lang={lang} setLang={setLang} theme={theme} setTheme={setTheme} ui={ui} name={data.meta.name} />

      <Hero data={data} lang={lang} ui={ui} />
      <About data={data} lang={lang} ui={ui} />
      <Experience data={data} lang={lang} ui={ui} />
      <Projects data={data} lang={lang} ui={ui} />
      <Skills data={data} lang={lang} ui={ui} />
      <Education data={data} lang={lang} ui={ui} />
      <Certifications data={data} lang={lang} ui={ui} />
      <Languages data={data} lang={lang} ui={ui} />
      <NowSection data={data} lang={lang} ui={ui} />
      <Testimonials data={data} lang={lang} ui={ui} />
      <Contact data={data} lang={lang} ui={ui} />
      <Footer ui={ui} lang={lang} />

      <Terminal open={terminalOpen} onClose={() => setTerminalOpen(false)} data={data} lang={lang} />
      <PortfolioTweaks />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
