// OrchestAI — App shell (auth, sidebar, topbar, routing)
const { useState: useState_A, useEffect: useEffect_A, useMemo: useMemo_A } = React;

// ---------- Design tokens ----------
const ACCENT_MAP = {
  lime:   { accent: "oklch(0.82 0.18 130)", sub: "oklch(0.96 0.06 130)", ink: "oklch(0.28 0.10 130)" },
  cobalt: { accent: "oklch(0.78 0.18 242)", sub: "oklch(0.96 0.04 242)", ink: "oklch(0.36 0.17 252)" },
  coral:  { accent: "oklch(0.80 0.18 28)",  sub: "oklch(0.96 0.04 28)",  ink: "oklch(0.45 0.17 28)" },
  amber:  { accent: "oklch(0.88 0.18 85)",  sub: "oklch(0.97 0.06 85)",  ink: "oklch(0.48 0.13 70)" }
};

const TWEAKS_DEFAULTS = { lang: "es", theme: "light", accent: "lime", density: "cozy" };

function applyTweaks(tw) {
  const root = document.documentElement;
  const a = ACCENT_MAP[tw.accent] || ACCENT_MAP.lime;
  root.style.setProperty("--oai-accent",     a.accent);
  root.style.setProperty("--oai-accent-sub", a.sub);
  root.style.setProperty("--oai-accent-ink", a.ink);
  const dark = tw.theme === "dark";
  root.style.setProperty("--oai-bg",          dark ? "oklch(0.16 0.012 265)" : "oklch(0.985 0.003 85)");
  root.style.setProperty("--oai-bg-raised",   dark ? "oklch(0.20 0.013 265)" : "oklch(1 0 0)");
  root.style.setProperty("--oai-bg-elev",     dark ? "oklch(0.20 0.013 265)" : "oklch(1 0 0)");
  root.style.setProperty("--oai-bg-sunk",     dark ? "oklch(0.14 0.011 265)" : "oklch(0.965 0.004 85)");
  root.style.setProperty("--oai-ink",         dark ? "oklch(0.96 0.005 265)" : "oklch(0.22 0.015 265)");
  root.style.setProperty("--oai-ink-2",       dark ? "oklch(0.78 0.01 265)"  : "oklch(0.42 0.015 265)");
  root.style.setProperty("--oai-ink-3",       dark ? "oklch(0.58 0.01 265)"  : "oklch(0.62 0.012 265)");
  root.style.setProperty("--oai-line",        dark ? "oklch(0.28 0.012 265)" : "oklch(0.92 0.006 265)");
  root.style.setProperty("--oai-line-2",      dark ? "oklch(0.34 0.014 265)" : "oklch(0.88 0.008 265)");
  root.style.setProperty("--oai-line-soft",   dark ? "oklch(0.26 0.01 265)"  : "oklch(0.94 0.004 85)");
  root.style.setProperty("--oai-s-4", tw.density === "compact" ? "10px" : "12px");
  root.style.setProperty("--oai-s-5", tw.density === "compact" ? "14px" : "16px");
  root.style.setProperty("--oai-s-6", tw.density === "compact" ? "18px" : "24px");
}

// ---------- Password gate ----------
const ACCESS_KEY = "oai_access_v1";

