// SQSEO marketing, "written like you" live brief demo (Phase 7).
// Paste a domain -> POST /api/tools/brief-preview -> REAL brand signals pulled from
// the page (detected colors, tone inferred from the copy, offerings it links to) +
// a REAL content brief generated by the engine for the site's top opportunity.
// Signup handoff to brief all your keywords. Strings route through window.LTQM.t.
(function init(){
if(!window.LongtailIQDesignSystem_ae8f12 || !window.LTQM){return setTimeout(init,30);}
const React = window.React;
const DS = window.LongtailIQDesignSystem_ae8f12;
const { Icon, Button } = DS;
const M = window.LTQM;

function Chip({ children, icon }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 7, height: 28, padding: "0 11px", borderRadius: 999, border: "1px solid var(--border-subtle)", background: "var(--paper)", fontSize: 12.5, fontWeight: 600, color: "var(--text-body)" }}>
      {icon && <Icon name={icon} size={13} style={{ color: "var(--text-faint)" }} />}{children}
    </span>
  );
}
function Block({ label, children }) {
  return (
    <div>
      <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--text-faint)", marginBottom: 9 }}>{label}</div>
      {children}
    </div>
  );
}

function Result({ data, onReset }) {
  const t = M.t;
  if (!data.ok) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "16px 18px", border: "1px solid var(--border-strong)", borderRadius: "var(--r-lg)", background: "var(--surface-card)", textAlign: "left" }}>
        <Icon name="alert-triangle" size={18} style={{ color: "var(--amber-500)", flex: "none" }} />
        <span style={{ fontSize: 14, color: "var(--text-body)", flex: 1 }}>{data.error || t("brief.err.analyze")}</span>
        <button onClick={onReset} style={{ border: "none", background: "transparent", color: "var(--accent-600)", fontWeight: 600, fontSize: 13, cursor: "pointer" }}>{t("brief.try_again")}</button>
      </div>
    );
  }
  const b = data.brief || {};
  return (
    <div className="fx-enter" style={{ textAlign: "left", border: "1px solid var(--border-subtle)", borderRadius: "var(--r-xl)", background: "var(--surface-card)", boxShadow: "var(--shadow-md)", overflow: "hidden" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "12px 18px", borderBottom: "1px solid var(--border-subtle)", background: "var(--ink-50)" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 8, fontSize: 13, fontWeight: 600, color: "var(--text-strong)", minWidth: 0 }}>
          <Icon name="wand-sparkles" size={15} style={{ color: "var(--accent-500)", flex: "none" }} />{t("brief.tailored_for")} <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{data.host}</span>
        </span>
        <button onClick={onReset} style={{ border: "none", background: "transparent", color: "var(--text-muted)", fontWeight: 600, fontSize: 12.5, cursor: "pointer", flex: "none" }}>{t("brief.try_another")}</button>
      </div>

      {/* brand signals detected from the page */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 18, padding: "18px 18px 6px" }} className="lt-brand-grid">
        {data.colors && data.colors.length > 0 && (
          <Block label={t("brief.detected_colors")}>
            <div style={{ display: "flex", gap: 7, flexWrap: "wrap" }}>
              {data.colors.slice(0, 5).map((c, i) => (
                <span key={i} title={c} style={{ display: "inline-flex", alignItems: "center", gap: 6, height: 26, padding: "0 9px 0 6px", borderRadius: 999, border: "1px solid var(--border-subtle)", background: "var(--paper)", fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)" }}>
                  <span style={{ width: 14, height: 14, borderRadius: 5, background: c, border: "1px solid rgba(0,0,0,0.08)" }} />{c}
                </span>
              ))}
            </div>
          </Block>
        )}
        {data.toneTags && data.toneTags.length > 0 && (
          <Block label={t("brief.tone")}>
            <div style={{ display: "flex", gap: 7, flexWrap: "wrap" }}>{data.toneTags.map((tag, i) => <Chip key={i} icon="mic">{tag}</Chip>)}</div>
          </Block>
        )}
        {data.offerings && data.offerings.length > 0 && (
          <Block label={t("brief.offerings")}>
            <div style={{ display: "flex", gap: 7, flexWrap: "wrap" }}>{data.offerings.slice(0, 5).map((o, i) => <Chip key={i} icon="link">{o}</Chip>)}</div>
          </Block>
        )}
      </div>

      {/* the live brief */}
      <div style={{ padding: 18, borderTop: "1px solid var(--border-subtle)", marginTop: 12 }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 10, flexWrap: "wrap", marginBottom: 14 }}>
          <span style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 700, color: "var(--text-strong)", textTransform: "capitalize" }}>{b.keyword}</span>
          <span style={{ fontSize: 12, color: "var(--text-faint)" }}>{b.intent} · {t("brief.opportunity")} {b.opportunity}/100 · {b.wordCount ? b.wordCount.min + "-" + b.wordCount.max + " " + t("brief.words") : ""}</span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }} className="lt-brief-grid">
          <Block label={t("brief.title_options")}>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {(b.titles || []).slice(0, 3).map((tt, i) => (
                <div key={i} style={{ display: "flex", gap: 8, fontSize: 13.5, color: "var(--text-strong)", fontWeight: 600, lineHeight: 1.4 }}><Icon name="type" size={13} style={{ color: "var(--text-faint)", marginTop: 3, flex: "none" }} />{tt}</div>
              ))}
            </div>
          </Block>
          <Block label={t("brief.outline")}>
            <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
              {(b.outline || []).slice(0, 6).map((s, i) => (
                <div key={i} style={{ display: "flex", gap: 8, fontSize: 13, color: "var(--text-body)", lineHeight: 1.4 }}>
                  <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, color: "var(--accent-600)", flex: "none", marginTop: 1 }}>H2·{String(i + 1).padStart(2, "0")}</span>
                  <span style={{ textTransform: "capitalize" }}>{s.h2}</span>
                </div>
              ))}
            </div>
          </Block>
        </div>
        {b.faqs && b.faqs.length > 0 && (
          <div style={{ marginTop: 16 }}>
            <Block label={t("brief.faqs")}>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 7 }}>{b.faqs.slice(0, 4).map((f, i) => <Chip key={i} icon="help-circle">{f}</Chip>)}</div>
            </Block>
          </div>
        )}
        {b.geoNote && (
          <div style={{ display: "flex", alignItems: "flex-start", gap: 9, padding: "11px 13px", marginTop: 16, borderRadius: 10, border: "1px solid var(--accent-100)", background: "var(--accent-50, #ecfdf5)", fontSize: 12.5, color: "var(--text-body)", lineHeight: 1.5 }}>
            <Icon name="sparkles" size={15} style={{ color: "var(--accent-600)", marginTop: 1, flex: "none" }} /><span><b style={{ color: "var(--text-strong)" }}>{t("brief.geo_note_label")}</b> {b.geoNote}</span>
          </div>
        )}
        <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap", marginTop: 18 }}>
          <Button variant="primary" size="md" className="fx-sheen" trailingIcon="arrow-right" onClick={()=>{window.location.href="/app/register.html";}}>{t("brief.cta")}</Button>
          <span style={{ fontSize: 12.5, color: "var(--text-faint)" }}>{t("brief.cta_note")}</span>
        </div>
      </div>
    </div>
  );
}

