// SQSEO Reports & exports screen (Phase 9). Two jobs:
//  1) Saved + shareable performance reports — create a named report, get a
//     read-only public link (/report.html#token), optionally schedule it.
//  2) Export any dataset as CSV (the full /api/export/*.csv surface).
// Live: GET/POST/PATCH/DELETE /api/reports, POST /api/reports/share.
(function init(){
if(!window.LongtailIQDesignSystem_ae8f12 || !window.LTQ || !window.LTQ.useApi || !window.LTQ.Modal || !window.LTQ.SectionTitle){return setTimeout(init,30);}
const React = window.React;
const DS = window.LongtailIQDesignSystem_ae8f12;
const { Card, Icon, Button } = DS;
const { useApi, api, toast, Modal, Popover, MenuItem, SectionTitle, EmptyState } = window.LTQ;
const t = (k, v) => (window.LTQ.t ? window.LTQ.t(k, v) : k);

const PERIODS = ["7d", "28d", "90d", "365d"];
const periodLabel = (v) => (PERIODS.includes(v) ? t("reports.period_" + v) : v);
const SCHEDULES = ["", "weekly", "monthly"];
const scheduleLabel = (v) => t(v === "weekly" ? "reports.weekly" : v === "monthly" ? "reports.monthly" : "reports.manual");
// "2d ago" style relative time from an ISO timestamp.
function ago(iso) {
  if (!iso) return "";
  const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
  if (s < 90) return t("time.just_now");
  const m = s / 60; if (m < 60) return t("time.m_ago", { n: Math.round(m) });
  const h = m / 60; if (h < 24) return t("time.h_ago", { n: Math.round(h) });
  const d = h / 24; if (d < 30) return t("time.d_ago", { n: Math.round(d) });
  return t("reports.mo_ago", { n: Math.round(d / 30) });
}

const EXPORTS = [
  {
    groupKey: "reports.group_research",
    items: [
      { path: "keywords.csv", key: "keywords", icon: "search" },
      { path: "clusters.csv", key: "clusters", icon: "layers" },
      { path: "ai-queries.csv", key: "ai_queries", icon: "sparkles" },
      { path: "competitor-gaps.csv", key: "competitor_gaps", icon: "git-compare" },
      { path: "content-ideas.csv", key: "content_ideas", icon: "lightbulb" },
    ],
  },
  {
    groupKey: "reports.group_performance",
    items: [
      { path: "pages.csv", key: "pages", icon: "file-text" },
      { path: "queries.csv", key: "queries", icon: "list" },
      { path: "topics.csv", key: "topics", icon: "folder" },
      { path: "ai-opportunities.csv", key: "ai_opportunities", icon: "zap" },
      { path: "history.csv", key: "history", icon: "trending-up" },
    ],
  },
];



const dl = (path) => {
  const a = document.createElement("a");
  a.href = "/api/export/" + path;
  document.body.appendChild(a);
  a.click();
  a.remove();
  toast(t("chrome.export_started"), { tone: "success" });
};
const copy = async (text) => {
  try { await navigator.clipboard.writeText(text); toast(t("reports.link_copied"), { tone: "success" }); }
  catch { toast(t("reports.copy_manual"), { tone: "warning" }); }
};

// A styled native select (no-build friendly, matches the DS input chrome).
function Field({ label, children }) {
  return (
    <label style={{ display: "block" }}>
      <span style={{ display: "block", fontSize: 12.5, fontWeight: 600, color: "var(--text-muted)", marginBottom: 6 }}>{label}</span>
      {children}
    </label>
  );
}
const selectStyle = { width: "100%", height: 38, padding: "0 12px", borderRadius: 9, border: "1px solid var(--border-subtle)", background: "var(--paper)", fontFamily: "var(--font-sans)", fontSize: 13.5, color: "var(--text-strong)", cursor: "pointer" };
const inputStyle = { width: "100%", height: 38, padding: "0 12px", borderRadius: 9, border: "1px solid var(--border-subtle)", background: "var(--paper)", fontFamily: "var(--font-sans)", fontSize: 13.5, color: "var(--text-strong)" };

function ReportModal({ initial, onClose, onSaved }) {
  const editing = !!initial;
  const [name, setName] = React.useState(initial?.name || t("reports.default_name"));
  const [period, setPeriod] = React.useState(initial?.period || "28d");
  const [schedule, setSchedule] = React.useState(initial?.schedule || "");
  const [recipients, setRecipients] = React.useState(initial?.recipients || "");
  const [busy, setBusy] = React.useState(false);

  const save = async () => {
    setBusy(true);
    const body = { name: name.trim() || t("reports.default_name"), period, schedule, recipients };
    const r = editing ? await api.patch("/api/reports/" + initial.id, body) : await api.post("/api/reports", body);
    setBusy(false);
    if (r.ok) { toast(editing ? t("reports.updated") : t("reports.created"), { tone: "success" }); onSaved(r.data.report); onClose(); }
    else toast(r.error || t("reports.save_failed"), { tone: "error" });
  };

  return (
    <Modal title={editing ? t("reports.edit") : t("reports.new")} sub={t("reports.hint")} onClose={onClose} width={480}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <Field label={t("reports.name_label")}>
          <input value={name} onChange={(e) => setName(e.target.value)} maxLength={120} placeholder={t("reports.name_ph")} style={inputStyle} />
        </Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label={t("reports.period")}>
            <select value={period} onChange={(e) => setPeriod(e.target.value)} style={selectStyle}>
              {PERIODS.map((p) => <option key={p} value={p}>{periodLabel(p)}</option>)}
            </select>
          </Field>
          <Field label={t("reports.schedule")}>
            <select value={schedule} onChange={(e) => setSchedule(e.target.value)} style={selectStyle}>
              {SCHEDULES.map((sv) => <option key={sv} value={sv}>{sv === "" ? t("reports.manual_full") : scheduleLabel(sv)}</option>)}
            </select>
          </Field>
        </div>
        {schedule && (
          <Field label={t("reports.recipients")}>
            <input value={recipients} onChange={(e) => setRecipients(e.target.value)} placeholder="alex@acme.com, jordan@acme.com" style={inputStyle} />
            <span style={{ display: "block", fontSize: 11.5, color: "var(--text-faint)", marginTop: 6 }}>
              <Icon name="info" size={12} style={{ verticalAlign: "-2px", marginRight: 4 }} />
              {t("reports.recipients_note", { schedule: scheduleLabel(schedule).toLowerCase() })}
            </span>
          </Field>
        )}
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 4 }}>
          <Button variant="secondary" size="sm" onClick={onClose}>{t("chrome.cancel")}</Button>
          <Button variant="primary" size="sm" leadingIcon={editing ? "check" : "plus"} onClick={save} disabled={busy}>{busy ? t("calendar.saving") : editing ? t("reports.save_changes") : t("reports.create")}</Button>
        </div>
      </div>
    </Modal>
  );
}

