/* ===========================================================================
   screen-dashboard.jsx — Overview with 3 layout variations (tweakable)
   =========================================================================== */
const D = window.STUDIO;

function StatTile({ num, label, delta, deltaDir, icon, spark, sparkColor, onClick }) {
  return (
    <div className="stat" onClick={onClick} style={onClick ? { cursor: "pointer" } : {}}>
      <div className="stat-ico"><Icon name={icon} size={62} stroke={1.6}/></div>
      <div className="stat-num">{num}</div>
      <div className="stat-label">{label}</div>
      {spark ? <div style={{ marginTop: 10 }}><Spark data={spark} color={sparkColor}/></div>
        : delta && <div className={`stat-delta ${deltaDir === "down" ? "delta-down" : "delta-up"}`}>{delta}</div>}
      {onClick && <div style={{ marginTop: 8, fontFamily: "var(--mono)", fontSize: 10, color: "var(--accent)", fontWeight: 600, letterSpacing: "0.05em", textTransform: "uppercase" }}>View →</div>}
    </div>
  );
}

function CompetitorCard({ c, go }) {
  return (
    <div className="comp-card" onClick={() => go({ name: "competitor", id: c.id })}>
      <div className="comp-top">
        <div className="comp-logo" style={{ background: c.swatch }}>{c.name[0]}</div>
        <div style={{ minWidth: 0 }}>
          <div className="comp-name">{c.name}</div>
          <div className="comp-cat">{c.category}</div>
        </div>
        <MatchRing value={c.match}/>
      </div>
      <div className="comp-reason">{c.reason}</div>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
        {c.status === "tracking"
          ? <Chip tone="olive" dot="#FBF1DA"><Icon name="spy" size={12}/> Tracking</Chip>
          : <Chip tone="ghost">+ Add to spy list</Chip>}
        <span style={{ marginLeft: "auto", fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-soft)" }}>Spend: {c.spend}</span>
      </div>
      <div className="comp-meta">
        <div><div className="m-num">{c.ads}</div><div className="m-lab">Ads</div></div>
        <div><div className="m-num">{c.hooks}</div><div className="m-lab">Hooks</div></div>
        <div><div className="m-num">{c.scripts}</div><div className="m-lab">Scripts</div></div>
        <div style={{ marginLeft: "auto", alignSelf: "center" }}><Spark data={c.trend} color={c.swatch}/></div>
      </div>
    </div>
  );
}

function FeedList({ items }) {
  const iconFor = { ad: ["grid", "#C75B27"], hook: ["hook", "#B14E7E"], gen: ["sparkle", "#2E8C86"], script: ["script", "#7C8B3C"], competitor: ["spy", "#E5A828"], gap: ["gap", "#B5482F"] };
  return (
    <div>
      {items.map((f, i) => {
        const [ic, col] = iconFor[f.kind] || ["sparkle", "#C75B27"];
        return (
          <div className="feed-item" key={i}>
            <div className="feed-ico" style={{ background: col }}><Icon name={ic} size={16}/></div>
            <div><div className="feed-text">{f.text}</div><div className="feed-time">{f.t}</div></div>
          </div>
        );
      })}
    </div>
  );
}

function HookPreview({ go }) {
  return (
    <div className="card card-pad">
      <div className="section-label"><Icon name="hook" size={14}/> Top hooks · vs Grüns</div>
      {D.hooks.slice(0, 3).map((h, i) => (
        <div key={h.id} style={{ display: "flex", gap: 13, alignItems: "flex-start", padding: "12px 0", borderBottom: i < 2 ? "1px solid var(--line)" : "none", cursor: "pointer" }} onClick={() => go({ name: "hooks" })}>
          <div className="hook-rank" style={{ width: 30, height: 30, flex: "0 0 30px", fontSize: 14, borderRadius: 8 }}>{i + 1}</div>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 14.5, color: "var(--ink)", lineHeight: 1.3, letterSpacing: "-0.01em" }}>“{h.example}”</div>
            <div style={{ fontSize: 12, color: "var(--ink-soft)", marginTop: 4 }}>{h.title}</div>
          </div>
          <div style={{ marginLeft: "auto", textAlign: "right", flex: "0 0 auto" }}>
            <div style={{ fontFamily: "var(--display)", fontSize: 17 }}>{h.strength}</div>
            <div style={{ fontFamily: "var(--mono)", fontSize: 8.5, textTransform: "uppercase", color: "var(--ink-soft)" }}>strength</div>
          </div>
        </div>
      ))}
      <button className="btn ghost sm" style={{ marginTop: 12 }} onClick={() => go({ name: "hooks" })}>See all 6 patterns <Icon name="arrow" size={14}/></button>
    </div>
  );
}