function PagePassword({ onUnlock }) {
  const [pw, setPw] = useState_A("");
  const [error, setError] = useState_A(false);

  const submit = (e) => {
    e.preventDefault();
    if (pw === "orchestai2026") {
      localStorage.setItem(ACCESS_KEY, "1");
      onUnlock();
    } else {
      setError(true);
      setPw("");
      setTimeout(() => setError(false), 2000);
    }
  };

  return (
    <div style={{
      minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center",
      background: "var(--oai-bg)", padding: 24
    }}>
      <div style={{ width: "100%", maxWidth: 380, textAlign: "center" }}>
        <div style={{
          width: 52, height: 52, background: "var(--oai-ink)", borderRadius: 14,
          display: "inline-grid", placeItems: "center", marginBottom: 20
        }}>
          <svg viewBox="0 0 28 28" fill="none" style={{ width: 30, height: 30 }}>
            <rect x="2" y="2" width="10" height="10" rx="2" fill="white"/>
            <rect x="16" y="2" width="10" height="10" rx="2" fill="white" opacity="0.65"/>
            <rect x="2" y="16" width="10" height="10" rx="2" fill="white" opacity="0.4"/>
            <circle cx="21" cy="21" r="5" fill="var(--oai-accent)" stroke="white" strokeWidth="1.5"/>
          </svg>
        </div>
        <h1 style={{ fontSize: 26, marginBottom: 6 }}>OrchestAI</h1>
        <p style={{ fontSize: 14, color: "var(--oai-ink-3)", marginBottom: 28 }}>Acceso restringido</p>
        <Card>
          <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <Field label="Contraseña de acceso">
              <Input
                type="password"
                placeholder="••••••••••••"
                value={pw}
                onChange={e => setPw(e.target.value)}
                autoFocus
                style={error ? { borderColor: "oklch(0.65 0.20 25)", outline: "none" } : {}}
              />
            </Field>
            {error && (
              <div style={{ fontSize: 12.5, color: "oklch(0.55 0.20 25)", textAlign: "center" }}>
                Contraseña incorrecta
              </div>
            )}
            <Button kind="accent" size="lg" style={{ width: "100%", justifyContent: "center" }} disabled={!pw}>
              Ingresar →
            </Button>
          </form>
        </Card>
        <div style={{ marginTop: 20, fontSize: 12, color: "var(--oai-ink-3)" }}>
          OrchestAI · orchestai.com.ar
        </div>
      </div>
    </div>
  );
}

// ---------- Login ----------
function PageLogin({ onLogin }) {
  const [form, setForm] = useState_A({ name: "", org: "", role: "" });
  const [lang, setLang] = useState_A("es");
  const t = useMemo_A(() => makeT(lang), [lang]);
  const valid = form.name.trim().length > 1;

  const submit = (e) => {
    e.preventDefault();
    if (!valid) return;
    const ini = initials(form.name);
    onLogin({ name: form.name.trim(), org: form.org.trim(), role: form.role.trim(), initials: ini });
  };

  return (
    <div style={{
      minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center",
      background: "var(--oai-bg)", padding: 24
    }}>
      <div style={{ width: "100%", maxWidth: 420 }}>
        <div style={{ textAlign: "center", marginBottom: 36 }}>
          <div style={{
            width: 52, height: 52, background: "var(--oai-ink)", borderRadius: 14,
            display: "inline-grid", placeItems: "center", marginBottom: 20
          }}>
            <svg viewBox="0 0 28 28" fill="none" style={{ width: 30, height: 30 }}>
              <rect x="2" y="2" width="10" height="10" rx="2" fill="white"/>
              <rect x="16" y="2" width="10" height="10" rx="2" fill="white" opacity="0.65"/>
              <rect x="2" y="16" width="10" height="10" rx="2" fill="white" opacity="0.4"/>
              <circle cx="21" cy="21" r="5" fill="var(--oai-accent)" stroke="white" strokeWidth="1.5"/>
            </svg>
          </div>
          <h1 style={{ fontSize: 26, marginBottom: 6 }}>{t("login_title")}</h1>
          <p style={{ fontSize: 14 }}>{t("login_sub")}</p>
          <div style={{ marginTop: 12 }}>
            <Segmented value={lang} onChange={setLang} options={[{ value: "es", label: "ES" }, { value: "en", label: "EN" }]}/>
          </div>
        </div>

        <Card>
          <form onSubmit={submit} className="oai-col" style={{ gap: 16 }}>
            <Field label={t("login_name")}>
              <Input
                placeholder={t("login_name_ph")}
                value={form.name}
                onChange={e => setForm({ ...form, name: e.target.value })}
                autoFocus
                required
              />
            </Field>
            <Field label={t("login_org")}>
              <Input
                placeholder={t("login_org_ph")}
                value={form.org}
                onChange={e => setForm({ ...form, org: e.target.value })}
              />
            </Field>
            <Field label={t("login_role")}>
              <Input
                placeholder={t("login_role_ph")}
                value={form.role}
                onChange={e => setForm({ ...form, role: e.target.value })}
              />
            </Field>
            <Button kind="accent" size="lg" style={{ width: "100%", justifyContent: "center" }} disabled={!valid}>
              {t("login_enter")} →
            </Button>
          </form>
        </Card>

        <div style={{ textAlign: "center", marginTop: 24, fontSize: 12, color: "var(--oai-ink-3)" }}>
          {t("footer")}
        </div>
      </div>
    </div>
  );
}

