/* /saved: the signed-in account's saved work (Molecular decision packs, Population genetics
   results, and Study records) from /api/saved. Uses chrome.jsx and tools-common.jsx. */

const SAVED_FILTERS = [["all", "All"], ["molecular", "Molecular"], ["population", "Population genetics"], ["study", "Study record"]];

function savedSummaryText(item) {
  const s = item.summary || {};
  const mode = s.mode === "exploratory" ? "exploratory" : s.mode === "registered" ? "registered" : null;
  if (item.module === "molecular") {
    const counts = Object.entries(s.counts || {}).filter(([, n]) => n > 0).map(([call, n]) => `${n} ${call.replace(/_/g, " ")}`);
    return [s.candidates != null ? `${s.candidates} candidates` : null, counts.join(", ") || null, mode].filter(Boolean).join(" · ");
  }
  if (item.module === "population") {
    return [s.fileName, s.individuals != null ? `${s.individuals} individuals` : null, s.populations != null ? `${s.populations} populations` : null,
      s.loci != null ? `${s.loci} loci` : null, s.bestK ? `best K ${s.bestK}` : null].filter(Boolean).join(" · ");
  }
  return [s.subjects != null ? `${s.subjects} subjects` : null, s.groups != null ? `${s.groups} groups` : null,
    s.assays != null ? `${s.assays} assay files` : null, s.outcomes != null ? `${s.outcomes} outcomes` : null, mode].filter(Boolean).join(" · ");
}

function SavedPage() {
  const account = useAccount();
  const [items, setItems] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [notice, setNotice] = React.useState(null);
  const [filter, setFilter] = React.useState("all");

  React.useEffect(() => {
    if (!account || !account.user || !account.saving) return undefined;
    let live = true;
    (async () => {
      // Finish a "Sign in and save" started on a tool page before sign-in.
      if (new URLSearchParams(window.location.search).get("pending")) {
        const pending = toolTakePendingSave();
        window.history.replaceState(null, "", "/saved");
        if (pending && SAVED_MODULES[pending.module]) {
          try {
            const item = await savedApi.create({ module: pending.module, title: pending.title, summary: pending.summary, payload: pending.payload });
            if (live) setNotice({ tone: "ok", title: `Saved "${item.title}"`, href: `${SAVED_MODULES[item.module].href}?saved=${item.id}` });
          } catch (err) {
            if (live) setNotice({ tone: "block", title: "Not saved", text: err.message || String(err) });
          }
        }
      }
      try {
        const list = await savedApi.list();
        if (live) setItems(list);
      } catch (err) {
        if (live) setError(err.message || String(err));
      }
    })();
    return () => { live = false; };
  }, [account]);

  const shown = (items || []).filter((item) => filter === "all" || item.module === filter);
  const replace = (item) => setItems((list) => list.map((x) => (x.id === item.id ? item : x)));
  const drop = (id) => setItems((list) => list.filter((x) => x.id !== id));

  return (
    <main>
      <div className="page-wrap">
        <div className="tool-head">
          <span className="mono" style={{ fontSize: 11, color: "var(--brand-700)", letterSpacing: ".08em", textTransform: "uppercase", fontWeight: 600 }}>Your account</span>
          <h1>Saved work</h1>
          <p>Decision packs, Population genetics results, and Study records you saved from the tools. Saving keeps results and tables, never your original files.</p>
        </div>
      </div>
      <div className="page-wrap tool-body">
        {!account ? <p className="tool-muted">Loading…</p> : null}
        {account && !account.enabled ? <ToolNotice tone="warn" title="Sign-in is not available right now">Please try again later.</ToolNotice> : null}
        {account && account.enabled && !account.user ? <SavedSignIn /> : null}
        {account && account.user && !account.saving ? <ToolNotice tone="warn" title="Saved work is not available right now">Please try again later.</ToolNotice> : null}
        {account && account.user && account.saving ? (
          <div className="tool-stack">
            {notice ? (
              <ToolNotice tone={notice.tone} title={notice.title}>
                {notice.href ? <a className="btn-link" href={notice.href}>Open it</a> : notice.text}
              </ToolNotice>
            ) : null}
            {error ? <ToolNotice tone="block" title="Could not load your saved work">{error}</ToolNotice> : null}
            {items === null && !error ? <p className="tool-muted">Loading your saved work…</p> : null}
            {items && items.length === 0 ? <SavedEmpty /> : null}
            {items && items.length > 0 ? (
              <>
                <div className="tool-tabs" role="tablist" aria-label="Filter by module">
                  {SAVED_FILTERS.map(([key, label]) => {
                    const n = key === "all" ? items.length : items.filter((i) => i.module === key).length;
                    return (
                      <button key={key} type="button" role="tab" className="tool-tab" aria-selected={filter === key}
                              style={{ minHeight: 44 }} onClick={() => setFilter(key)}>{label} ({n})</button>
                    );
                  })}
                </div>
                {shown.length === 0 ? <p className="tool-muted">Nothing saved from this module yet.</p> : null}
                {shown.map((item) => <SavedRow key={item.id} item={item} onChange={replace} onDelete={drop} />)}
                <p className="tool-muted" style={{ fontSize: 12.5 }}>{items.length} of 200 saved items.</p>
              </>
            ) : null}
          </div>
        ) : null}
      </div>
    </main>
  );
}