function MushLegend() {
  return (
    <div className="card card-pad">
      <div className="section-label"><Icon name="mushroom" size={14}/> The SuperMush five</div>
      <div className="mush-row">
        {D.mushrooms.map((m) => (
          <div className="mush-pill" key={m.name}>
            <span className="mush-cap" style={{ background: m.color }}/>
            <span>{m.name}</span><span className="mush-ben">{m.benefit}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

const STATS = [
  { num: "10", label: "Ads tracked", icon: "grid", delta: "▲ 2 new this week", deltaDir: "up" },
  { num: "6", label: "Hook patterns", icon: "hook", delta: "1 crossed 30-day mark", deltaDir: "up" },
  { num: "12", label: "Scripts for Alli", icon: "script", delta: "5 with generated creative", deltaDir: "up" },
  { num: "7", label: "Gaps to exploit", icon: "gap", delta: "ranked by potential", deltaDir: "up" },
];

function Dashboard({ go, store }) {
  const c = D.competitors[0];
  if (!c) {
    return (
      <div className="content">
        <div className="page-head">
          <div className="eyebrow"><Icon name="sparkle" size={13}/> SuperMush Ad Studio · Overview</div>
          <h1 className="page-title">No competitors analyzed yet.</h1>
          <p className="page-desc">Run an analysis to populate the dashboard.</p>
        </div>
      </div>
    );
  }
  return (
    <div className="content">
      <div className="page-head">
        <div className="eyebrow"><Icon name="sparkle" size={13}/> SuperMush Ad Studio · Overview</div>
        <h1 className="page-title">Good morning, {(D.brand && D.brand.founder) || "Alli"}.</h1>
        <p className="page-desc">Your competitive creative desk. {D.competitors.length} competitor analyzed, {D.hooks.length} hook patterns decoded, {D.scripts.length} scripts staged — {D.scripts.filter(s => s.generated).length} with generated creative.</p>
      </div>
      <div className="stat-row" style={{ marginBottom: 26 }}>
        <StatTile num={String(D.ads.length)} label="Ads tracked" icon="grid" onClick={() => go({ name: "ads" })}/>
        <StatTile num={String(D.hooks.length)} label="Hook patterns" icon="hook" onClick={() => go({ name: "hooks" })}/>
        <StatTile num={String(D.scripts.length)} label="Scripts for Alli" icon="script" onClick={() => go({ name: "scripts" })}/>
        <StatTile num={String(D.gaps.length)} label="Gaps to exploit" icon="gap" onClick={() => go({ name: "gaps" })}/>
      </div>
      <div className="section-label" style={{ fontSize: 12 }}><Icon name="spy" size={14}/> Analyzed competitor</div>
      <div className="comp-grid">{D.competitors.map((c) => <CompetitorCard key={c.id} c={c} go={go}/>)}</div>

      {(D.suggested_competitors || []).length > 0 && (
        <>
          <div style={{ height: 28 }}/>
          <div className="section-label" style={{ fontSize: 12, display: "flex", alignItems: "center", gap: 6, marginBottom: 12 }}>
            <Icon name="search" size={14}/> Suggested · not yet analyzed
            <span style={{ marginLeft: "auto", fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-faint)", fontWeight: 500 }}>
              {D.suggested_competitors.length} queued
            </span>
          </div>
          <div>
            {D.suggested_competitors.map((c) => (
              <CompetitorRow key={c.id} c={c} analyzed={false} onClick={() => store && store.toast("Analysis queued · routed to Slack bot", { label: "OK", fn: () => {} })}/>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

function CompetitorRow({ c, analyzed, onClick }) {
  return (
    <div
      onClick={onClick}
      style={{
        display: "flex",
        alignItems: "center",
        gap: 14,
        padding: "12px 16px",
        background: "#fff",
        border: analyzed ? "2px solid var(--accent)" : "var(--bd) solid var(--line)",
        borderRadius: "var(--r-md)",
        marginBottom: 8,
        cursor: "pointer",
        transition: "border-color .15s, transform .15s",
      }}
      onMouseEnter={(e) => { if (!analyzed) e.currentTarget.style.borderColor = "var(--line-strong)"; }}
      onMouseLeave={(e) => { if (!analyzed) e.currentTarget.style.borderColor = "var(--line)"; }}
    >
      <div style={{
        width: 38, height: 38, borderRadius: 10,
        background: c.swatch, color: "#fff",
        display: "grid", placeItems: "center",
        fontFamily: "var(--display)", fontWeight: 800, fontSize: 17,
        letterSpacing: "-0.01em",
        flex: "0 0 38px",
      }}>{(c.name || "?")[0].toUpperCase()}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 14.5, color: "var(--ink)", lineHeight: 1.2 }}>{c.name}</div>
        <div style={{ fontSize: 12.5, color: "var(--ink-soft)", marginTop: 2 }}>{c.category || c.handle}</div>
      </div>
      {analyzed ? (
        <>
          <span style={{
            padding: "4px 10px",
            background: "var(--olive-soft)",
            color: "var(--olive)",
            fontSize: 11,
            fontWeight: 700,
            borderRadius: 999,
            display: "inline-flex",
            alignItems: "center",
            gap: 5,
            fontFamily: "var(--display)",
            letterSpacing: "0.01em",
          }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--olive)" }}/>
            Analyzed
          </span>
          <div style={{
            width: 24, height: 24, borderRadius: 999,
            background: "var(--accent)",
            color: "#fff",
            display: "grid", placeItems: "center",
            flex: "0 0 24px",
          }}>
            <Icon name="check" size={14} stroke={3}/>
          </div>
        </>
      ) : (
        <>
          <span style={{
            padding: "4px 10px",
            background: "var(--paper-2)",
            color: "var(--ink-soft)",
            fontSize: 11,
            fontWeight: 600,
            borderRadius: 999,
            fontFamily: "var(--display)",
            letterSpacing: "0.01em",
          }}>
            Queued
          </span>
          <div style={{
            width: 24, height: 24, borderRadius: 999,
            border: "1.5px solid var(--line-strong)",
            background: "#fff",
            flex: "0 0 24px",
          }}/>
        </>
      )}
    </div>
  );
}

Object.assign(window, { Dashboard, CompetitorCard, StatTile, FeedList, CompetitorRow });
