// SQSEO app, Saved Lists screen (live: GET/POST/DELETE /api/lists).
(function init(){
if(!window.LongtailIQDesignSystem_ae8f12 || !window.LTQ || !window.LTQ.useApi){return setTimeout(init,30);}
const React = window.React;
const DS = window.LongtailIQDesignSystem_ae8f12;
const { Card, Icon, Badge, Button } = DS;
const { SectionTitle, EmptyState, useApi, Modal, api, toast, reloadBoot } = window.LTQ;
const t = (k, v) => (window.LTQ.t ? window.LTQ.t(k, v) : k);

const field = { width: "100%", height: 42, padding: "0 12px", borderRadius: 10, background: "var(--surface-card)", border: "1px solid var(--border-strong)", fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-strong)", outline: "none" };
function relTime(iso) {
  if (!iso) return "";
  const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
  if (s < 60) return t("time.just_now");
  if (s < 3600) return t("time.m_ago", { n: Math.floor(s / 60) });
  if (s < 86400) return t("time.h_ago", { n: Math.floor(s / 3600) });
  return t("time.d_ago", { n: Math.floor(s / 86400) });
}

function NewListModal({ onClose, onCreated }) {
  const [name, setName] = React.useState("");
  const [tag, setTag] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const submit = async (e) => {
    e && e.preventDefault();
    if (!name.trim()) return;
    setBusy(true);
    const r = await api.post("/api/lists", { name: name.trim(), tag: tag.trim() });
    setBusy(false);
    if (r.ok) { await reloadBoot(); toast(t("saved.created"), { tone: "success" }); onCreated(); onClose(); }
    else toast(r.error || t("saved.create_failed"), { tone: "error" });
  };
  return (
    <Modal title={t("research.new_list")} sub={t("saved.new_sub")} onClose={onClose}>
      <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <label style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-body)" }}>{t("research.list_name")}<input autoFocus value={name} onChange={(e) => setName(e.target.value)} placeholder={t("research.list_name_ph")} style={{ ...field, marginTop: 6 }} /></label>
        <label style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-body)" }}>{t("research.tag")} <span style={{ color: "var(--text-faint)", fontWeight: 500 }}>{t("wizard.optional")}</span><input value={tag} onChange={(e) => setTag(e.target.value)} placeholder={t("research.tag_ph")} style={{ ...field, marginTop: 6 }} /></label>
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 4 }}>
          <button type="button" onClick={onClose} style={{ height: 38, padding: "0 14px", borderRadius: 9, border: "1px solid var(--border-subtle)", background: "var(--paper)", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600, color: "var(--text-body)" }}>{t("chrome.cancel")}</button>
          <button type="submit" disabled={busy || !name.trim()} style={{ height: 38, padding: "0 16px", borderRadius: 9, border: "none", background: "var(--ink-900)", color: "#fff", cursor: name.trim() ? "pointer" : "default", opacity: name.trim() ? 1 : 0.6, fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 7 }}>
            {busy ? <span className="lt-spin" style={{ width: 14, height: 14, border: "2px solid rgba(255,255,255,0.4)", borderTopColor: "#fff", borderRadius: 999 }} /> : <Icon name="folder-plus" size={15} />} {t("saved.create")}
          </button>
        </div>
      </form>
    </Modal>
  );
}

