// SQSEO app, Content Ideas screen (live: GET /api/content-ideas) + saved content
// briefs (GET/DELETE /api/briefs). "Generate full brief" opens the brief drawer
// for a cluster's lead query; saved briefs are listed, viewable, and exportable.
(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 { IntentBadge, SectionTitle, EmptyState, useApi } = window.LTQ;
const t = (k, v) => (window.LTQ.t ? window.LTQ.t(k, v) : k);

const TONE = { accent: ["var(--accent-50)", "var(--accent-600)"], blue: ["var(--blue-50)", "var(--blue-600)"], violet: ["var(--violet-50)", "var(--violet-600)"], red: ["var(--red-50)", "var(--red-500)"], green: ["var(--green-50)", "var(--green-600)"], amber: ["var(--amber-50)", "var(--amber-600)"] };

function IdeaCard({ idea, onBrief }) {
  const [bg, fg] = TONE[idea.tone] || TONE.accent;
  const h2s = Array.isArray(idea.h2s) ? idea.h2s : [];
  return (
    <Card pad={20} interactive style={{ display: "flex", flexDirection: "column", gap: 14, height: "100%" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 8, height: 26, padding: "0 11px 0 8px", borderRadius: 999, background: bg, color: fg, fontSize: 12, fontWeight: 700 }}>
          <Icon name={idea.icon} size={14} /> {window.LTQ.dataLabel("type", idea.kind)}
        </span>
      </div>
      <h3 style={{ fontSize: 17, fontWeight: 700, color: "var(--text-strong)", lineHeight: 1.3, letterSpacing: "-0.01em" }}>{idea.title}</h3>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6, alignItems: "center" }}>
        <Badge tone="neutral" icon="search" size="sm">{idea.query}</Badge>
        <IntentBadge value={idea.intent} />
      </div>
      <p style={{ fontSize: 13, color: "var(--text-muted)", lineHeight: 1.55 }}>{idea.angle}</p>
      {h2s.length > 0 && (
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--text-faint)", marginBottom: 8 }}>{t("ideas.suggested_h2s")}</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {h2s.map((h, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--text-body)" }}>
                <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: fg, fontWeight: 700, width: 16 }}>{String(i + 1).padStart(2, "0")}</span>{h}
              </div>
            ))}
          </div>
        </div>
      )}
      <div style={{ display: "flex", flexDirection: "column", gap: 6, padding: "12px 14px", background: "var(--ink-50)", borderRadius: "var(--r-md)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, color: "var(--text-body)" }}><Icon name="megaphone" size={14} style={{ color: fg }} /><b style={{ color: "var(--text-strong)" }}>{t("ideas.cta")}</b> {idea.cta}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, color: "var(--text-body)" }}><Icon name="link" size={14} style={{ color: fg }} /><b style={{ color: "var(--text-strong)" }}>{t("ideas.internal_link")}</b> {idea.link}</div>
      </div>
      <div style={{ flex: 1 }} />
      <Button variant="secondary" size="sm" block trailingIcon="arrow-right" onClick={() => onBrief && onBrief(idea.query)}>{t("ideas.generate_full")}</Button>
    </Card>
  );
}