function ReportCard({ r, onEdit, onDelete }) {
  const [hover, setHover] = React.useState(false);
  const scheduled = !!r.schedule;
  const recCount = (r.recipients || "").split(",").filter(Boolean).length;
  return (
    <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ display: "flex", alignItems: "center", gap: 14, padding: "16px 18px", border: "1px solid var(--border-subtle)", borderRadius: "var(--r-lg)", background: "var(--paper)",
        transform: hover ? "translateY(-1px)" : "none", boxShadow: hover ? "var(--shadow-sm)" : "none", transition: "transform var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out)" }}>
      <span style={{ width: 40, height: 40, flex: "none", borderRadius: 10, display: "grid", placeItems: "center", background: "var(--ink-900)", color: "#fff" }}>
        <Icon name="file-bar-chart" size={19} />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: "var(--text-strong)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.name}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 4, flexWrap: "wrap" }}>
          <span style={{ fontSize: 11.5, color: "var(--text-muted)", fontWeight: 600 }}>{periodLabel(r.period)}</span>
          <span style={{ width: 3, height: 3, borderRadius: 999, background: "var(--text-faint)" }} />
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, fontWeight: 600, color: scheduled ? "var(--viz-green)" : "var(--text-faint)" }}>
            <Icon name={scheduled ? "calendar-clock" : "hand"} size={12} />{scheduleLabel(r.schedule)}{scheduled && recCount ? " · " + t("reports.n_recipients", { n: recCount }) : ""}
          </span>
          <span style={{ width: 3, height: 3, borderRadius: 999, background: "var(--text-faint)" }} />
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, fontWeight: 600, color: r.views ? "var(--text-muted)" : "var(--text-faint)" }}>
            <Icon name="eye" size={12} />{r.views ? t("reports.opened_n", { n: r.views }) + (r.last_viewed_at ? " · " + ago(r.last_viewed_at) : "") : t("reports.not_opened")}
          </span>
        </div>
      </div>
      <button onClick={() => copy(r.url)} style={{ display: "inline-flex", alignItems: "center", gap: 7, height: 32, padding: "0 12px", border: "1px solid var(--border-subtle)", background: "var(--paper)", borderRadius: 8, cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 600, color: "var(--text-body)", flex: "none" }}>
        <Icon name="link" size={14} /> {t("reports.copy_link")}
      </button>
      <Popover align="right" width={188}
        trigger={(open, toggle) => (
          <button onClick={toggle} aria-label={t("reports.actions")} style={{ width: 32, height: 32, flex: "none", display: "grid", placeItems: "center", border: "1px solid var(--border-subtle)", background: open ? "var(--ink-50)" : "var(--paper)", borderRadius: 8, cursor: "pointer", color: "var(--text-muted)" }}>
            <Icon name="more-horizontal" size={16} />
          </button>
        )}>
        {(close) => (<>
          <MenuItem icon="external-link" label={t("reports.open")} onClick={() => { close(); window.open(r.url, "_blank", "noopener"); }} />
          <MenuItem icon="link" label={t("reports.copy_link")} onClick={() => { close(); copy(r.url); }} />
          <MenuItem icon="pencil" label={t("wizard.edit")} onClick={() => { close(); onEdit(r); }} />
          <div style={{ height: 1, background: "var(--border-subtle)", margin: "5px 4px" }} />
          <MenuItem icon="trash-2" label={t("reports.delete")} danger onClick={() => { close(); onDelete(r); }} />
        </>)}
      </Popover>
    </div>
  );
}