// ---------- Sidebar ----------
function Sidebar({ t, route, setRoute, tw, auth, db }) {
  const items = [
    { k: "home",      label: t("nav_home"),      icon: Icon.home },
    { k: "new",       label: t("nav_new"),        icon: Icon.plus, accent: true },
    { k: "projects",  label: t("nav_projects"),   icon: Icon.chart },
    { k: "workspace", label: t("nav_workspace"),  icon: Icon.bolt },
    { k: "dataroom",  label: t("nav_dataroom"),   icon: Icon.folder },
    { k: "wiki",      label: t("nav_wiki"),        icon: Icon.book },
    { k: "research",  label: t("nav_research"),   icon: Icon.globe }
  ];
  const recent = (db.projects || []).slice(0, 4);

  return (
    <aside className="oai-sidebar">
      <div className="oai-sidebar__brand">
        <div className="oai-logo">
          <svg viewBox="0 0 28 28" fill="none">
            <rect x="2" y="2" width="10" height="10" rx="2" fill="currentColor"/>
            <rect x="16" y="2" width="10" height="10" rx="2" fill="currentColor" opacity="0.65"/>
            <rect x="2" y="16" width="10" height="10" rx="2" fill="currentColor" opacity="0.4"/>
            <circle cx="21" cy="21" r="5" fill="var(--oai-accent)" stroke="currentColor" strokeWidth="1.5"/>
          </svg>
        </div>
        <div style={{ lineHeight: 1.1 }}>
          <div style={{ fontWeight: 700, fontSize: 16 }}>OrchestAI</div>
          <div style={{ fontSize: 11, color: "var(--oai-ink-3)" }}>{t("sidebar_tag")}</div>
        </div>
      </div>

      <nav className="oai-sidebar__nav">
        <div className="oai-nav-section">
          {items.map(it => (
            <div
              key={it.k}
              className={classNames("oai-nav-item", route === it.k && "is-active", it.accent && "oai-nav-item--accent")}
              onClick={() => setRoute(it.k)}
            >
              {React.createElement(it.icon, { className: "oai-nav-item__icon" })}
              <span>{it.label}</span>
            </div>
          ))}
        </div>

        <div className="oai-nav-section">
          <div className="oai-nav-section__title">{t("nav_recent")}</div>
          {recent.length === 0 ? (
            <div className="oai-nav-item oai-nav-item--sub" style={{ fontStyle: "italic" }}>{t("no_recent")}</div>
          ) : recent.map(p => (
            <div
              key={p.id}
              className={classNames("oai-nav-item", "oai-nav-item--sub")}
              onClick={() => setRoute("workspace:" + p.id)}
            >
              <span className={classNames("oai-nav-item__dot", "is-" + p.status)}/>
              <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.name}</span>
            </div>
          ))}
        </div>

        <div className="oai-nav-section">
          <div className="oai-nav-section__title">{t("nav_methods")}</div>
          {["dcf","multiples","lbo","montecarlo","risk_ar"].map(m => (
            <div key={m} className="oai-nav-item oai-nav-item--sub">
              <Icon.dot className="oai-nav-item__icon" style={{ width: 6, height: 6 }}/>
              <span>{t("methods." + m).split(" ")[0].replace(/[()]/g,"")}</span>
            </div>
          ))}
        </div>
      </nav>

      <div className="oai-sidebar__foot">
        <div className="oai-row">
          <Avatar initials={auth.initials} size={30}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{auth.name}</div>
            <div style={{ fontSize: 11, color: "var(--oai-ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
              {auth.role || "OrchestAI"}{auth.org ? " · " + auth.org : ""}
            </div>
          </div>
          <button className="oai-btn oai-btn--ghost oai-btn--sm" onClick={() => { window.DB.clearAuth(); location.reload(); }}>
            <Icon.x className="oai-btn__icon"/>
          </button>
        </div>
      </div>
    </aside>
  );
}

// ---------- Topbar ----------
function Topbar({ t, lang, setLang, tw, setTw }) {
  return (
    <div className="oai-topbar">
      <div style={{ position: "relative", flex: 1, maxWidth: 520 }}>
        <Icon.search style={{ position: "absolute", left: 12, top: 9, width: 16, height: 16, color: "var(--oai-ink-3)" }}/>
        <Input placeholder={t("search_ph")} style={{ paddingLeft: 36 }}/>
        <span style={{ position: "absolute", right: 10, top: 10, fontSize: 10.5, color: "var(--oai-ink-3)", fontFamily: "var(--oai-font-mono)" }}>⌘K</span>
      </div>
      <div className="grow"/>
      <div className="oai-row" style={{ gap: 4 }}>
        <Segmented value={lang} onChange={setLang} options={[{ value: "es", label: "ES" }, { value: "en", label: "EN" }]}/>
        <Button kind="ghost" size="sm" icon={Icon.bell}/>
        <Button
          kind={tw.theme === "dark" ? "outline" : "ghost"}
          size="sm"
          icon={Icon.sparkle}
          onClick={() => setTw(prev => ({ ...prev, theme: prev.theme === "dark" ? "light" : "dark" }))}
        >
          {tw.theme === "dark" ? t("light_mode") : t("dark_mode")}
        </Button>
      </div>
    </div>
  );
}

// ---------- Home ----------
function PageHome({ t, setRoute, auth, db }) {
  const hour = new Date().getHours();
  const greet = t(greeting());
  const firstName = auth.name.split(" ")[0];
  const running = (db.projects || []).filter(p => p.status === "running").length;
  const total   = (db.projects || []).length;
  const wikiN   = (db.wikiEntries || []).length;
  const docsN   = (db.docs || []).length;

  return (
    <div>
      <div className="page-header">
        <h1>{greet}, {firstName}</h1>
        <p>
          {total === 0
            ? "No hay proyectos aún. Cree su primer análisis de valuación."
            : `${total} proyecto${total !== 1 ? "s" : ""} en el sistema${running > 0 ? `, ${running} en ejecución` : ""}.`
          }
        </p>
      </div>

      <div className="oai-grid" style={{ gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 24 }}>
        {[
          { label: t("kpi_active"),  value: String(total),  delta: total === 0 ? t("nav_new") : total + " total", tone: "lime" },
          { label: t("kpi_running"), value: String(running),delta: running === 0 ? t("no_active_runs") : running + " " + t("nav_projects").toLowerCase(), tone: "amber" },
          { label: t("kpi_docs"),    value: String(docsN), delta: docsN === 0 ? t("empty_docs") : docsN + " archivos", tone: "cobalt" },
          { label: t("kpi_wiki"),    value: String(wikiN), delta: wikiN === 0 ? t("empty_wiki") : wikiN + " entradas", tone: "lime" }
        ].map(s => (
          <Card key={s.label}>
            <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600 }}>{s.label}</div>
            <div style={{ fontSize: 32, fontWeight: 700, marginTop: 8, fontFamily: "var(--oai-font-display)", letterSpacing: "-0.02em" }}>{s.value}</div>
            <div style={{ marginTop: 6 }}><Pill tone={s.tone}>{s.delta}</Pill></div>
          </Card>
        ))}
      </div>

      <div className="oai-grid" style={{ gridTemplateColumns: "2fr 1fr", gap: 20 }}>
        <Card>
          <div className="oai-row" style={{ marginBottom: 12 }}>
            <h3 style={{ flex: 1 }}>{t("recent_projects")}</h3>
            <Button kind="ghost" size="sm" onClick={() => setRoute("projects")}>{t("view_all")}</Button>
          </div>
          {(db.projects || []).length === 0 ? (
            <EmptyState
              icon={Icon.chart}
              title={t("no_projects_here")}
              sub={t("empty_projects_sub")}
              action={<Button kind="accent" icon={Icon.plus} onClick={() => setRoute("new")}>{t("nav_new")}</Button>}
            />
          ) : (
            <div className="oai-col" style={{ gap: 10 }}>
              {(db.projects || []).slice(0, 4).map(p => (
                <div
                  key={p.id}
                  className="oai-row"
                  style={{ padding: "12px", background: "var(--oai-bg-sunk)", borderRadius: 8, cursor: "pointer" }}
                  onClick={() => setRoute("workspace:" + p.id)}
                >
                  <span className={classNames("oai-nav-item__dot", "is-" + p.status)}/>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600, fontSize: 13.5 }}>{p.name}</div>
                    <div className="muted" style={{ fontSize: 11.5, marginTop: 2 }}>
                      {t("sectors." + p.sector)} · {p.country} · {p.currency}
                      {p.ev_low ? ` · EV ${p.ev_low}–${p.ev_high}M` : ""}
                    </div>
                  </div>
                  <Pill tone={p.status === "running" ? "amber" : p.status === "delivered" ? "lime" : "neutral"}>
                    {t("status." + p.status)}
                  </Pill>
                </div>
              ))}
            </div>
          )}
        </Card>

        <Card>
          <div className="oai-row" style={{ marginBottom: 12 }}>
            <Icon.sparkle style={{ width: 16, height: 16, color: "var(--oai-accent-ink)" }}/>
            <h3>{t("knowledge_wiki")}</h3>
          </div>
          {(db.wikiEntries || []).length === 0 ? (
            <EmptyState
              icon={Icon.book}
              title={t("empty_wiki")}
              sub={t("entries_auto")}
              action={<Button kind="ghost" size="sm" onClick={() => setRoute("wiki")}>{t("go_to_wiki")}</Button>}
            />
          ) : (
            <>
              <div className="oai-col" style={{ gap: 8 }}>
                {(db.wikiEntries || []).slice(0, 3).map(e => (
                  <div key={e.id} className="suggestion-card">
                    <div className="suggestion-card__title">{e.title}</div>
                    <div className="suggestion-card__reason">{e.summary}</div>
                  </div>
                ))}
              </div>
              <Button kind="ghost" size="sm" style={{ marginTop: 10, width: "100%" }} onClick={() => setRoute("wiki")}>{t("go_to_wiki")}</Button>
            </>
          )}
        </Card>
      </div>
    </div>
  );
}