function ViewListModal({ list, onClose, onChanged }) {
  const { loading, data } = useApi("/api/lists/" + list.id, [list.id]);
  const items = (data && data.items) || [];
  const [editing, setEditing] = React.useState(false);
  const [name, setName] = React.useState(list.name);
  const rename = async () => {
    if (!name.trim() || name.trim() === list.name) { setEditing(false); return; }
    const r = await api.patch("/api/lists/" + list.id, { name: name.trim() });
    if (r.ok) { setEditing(false); await reloadBoot(); onChanged && onChanged(); toast(t("saved.renamed"), { tone: "success" }); }
    else toast(r.error || t("saved.rename_failed"), { tone: "error" });
  };
  return (
    <Modal title={list.name} sub={t("saved.n_keywords", { n: list.count }) + (list.tag ? " · " + list.tag : "")} onClose={onClose} width={560}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
        {editing ? (
          <>
            <input autoFocus value={name} onChange={(e) => setName(e.target.value)} onKeyDown={(e) => e.key === "Enter" && rename()}
              style={{ flex: 1, height: 34, padding: "0 10px", borderRadius: 8, border: "1px solid var(--border-strong)", background: "var(--surface-card)", fontSize: 13.5, fontFamily: "var(--font-sans)", color: "var(--text-strong)", outline: "none" }} />
            <button onClick={rename} style={{ height: 34, padding: "0 12px", borderRadius: 8, border: "none", background: "var(--ink-900)", color: "#fff", cursor: "pointer", fontSize: 12.5, fontWeight: 600 }}>{t("research.save")}</button>
          </>
        ) : (
          <>
            <button onClick={() => setEditing(true)} style={{ height: 32, padding: "0 11px", borderRadius: 8, border: "1px solid var(--border-subtle)", background: "var(--paper)", cursor: "pointer", fontSize: 12.5, fontWeight: 600, color: "var(--text-body)", display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="pencil" size={13} /> {t("saved.rename")}</button>
            <button onClick={() => downloadList(list.id)} style={{ height: 32, padding: "0 11px", borderRadius: 8, border: "1px solid var(--border-subtle)", background: "var(--paper)", cursor: "pointer", fontSize: 12.5, fontWeight: 600, color: "var(--text-body)", display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="download" size={13} /> {t("research.export_csv")}</button>
          </>
        )}
      </div>
      <div className="lt-scroll" style={{ maxHeight: 420, overflowY: "auto", margin: "0 -4px" }}>
        {loading ? <div style={{ padding: 20, textAlign: "center", color: "var(--text-faint)", fontSize: 13 }}>{t("chrome.loading")}</div>
          : items.length === 0 ? <div style={{ padding: 24, textAlign: "center", color: "var(--text-faint)", fontSize: 13 }}>{t("saved.empty_list")}</div>
          : items.map((it, i) => (
            <div key={it.id || i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 8px", borderBottom: i < items.length - 1 ? "1px solid var(--border-subtle)" : "none" }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text-strong)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{it.keyword}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-faint)" }}>{[it.intent, it.platform].filter(Boolean).join(" · ")}</div>
              </div>
              <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-muted)" }}>{(it.demand || 0).toLocaleString()}</span>
              <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 13, fontWeight: 700, color: it.score >= 80 ? "var(--viz-green)" : "var(--text-strong)", width: 28, textAlign: "right" }}>{it.score}</span>
            </div>
          ))}
      </div>
    </Modal>
  );
}

const downloadList = (id) => { const a = document.createElement("a"); a.href = "/api/lists/" + id + "/export.csv"; document.body.appendChild(a); a.click(); a.remove(); toast(t("chrome.export_started"), { tone: "success" }); };

function ListCard({ list, onView, onDelete }) {
  return (
    <Card pad={18} style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
        <span style={{ width: 38, height: 38, borderRadius: 11, display: "grid", placeItems: "center", background: "var(--ink-50)", boxShadow: "var(--ring-inset)" }}>
          <Icon name="folder" size={18} style={{ color: list.color || "var(--accent-500)" }} />
        </span>
        <div style={{ display: "flex", gap: 2 }}>
          <button onClick={() => downloadList(list.id)} title={t("research.export_csv")} style={{ width: 28, height: 28, borderRadius: 8, border: "none", background: "transparent", cursor: "pointer", display: "grid", placeItems: "center", color: "var(--text-faint)" }}
            onMouseEnter={e => { e.currentTarget.style.background = "var(--ink-50)"; e.currentTarget.style.color = "var(--text-strong)"; }} onMouseLeave={e => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--text-faint)"; }}>
            <Icon name="download" size={15} />
          </button>
          <button onClick={onDelete} title={t("saved.delete")} style={{ width: 28, height: 28, borderRadius: 8, border: "none", background: "transparent", cursor: "pointer", display: "grid", placeItems: "center", color: "var(--text-faint)" }}
            onMouseEnter={e => { e.currentTarget.style.background = "var(--ink-50)"; e.currentTarget.style.color = "var(--viz-red)"; }} onMouseLeave={e => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--text-faint)"; }}>
            <Icon name="trash-2" size={15} />
          </button>
        </div>
      </div>
      <div style={{ cursor: "pointer" }} onClick={onView}>
        <div style={{ fontSize: 15, fontWeight: 700, color: "var(--text-strong)" }}>{list.name}</div>
        <div style={{ fontSize: 12.5, color: "var(--text-muted)", marginTop: 2 }}><b className="lt-num" style={{ color: "var(--text-body)" }}>{list.count}</b> {t("saved.keywords_lc")} · {relTime(list.updated_at)}</div>
      </div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        {list.tag ? <Badge tone="neutral" dot>{list.tag}</Badge> : <span />}
        <Button variant="secondary" size="sm" trailingIcon="arrow-right" onClick={onView}>{t("saved.open")}</Button>
      </div>
    </Card>
  );
}