function ExportTile({ item }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button onClick={() => dl(item.path)} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ display: "flex", alignItems: "flex-start", gap: 12, padding: 14, textAlign: "left", border: "1px solid var(--border-subtle)", borderRadius: "var(--r-lg)", background: hover ? "var(--ink-50)" : "var(--paper)", cursor: "pointer", width: "100%",
        transform: hover ? "translateY(-1px)" : "none", transition: "transform var(--dur-fast) var(--ease-out), background var(--dur-fast) var(--ease-out)" }}>
      <span style={{ width: 34, height: 34, flex: "none", borderRadius: 9, display: "grid", placeItems: "center", background: "var(--ink-50)", border: "1px solid var(--border-subtle)" }}>
        <Icon name={item.icon} size={16} style={{ color: "var(--accent-500)" }} />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
          <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text-strong)" }}>{t("reports.exp_" + item.key)}</span>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 9.5, fontWeight: 700, color: "var(--text-faint)", border: "1px solid var(--border-subtle)", borderRadius: 5, padding: "0 5px", lineHeight: 1.7 }}>CSV</span>
        </div>
        <div style={{ fontSize: 11.5, color: "var(--text-faint)", lineHeight: 1.4, marginTop: 2 }}>{t("reports.exp_" + item.key + "_desc")}</div>
      </div>
      <Icon name="download" size={15} style={{ color: hover ? "var(--text-body)" : "var(--text-faint)", flex: "none", marginTop: 3 }} />
    </button>
  );
}