// ---------- Tweaks panel ----------
function TweaksPanel({ open, onClose, tw, setTw }) {
  if (!open) return null;
  const set = (k, v) => setTw(prev => ({ ...prev, [k]: v }));
  return (
    <div style={{
      position: "fixed", right: 20, bottom: 20, width: 300,
      background: "var(--oai-bg-elev)", border: "1px solid var(--oai-line)",
      borderRadius: 12, padding: 16, boxShadow: "var(--oai-shadow-lg)", zIndex: 100
    }}>
      <div className="oai-row" style={{ marginBottom: 12 }}>
        <h3 style={{ flex: 1 }}>Tweaks</h3>
        <button className="oai-btn oai-btn--ghost oai-btn--sm" onClick={onClose}>✕</button>
      </div>
      <Field label={t("theme")}>
        <Segmented value={tw.theme} onChange={v => set("theme", v)}
          options={[{ value: "light", label: t("light_mode") }, { value: "dark", label: t("dark_mode") }]}/>
      </Field>
      <Field label={t("tweaks_accent")} style={{ marginTop: 12 }}>
        <div className="oai-row" style={{ gap: 6, marginTop: 4 }}>
          {Object.entries(ACCENT_MAP).map(([k, a]) => (
            <div key={k} onClick={() => set("accent", k)} style={{
              width: 32, height: 32, borderRadius: 6, background: a.accent, cursor: "pointer",
              border: tw.accent === k ? "2px solid var(--oai-ink)" : "2px solid transparent"
            }}/>
          ))}
        </div>
      </Field>
      <Field label={t("density")} style={{ marginTop: 12 }}>
        <Segmented value={tw.density} onChange={v => set("density", v)}
          options={[{ value: "cozy", label: t("density_comfortable") }, { value: "compact", label: t("density_compact") }]}/>
      </Field>
    </div>
  );
}