function SavedLists() {
  const { loading, data, reload } = useApi("/api/lists");
  const lists = (data && data.lists) || [];
  const [adding, setAdding] = React.useState(false);
  const [viewing, setViewing] = React.useState(null);
  const [confirmDel, setConfirmDel] = React.useState(null); // list pending delete confirmation

  const del = async (list) => {
    setConfirmDel(null);
    const r = await api.del("/api/lists/" + list.id);
    if (r.ok) { await reloadBoot(); reload(); toast(t("saved.deleted"), { tone: "success" }); }
    else toast(r.error || t("brief.delete_failed"), { tone: "error" });
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <SectionTitle eyebrow={t("saved.eyebrow")} title={t("nav.saved")}
        sub={t("saved.sub")}
        right={<Button variant="primary" size="sm" leadingIcon="folder-plus" onClick={() => setAdding(true)}>{t("research.new_list")}</Button>} />

      {loading ? (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 14 }}>{[0, 1, 2, 3].map((i) => <Card key={i} pad={18}><span className="lt-shimmer" style={{ display: "block", height: 120, borderRadius: 10, background: "var(--ink-100)" }} /></Card>)}</div>
      ) : lists.length === 0 ? (
        <Card pad={0}><EmptyState icon="bookmark" sq="idle" title={t("saved.empty_title")}
          body={t("saved.empty_body")}
          action={<Button variant="primary" leadingIcon="folder-plus" onClick={() => setAdding(true)}>{t("saved.create_list")}</Button>} /></Card>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 14 }}>
          {lists.map((l) => <ListCard key={l.id} list={l} onView={() => setViewing(l)} onDelete={() => setConfirmDel(l)} />)}
          <Card pad={18} onClick={() => setAdding(true)} style={{ border: "1px dashed var(--ink-300)", boxShadow: "none", background: "transparent", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 8, minHeight: 150, cursor: "pointer", color: "var(--text-muted)" }}>
            <Icon name="plus" size={22} /><span style={{ fontSize: 13, fontWeight: 600 }}>{t("research.new_list")}</span>
          </Card>
        </div>
      )}

      {adding && <NewListModal onClose={() => setAdding(false)} onCreated={reload} />}
      {viewing && <ViewListModal list={viewing} onClose={() => setViewing(null)} onChanged={() => { reload(); setViewing(null); }} />}
      {confirmDel && (
        <Modal title={t("settings.delete_q", { name: confirmDel.name })} sub={t("saved.delete_sub")} onClose={() => setConfirmDel(null)} width={440}>
          <div style={{ display: "flex", justifyContent: "flex-end", gap: 8 }}>
            <button onClick={() => setConfirmDel(null)} style={{ height: 38, padding: "0 14px", borderRadius: 9, border: "1px solid var(--border-subtle)", background: "var(--paper)", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600, color: "var(--text-body)" }}>{t("chrome.cancel")}</button>
            <button onClick={() => del(confirmDel)} style={{ height: 38, padding: "0 16px", borderRadius: 9, border: "none", background: "var(--viz-red)", color: "#fff", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 7 }}>
              <Icon name="trash-2" size={15} /> {t("saved.delete")}
            </button>
          </div>
        </Modal>
      )}
    </div>
  );
}
window.LTQ.SavedLists = SavedLists;
})();