function SavedSignIn() {
  return (
    <div className="panel" style={{ maxWidth: 560 }}>
      <div className="panel-body">
        <h2 style={{ margin: 0, fontSize: 20, fontWeight: 700, color: "var(--ink-900)" }}>Sign in to see your saved work</h2>
        <p style={{ margin: "8px 0 16px", fontSize: 14.5, lineHeight: 1.55, color: "var(--ink-700)" }}>
          Use your ConductScience account. Save decision packs, Population genetics results, and Study records from each tool, and open them here.
        </p>
        <a className="btn btn-primary btn-tap" href={signInHref()}>Sign in</a>
      </div>
    </div>
  );
}

function SavedEmpty() {
  return (
    <div className="panel">
      <div className="panel-body">
        <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: "var(--ink-900)" }}>Nothing saved yet</h2>
        <p style={{ margin: "8px 0 16px", fontSize: 14.5, lineHeight: 1.55, color: "var(--ink-700)" }}>
          Finish an analysis in a tool and choose "Save to your account".
        </p>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          <a className="btn btn-ghost btn-tap" href="/molecular/app">Molecular</a>
          <a className="btn btn-ghost btn-tap" href="/population/app">Population genetics</a>
          <a className="btn btn-ghost btn-tap" href="/study/app">Study record</a>
        </div>
      </div>
    </div>
  );
}

function SavedRow({ item, onChange, onDelete }) {
  const info = SAVED_MODULES[item.module] || { label: item.module, href: "/" };
  const [mode, setMode] = React.useState("view");
  const [title, setTitle] = React.useState(item.title);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  const open = `${info.href}?saved=${item.id}`;

  async function run(action) {
    setBusy(true);
    setError(null);
    try {
      await action();
    } catch (err) {
      setError(err.message || String(err));
    } finally {
      setBusy(false);
    }
  }

  const download = () => run(async () => {
    const full = await savedApi.get(item.id);
    toolDownload(`${toolSlug(item.title, item.module)}.json`, JSON.stringify(full.payload, null, 2), "application/json");
  });
  const rename = () => run(async () => {
    const updated = await savedApi.update(item.id, { title });
    onChange(updated);
    setMode("view");
  });
  const remove = () => run(async () => {
    await savedApi.remove(item.id);
    onDelete(item.id);
  });

  return (
    <div className="panel">
      <div className="panel-body" style={{ display: "grid", gap: 10 }}>
        <div style={{ display: "flex", gap: 12, alignItems: "flex-start", justifyContent: "space-between", flexWrap: "wrap" }}>
          <div style={{ minWidth: 0, flex: "1 1 280px" }}>
            <span className="chip" style={{ fontSize: 11 }}>{info.label}</span>
            {mode === "rename" ? (
              <div style={{ display: "flex", gap: 8, marginTop: 8, flexWrap: "wrap" }}>
                <input className="tool-input" style={{ flex: "1 1 220px" }} value={title} maxLength={200} aria-label="Name"
                       onChange={(e) => setTitle(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") rename(); }} />
                <button type="button" className="btn btn-primary btn-tap" disabled={busy} onClick={rename}>Save name</button>
                <button type="button" className="btn btn-ghost btn-tap" onClick={() => { setTitle(item.title); setMode("view"); }}>Cancel</button>
              </div>
            ) : (
              <a href={open} style={{ display: "block", marginTop: 8, fontSize: 16.5, fontWeight: 600, color: "var(--ink-900)", textDecoration: "none", overflowWrap: "anywhere" }}>{item.title}</a>
            )}
            <div style={{ marginTop: 4, fontSize: 13.5, color: "var(--ink-600)", overflowWrap: "anywhere" }}>{savedSummaryText(item)}</div>
            <div className="tool-muted" style={{ marginTop: 4, fontSize: 12.5 }}>
              Saved {toolFmtTime(item.updatedAt)} · {toolFmtBytes(item.payloadBytes || 0)} · fingerprint <span className="tool-mono">{String(item.payloadSha256 || "").slice(0, 12)}…</span>
            </div>
          </div>
          {mode === "confirm" ? (
            <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
              <span style={{ fontSize: 13.5, color: "var(--block)" }}>Delete for good?</span>
              <button type="button" className="btn btn-tap" style={{ background: "var(--block)", color: "white" }} disabled={busy} onClick={remove}>Delete</button>
              <button type="button" className="btn btn-ghost btn-tap" onClick={() => setMode("view")}>Keep</button>
            </div>
          ) : (
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              <a className="btn btn-primary btn-tap" href={open}>Open</a>
              <button type="button" className="btn btn-ghost btn-tap" disabled={busy} onClick={download}>Download</button>
              <button type="button" className="btn btn-ghost btn-tap" onClick={() => setMode("rename")}>Rename</button>
              <button type="button" className="btn btn-ghost btn-tap" onClick={() => setMode("confirm")}>Delete</button>
            </div>
          )}
        </div>
        {error ? <ToolNotice tone="block" title="That did not work">{error}</ToolNotice> : null}
      </div>
    </div>
  );
}

Object.assign(window, { SavedPage });