// ---------- App root ----------
function App() {
  const [unlocked, setUnlocked] = useState_A(() => localStorage.getItem(ACCESS_KEY) === "1");
  const [auth, setAuth] = useState_A(() => window.DB.getAuth());
  const [tw, setTw] = useState_A(() => {
    try { return { ...TWEAKS_DEFAULTS, ...JSON.parse(localStorage.getItem("oai_tw") || "{}") }; }
    catch { return TWEAKS_DEFAULTS; }
  });
  const [route, setRoute] = useState_A(() => localStorage.getItem("oai_route") || "home");
  const [tweaksOpen, setTweaksOpen] = useState_A(false);
  const db = useDB();

  const lang    = tw.lang || "es";
  const setLang = (v) => setTw(prev => ({ ...prev, lang: v }));
  const t = useMemo_A(() => makeT(lang), [lang]);

  useEffect_A(() => { applyTweaks(tw); localStorage.setItem("oai_tw", JSON.stringify(tw)); }, [tw]);
  useEffect_A(() => { localStorage.setItem("oai_route", route); }, [route]);

  const handleLogin = (user) => {
    window.DB.setAuth(user);
    setAuth(user);
  };

  if (!unlocked) return <PagePassword onUnlock={() => setUnlocked(true)} />;
  if (!auth) return <PageLogin onLogin={handleLogin} />;

  // Parse route — supports "workspace:projectId"
  const [routeBase, routeParam] = route.split(":");
  const activeProjectId = routeBase === "workspace" && routeParam ? routeParam : (db.projects[0]?.id || null);

  const handleNewProject = (projectId) => {
    setRoute("workspace:" + projectId);
  };

  return (
    <div className="oai-app">
      <Sidebar t={t} route={routeBase} setRoute={setRoute} tw={tw} auth={auth} db={db}/>
      <div className="oai-main">
        <Topbar t={t} lang={lang} setLang={setLang} tw={tw} setTw={setTw}/>
        <div className="oai-content">
          {routeBase === "home"      && <PageHome      t={t} setRoute={setRoute} auth={auth} db={db}/>}
          {routeBase === "new"       && <PageNewAnalysis t={t} onRun={handleNewProject} auth={auth}/>}
          {routeBase === "projects"  && <PageProjects  t={t} lang={lang} onOpen={id => setRoute("workspace:" + id)} onNew={() => setRoute("new")}/>}
          {routeBase === "workspace" && <PageWorkspace t={t} lang={lang} projectId={activeProjectId}/>}
          {routeBase === "dataroom"  && <PageDataRoom  t={t} lang={lang} auth={auth}/>}
          {routeBase === "wiki"      && <PageWiki      t={t} lang={lang} auth={auth}/>}
          {routeBase === "research"  && <PageResearch  t={t}/>}
        </div>
      </div>
      <TweaksPanel open={tweaksOpen} onClose={() => setTweaksOpen(false)} tw={tw} setTw={setTw}/>
    </div>
  );
}

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