function BrandBrief() {
  const t = M.t;
  const [url, setUrl] = React.useState("");
  const [phase, setPhase] = React.useState("idle");
  const [data, setData] = React.useState(null);
  const submit = async (e) => {
    e && e.preventDefault();
    const v = url.trim();
    if (v.length < 3 || phase === "loading") return;
    setPhase("loading");
    try {
      const res = await fetch("/api/tools/brief-preview", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ url: v }) });
      const d = await res.json().catch(() => ({}));
      setData(res.ok ? d : { ok: false, error: d.message || t("brief.err.invalid") });
    } catch (err) {
      setData({ ok: false, error: t("brief.err.server") });
    }
    setPhase("done");
  };
  const reset = () => { setPhase("idle"); setData(null); };

  return (
    <div style={{ position: "relative", borderTop: "1px solid var(--border-subtle)", background: "var(--ink-50)", overflow: "hidden" }}>
      <section style={{ position: "relative", maxWidth: 900, margin: "0 auto", padding: "76px 24px", textAlign: "center" }}>
        <div className="lt-reveal" style={{ marginBottom: 18 }}>
          <span className="lt-pill-label"><Icon name="wand-sparkles" size={14} style={{ color: "var(--text-muted)" }} />{t("brief.pill")}</span>
        </div>
        <h2 className="lt-reveal lt-display" style={{ fontSize: "clamp(1.9rem,1.4rem+1.6vw,2.6rem)", fontWeight: 700, letterSpacing: "-0.025em", color: "var(--ink-900)", lineHeight: 1.08 }}>
          {t("brief.title")}<br/><span style={{ color: "var(--ink-400)" }}>{t("brief.title_gray")}</span>
        </h2>
        <p className="lt-reveal" style={{ fontSize: 16, color: "var(--text-muted)", marginTop: 14, lineHeight: 1.6, maxWidth: 560, marginLeft: "auto", marginRight: "auto" }}>
          {t("brief.sub")}
        </p>
        <form onSubmit={submit} className="lt-reveal" style={{ display: "flex", gap: 8, justifyContent: "center", flexWrap: "wrap", margin: "26px auto 0", maxWidth: 560 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, flex: "1 1 300px", minWidth: 240, height: 50, padding: "0 14px", background: "var(--surface-card)", border: "1px solid var(--border-strong)", borderRadius: "var(--r-md)", boxShadow: "var(--shadow-xs)" }}>
            <Icon name="globe" size={18} style={{ color: "var(--accent-500)", flex: "none" }} />
            <input value={url} onChange={(e)=>setUrl(e.target.value)} type="text" inputMode="url" placeholder={t("brief.placeholder")} aria-label={t("brief.url_aria")}
              style={{ flex: 1, minWidth: 0, height: 46, border: "none", outline: "none", background: "transparent", fontFamily: "var(--font-sans)", fontSize: 15, fontWeight: 500, color: "var(--text-strong)" }} />
          </div>
          <Button variant="primary" size="lg" className="fx-sheen" leadingIcon={phase === "loading" ? undefined : "wand-sparkles"} disabled={phase === "loading" || url.trim().length < 3} onClick={submit}>
            {phase === "loading" ? t("brief.reading") : t("brief.write")}
          </Button>
        </form>

        {phase !== "idle" && (
          <div style={{ marginTop: 26 }}>
            {phase === "loading" ? (
              <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 12, padding: "40px 0", color: "var(--text-muted)" }}>
                <span className="lt-spinner" style={{ display: "inline-block", width: 20, height: 20, border: "2px solid var(--accent-200)", borderTopColor: "var(--accent-500)", borderRadius: 999 }} />
                <span style={{ fontSize: 14 }}>{t("brief.loading")}</span>
              </div>
            ) : data ? <Result data={data} onReset={reset} /> : null}
          </div>
        )}
      </section>
    </div>
  );
}
window.LTQM = window.LTQM || {};
window.LTQM.BrandBrief = BrandBrief;
})();