// A compact saved-brief card (opens the read-only brief drawer on click).
function SavedBriefCard({ row, onOpen }) {
  const wc = row.wordCount || { min: 0, max: 0 };
  return (
    <button onClick={() => onOpen(row)} style={{ textAlign: "left", border: "1px solid var(--border-subtle)", borderRadius: "var(--r-lg)", background: "var(--surface-card)", padding: 16, cursor: "pointer", display: "flex", flexDirection: "column", gap: 10, boxShadow: "var(--shadow-xs)", transition: "box-shadow var(--dur-base), transform var(--dur-base)" }}
      onMouseEnter={e => { e.currentTarget.style.boxShadow = "var(--shadow-md)"; e.currentTarget.style.transform = "translateY(-2px)"; }}
      onMouseLeave={e => { e.currentTarget.style.boxShadow = "var(--shadow-xs)"; e.currentTarget.style.transform = "none"; }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.05em", color: "var(--text-faint)" }}><Icon name="file-pen-line" size={13} /> {t("ideas.brief")}</span>
        {row.grounded && <span title={t("brief.grounded_title")} style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 10, fontWeight: 700, textTransform: "uppercase", color: "var(--accent-600)" }}><Icon name="radar" size={11} /> GSC</span>}
      </div>
      <div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--text-strong)", lineHeight: 1.3, textTransform: "capitalize" }}>{row.keyword}</div>
      <div style={{ display: "flex", alignItems: "center", gap: 12, fontSize: 12, color: "var(--text-muted)", flexWrap: "wrap" }}>
        {row.intent && <IntentBadge value={row.intent} />}
        <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontWeight: 700, color: "var(--text-body)" }}>{row.opportunity}/100</span>
        <span>{t("ideas.n_sections", { n: row.sections })}</span>
        {wc.min ? <span>{t("ideas.n_words", { range: wc.min.toLocaleString() + "–" + wc.max.toLocaleString() })}</span> : null}
      </div>
    </button>
  );
}

function SavedBriefs({ briefs, loading, onOpen }) {
  if (!loading && briefs.length === 0) return null;
  return (
    <Card pad={20}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 8, fontSize: 15, fontWeight: 700, color: "var(--text-strong)" }}><Icon name="folder-open" size={16} style={{ color: "var(--accent-500)" }} /> {t("ideas.saved_briefs")}</span>
        <Badge tone="neutral" variant="soft">{briefs.length}</Badge>
      </div>
      {loading ? (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
          {[0, 1, 2].map(i => <span key={i} className="lt-shimmer" style={{ height: 120, borderRadius: 12, background: "var(--ink-100)" }} />)}
        </div>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }} className="lt-briefs-grid">
          {briefs.map(b => <SavedBriefCard key={b.id} row={b} onOpen={onOpen} />)}
        </div>
      )}
    </Card>
  );
}

function ContentIdeas({ onNavigate }) {
  const { loading, data } = useApi("/api/content-ideas");
  const saved = useApi("/api/briefs");
  const ideas = (data && data.ideas) || [];
  const briefs = (saved.data && saved.data.briefs) || [];
  const [briefPhrase, setBriefPhrase] = React.useState(null); // generate by phrase
  const [openBrief, setOpenBrief] = React.useState(null); // a saved brief row to view

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <SectionTitle eyebrow={t("ideas.eyebrow")} title={t("nav.content")}
        sub={t("ideas.sub")} />

      <SavedBriefs briefs={briefs} loading={saved.loading} onOpen={setOpenBrief} />

      {loading ? (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          {[0, 1].map((i) => <Card key={i} pad={20}><span className="lt-shimmer" style={{ display: "block", height: 180, borderRadius: 10, background: "var(--ink-100)" }} /></Card>)}
        </div>
      ) : ideas.length === 0 ? (
        <Card pad={0}><EmptyState icon="lightbulb" sq="think" title={t("ideas.empty_title")}
          body={t("ideas.empty_body")}
          action={<Button variant="primary" leadingIcon="search" onClick={() => onNavigate && onNavigate("research")}>{t("gaps.start_researching")}</Button>} /></Card>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          {ideas.map((idea, i) => <IdeaCard key={idea.id || i} idea={idea} onBrief={setBriefPhrase} />)}
        </div>
      )}

      {briefPhrase && window.LTQ.BriefDrawer && (
        <window.LTQ.BriefDrawer keyword={briefPhrase} onClose={() => setBriefPhrase(null)} onSaved={() => saved.reload && saved.reload()} />
      )}
      {openBrief && window.LTQ.SavedBriefDrawer && (
        <window.LTQ.SavedBriefDrawer row={openBrief} onClose={() => setOpenBrief(null)} onDeleted={() => saved.reload && saved.reload()} />
      )}
    </div>
  );
}
window.LTQ.ContentIdeas = ContentIdeas;
})();