function Reports() {
  const { loading, data, reload } = useApi("/api/reports");
  const [modal, setModal] = React.useState(null); // null | {} (new) | report (edit)
  const [sharing, setSharing] = React.useState(false);
  const reports = (data && data.reports) || [];

  const quickShare = async () => {
    setSharing(true);
    const r = await api.post("/api/reports/share", { period: "28d" });
    setSharing(false);
    if (r.ok) {
      await copy(r.data.url);
      // First-ever shared report in this workspace: one celebration.
      if (window.GameFeel && window.GameFeel.first("share") && window.LTQEngine) window.LTQEngine.celebrate("save");
    }
    else toast(r.error || t("reports.link_failed"), { tone: "error" });
  };
  // The printable A4 document covers one finished calendar month, so the
  // button opens the last complete one (the live month is on Performance).
  const openMonthly = () => {
    const d = new Date();
    const y = d.getFullYear();
    const m = d.getMonth(); // 0-based: this value IS the previous month's number
    const ym = m === 0 ? `${y - 1}-12` : `${y}-${String(m).padStart(2, "0")}`;
    window.open("/api/reports/monthly/" + ym, "_blank", "noopener");
  };
  // Deleting a report kills its live shared link, so it confirms first —
  // the same pattern Saved Lists and API-key revoke use.
  const [confirmDel, setConfirmDel] = React.useState(null);
  const onDelete = (r) => setConfirmDel(r);
  const doDelete = async (r) => {
    setConfirmDel(null);
    const res = await api.del("/api/reports/" + r.id);
    if (res.ok) { toast(t("reports.deleted"), { tone: "success" }); reload(); }
    else toast(res.error || t("brief.delete_failed"), { tone: "error" });
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
      <SectionTitle eyebrow={t("reports.eyebrow")} title={t("nav.exports")}
        sub={t("reports.sub")}
        right={<div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <Button variant="secondary" size="sm" leadingIcon="file-text" onClick={openMonthly}>{t("reports.monthly_doc")}</Button>
          <Button variant="secondary" size="sm" leadingIcon="link" onClick={quickShare} disabled={sharing}>{sharing ? t("reports.creating") : t("reports.quick_share")}</Button>
          <Button variant="primary" size="sm" leadingIcon="plus" onClick={() => setModal({})}>{t("reports.new")}</Button>
        </div>} />

      {/* saved reports */}
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {loading ? (
          [0, 1].map((i) => <Card key={i} pad={16}><span className="lt-shimmer" style={{ display: "block", height: 40, borderRadius: 8, background: "var(--ink-100)" }} /></Card>)
        ) : reports.length === 0 ? (
          <Card pad={0}><EmptyState icon="file-bar-chart" sq="idle" title={t("reports.empty_title")}
            body={t("reports.empty_body")}
            action={<Button variant="primary" leadingIcon="plus" onClick={() => setModal({})}>{t("reports.new")}</Button>} /></Card>
        ) : (
          reports.map((r) => <ReportCard key={r.id} r={r} onEdit={(rep) => setModal(rep)} onDelete={onDelete} />)
        )}
      </div>

      {/* CSV exports */}
      <div>
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 12, marginBottom: 14 }}>
          <div>
            <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text-strong)", marginBottom: 4 }}>{t("reports.export_data")}</div>
            <div style={{ fontSize: 12.5, color: "var(--text-faint)" }}>{t("reports.export_data_sub")}</div>
          </div>
          <Button variant="secondary" size="sm" leadingIcon="package" onClick={() => dl("all.zip")}>{t("reports.download_all")}</Button>
        </div>
        {EXPORTS.map((grp) => (
          <div key={grp.groupKey} style={{ marginBottom: 18 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 10 }}>{t(grp.groupKey)}</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 10 }}>
              {grp.items.map((it) => <ExportTile key={it.path} item={it} />)}
            </div>
          </div>
        ))}
      </div>

      {modal && <ReportModal initial={modal.id ? modal : null} onClose={() => setModal(null)} onSaved={() => reload()} />}
      {confirmDel && (
        <Modal title={t("settings.delete_q", { name: confirmDel.name })} sub={t("reports.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={() => doDelete(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("reports.delete")}
            </button>
          </div>
        </Modal>
      )}
    </div>
  );
}
window.LTQ.Reports = Reports;
})();
