// App shell — state, routing between steps, edit-mode wiring.

const { useState, useEffect } = React;

const STORE_KEY = "tb_state_v1";
const HISTORY_KEY = "tb_history_v1";
const loadState = () => {
  try { return JSON.parse(localStorage.getItem(STORE_KEY) || "{}"); } catch { return {}; }
};
const saveState = (s) => localStorage.setItem(STORE_KEY, JSON.stringify(s));
const loadHistory = () => {
  try { return JSON.parse(localStorage.getItem(HISTORY_KEY) || "[]"); } catch { return []; }
};
const saveHistory = (h) => localStorage.setItem(HISTORY_KEY, JSON.stringify(h.slice(0, 20)));

function App() {
  const initial = loadState();
  const [step, setStep] = useState(initial.step ?? 0);
  const [form, setForm] = useState(initial.form ?? {
    company: "", industry: "", headcount: "", language: "EN", ats: "",
    websiteUrl: "", careerUrl: "",
    aeName: "", demoDate: "", country: "", logoDataUrl: "",
    brandColor: "", contactName: "", contactEmail: ""
  });
  const [suggested, setSuggested] = useState(initial.suggested ?? []);
  const [selected, setSelected] = useState(initial.selected ?? []);
  const [names, setNames] = useState(initial.names ?? {});
  const [deploy, setDeploy] = useState(initial.deploy ?? "netlify");
  const [building, setBuilding] = useState(false);

  // Tweaks
  const [tweaks, setTweaks] = useState(window.__TWEAKS__);
  const [tweaksOpen, setTweaksOpen] = useState(false);
  const [history, setHistory] = useState(loadHistory());
  const [historyOpen, setHistoryOpen] = useState(false);

  const pushHistory = () => {
    if (!form.company) return;
    const entry = {
      id: `b_${Date.now()}`,
      at: Date.now(),
      company: form.company,
      ae: form.aeName || "",
      demo: form.demoDate || "",
      country: form.country || "",
      useCaseCount: selected.length,
      snapshot: { form, selected, names, suggested },
    };
    const next = [entry, ...history.filter(h => h.company !== form.company)].slice(0, 20);
    setHistory(next);
    saveHistory(next);
  };

  const loadHistoryEntry = (entry) => {
    setForm(entry.snapshot.form);
    setSelected(entry.snapshot.selected || []);
    setNames(entry.snapshot.names || {});
    setSuggested(entry.snapshot.suggested || []);
    setStep(0);
    setHistoryOpen(false);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const duplicateHistoryEntry = (entry) => {
    loadHistoryEntry(entry);
    setForm({ ...entry.snapshot.form, company: "", websiteUrl: "", careerUrl: "", demoDate: "" });
  };

  useEffect(() => { applyTweaks(tweaks); }, [tweaks]);
  useEffect(() => {
    saveState({ step, form, selected, names, deploy, suggested });
  }, [step, form, selected, names, deploy, suggested]);

  // Edit-mode host integration
  useEffect(() => {
    const onMsg = (e) => {
      if (!e.data || typeof e.data !== "object") return;
      if (e.data.type === "__activate_edit_mode") setTweaksOpen(true);
      if (e.data.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", onMsg);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);
  useEffect(() => {
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: tweaks }, "*");
  }, [tweaks]);

  const go = (n) => {
    setStep(n);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  return (
    <div className="app">
      <div className="topbar">
        <Logo />
        <div className="topbar-meta">
          {tweaks.showWatermark && <span className="chip"><span className="dot" /> Internal tool · AE Tenant Builder</span>}
          <div className="recent-wrap">
            <button className="btn btn-ghost" onClick={() => setHistoryOpen(v => !v)}
              style={{ fontSize: 12, display: "inline-flex", alignItems: "center", gap: 6 }}>
              <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 15 14"/></svg>
              Recent {history.length > 0 && <span className="recent-count">{history.length}</span>}
            </button>
            {historyOpen && (
              <RecentBuilds history={history} onLoad={loadHistoryEntry} onDuplicate={duplicateHistoryEntry}
                onClear={() => { if (confirm("Clear all recent builds?")) { setHistory([]); saveHistory([]); }}}
                onClose={() => setHistoryOpen(false)} />
            )}
          </div>
          <span style={{ color: "var(--ink-4)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.04em" }}>
            v0.4.2 · TALENTRY
          </span>
          <button className="btn btn-ghost" onClick={() => {
            if (confirm("Reset the wizard? This clears everything you've entered.")) {
              localStorage.removeItem(STORE_KEY);
              location.reload();
            }
          }} style={{ fontSize: 12 }}>Reset</button>
          <button className="btn btn-ghost" onClick={() => {
            if (window.__AUTH0_CLIENT__) {
              window.__AUTH0_CLIENT__.logout({
                logoutParams: { returnTo: window.location.origin }
              });
            }
          }} style={{ fontSize: 12, color: "var(--ink-4)" }} title="Sign out">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
            Sign out
          </button>
        </div>
      </div>

      <div className="stage-wrap">
        <EditorialPanel step={step} form={form} selected={selected} onStepClick={go} maxStep={step} />

        <main className="stage" data-screen-label={`0${step+1} ${STEPS[step].t}`}>
          {step === 0 && (
            <Step1 form={form} setForm={setForm} onNext={() => go(1)}
              onImportUseCases={(ids) => {
                setSelected(prev => [...new Set([...(prev || []), ...ids])]);
                setSuggested(ids);
              }} />
          )}
          {step === 1 && (
            <Step2 selected={selected} setSelected={setSelected} suggested={suggested}
              onNext={() => go(2)} onBack={() => go(0)} />
          )}
          {step === 2 && (
            <Step3 form={form} selected={selected} names={names} setNames={setNames}
              onNext={() => go(3)} onBack={() => go(1)} />
          )}
          {step === 3 && (
            <Review form={form} selected={selected} names={names}
              deploy={deploy} setDeploy={setDeploy}
              onBack={() => go(2)} onBuild={() => setBuilding(true)} />
          )}
        </main>
      </div>

      {building && (
        <BuildingModal
          form={form} selected={selected} names={names} deploy={deploy}
          onStart={pushHistory}
          onClose={() => setBuilding(false)} />
      )}

      {tweaksOpen && (
        <TweaksPanel tweaks={tweaks} setTweaks={setTweaks}
          onClose={() => setTweaksOpen(false)} />
      )}
    </div>
  );
}

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