/* ========================================================================
   ui.jsx — Reusable UI atoms used across pages
   ====================================================================== */

function Pill({ children, variant = "default", icon }) {
  const cls =
    variant === "yellow" ? "pill pill-yellow"
    : variant === "yellow-soft" ? "pill pill-yellow-soft"
    : variant === "blue" ? "pill pill-blue"
    : variant === "green" ? "pill pill-green"
    : variant === "amber" ? "pill pill-amber"
    : variant === "red" ? "pill pill-red"
    : variant === "dark" ? "pill pill-dark"
    : "pill";
  return (
    <span className={cls}>
      {icon === "dot" && <span className="dot" />}
      {typeof icon === "string" && icon !== "dot" && <Icon name={icon} size={11} stroke={2} />}
      {children}
    </span>
  );
}

function Btn({ children, variant = "secondary", size, icon, iconRight, onClick, type = "button", disabled, style, title }) {
  const cls = ["btn",
    variant === "primary" ? "btn-primary"
    : variant === "dark" ? "btn-dark"
    : variant === "ghost" ? "btn-ghost"
    : "btn-secondary",
    size === "sm" ? "btn-sm" : "",
  ].filter(Boolean).join(" ");
  return (
    <button type={type} className={cls} onClick={onClick} disabled={disabled} style={style} title={title}>
      {icon && <Icon name={icon} size={size === "sm" ? 13 : 15} stroke={2} />}
      {children}
      {iconRight && <Icon name={iconRight} size={size === "sm" ? 13 : 15} stroke={2} />}
    </button>
  );
}

function IconBtn({ icon, onClick, title, size = 16, style }) {
  return (
    <button className="icon-btn" onClick={onClick} title={title} style={style}>
      <Icon name={icon} size={size} stroke={2} />
    </button>
  );
}

function Card({ children, padding = "", title, sub, action, dark = false, style, className = "" }) {
  const cls = `${dark ? "card-dark" : "card"} ${className}`;
  if (!title) {
    return (
      <div className={cls} style={style}>
        <div className={padding === "lg" ? "card-pad-lg" : padding === "none" ? "" : "card-pad"}>
          {children}
        </div>
      </div>
    );
  }
  return (
    <div className={cls} style={style}>
      <div className="card-head">
        <div>
          <div className="card-title">{title}</div>
          {sub && <div className="card-sub">{sub}</div>}
        </div>
        {action}
      </div>
      <div className={padding === "lg" ? "card-pad-lg" : padding === "none" ? "" : "card-pad"}>
        {children}
      </div>
    </div>
  );
}

function StatTile({ label, value, delta, deltaTone = "green", icon, accent }) {
  return (
    <div className="card card-pad" style={{ position: "relative", overflow: "hidden" }}>
      {accent && (
        <div style={{ position: "absolute", top: 0, right: 0, width: 90, height: 90, background: accent, opacity: 0.15, borderRadius: "0 12px 0 90px" }} />
      )}
      <div className="row-between">
        <div className="text-xs uppercase muted" style={{ letterSpacing: "0.14em", fontWeight: 800 }}>{label}</div>
        {icon && <div style={{ width: 28, height: 28, borderRadius: 8, background: "var(--surface-2)", display: "grid", placeItems: "center", color: "var(--fg-muted)" }}><Icon name={icon} size={14} /></div>}
      </div>
      <div style={{ fontSize: 30, fontWeight: 800, letterSpacing: "-0.025em", marginTop: 10, lineHeight: 1 }}>{value}</div>
      {delta && (
        <div className="row gap-6 mt-12 text-xs fw-7" style={{ color: deltaTone === "green" ? "oklch(0.45 0.16 150)" : deltaTone === "red" ? "oklch(0.5 0.18 25)" : "var(--fg-muted)" }}>
          <Icon name="trend" size={12} stroke={2.2} />
          <span>{delta}</span>
          <span className="muted" style={{ color: "var(--fg-subtle)", fontWeight: 600 }}>vs. last 7 days</span>
        </div>
      )}
    </div>
  );
}

function AppIcon({ project, size = 44, rounded = "22%" }) {
  return (
    <div
      className="app-ico"
      style={{
        width: size, height: size,
        background: project.icon?.gradient || "var(--fg)",
        borderRadius: rounded,
        fontSize: size * 0.45,
      }}
    >
      {project.icon?.letter || project.name[0]}
    </div>
  );
}

function ProjectStatus({ project }) {
  return <Pill variant={project.statusVariant} icon="dot">{project.status}</Pill>;
}

function Section({ title, sub, action, children, dense = false, eyebrow }) {
  return (
    <section style={{ marginBottom: dense ? 20 : 32 }}>
      <div className="row-between" style={{ marginBottom: 14, gap: 12 }}>
        <div>
          {eyebrow && <div className="text-xs uppercase muted" style={{ letterSpacing: "0.14em", fontWeight: 800, marginBottom: 4 }}>{eyebrow}</div>}
          <div style={{ fontSize: 18, fontWeight: 800, letterSpacing: "-0.015em" }}>{title}</div>
          {sub && <div className="muted text-sm mt-4">{sub}</div>}
        </div>
        {action}
      </div>
      {children}
    </section>
  );
}

function Empty({ icon = "inbox", title, sub, action }) {
  return (
    <div className="card card-pad" style={{ textAlign: "center", padding: 36 }}>
      <div style={{ width: 44, height: 44, borderRadius: 12, background: "var(--surface-2)", display: "inline-grid", placeItems: "center", color: "var(--fg-muted)", margin: "0 auto 12px" }}>
        <Icon name={icon} size={20} stroke={1.6} />
      </div>
      <div className="fw-7" style={{ fontSize: 14 }}>{title}</div>
      {sub && <div className="muted text-sm mt-4" style={{ maxWidth: 420, margin: "4px auto 0" }}>{sub}</div>}
      {action && <div className="mt-16">{action}</div>}
    </div>
  );
}

function Tabs({ tabs, active, onChange, right }) {
  return (
    <div className="row-between" style={{ borderBottom: "1px solid var(--border)" }}>
      <div className="tabs" style={{ borderBottom: 0 }}>
        {tabs.map(t => (
          <button key={t.id} className={"tab" + (active === t.id ? " active" : "")} onClick={() => onChange(t.id)}>
            {t.label}
            {t.count != null && <span className="count">{t.count}</span>}
          </button>
        ))}
      </div>
      {right && <div className="row gap-8" style={{ paddingBottom: 6 }}>{right}</div>}
    </div>
  );
}

function Field({ label, sub, children, hint, required }) {
  return (
    <div>
      {label && (
        <div className="row-between" style={{ marginBottom: 6 }}>
          <label className="field-label" style={{ marginBottom: 0 }}>{label}{required && <span style={{ color: "var(--red)" }}> *</span>}</label>
          {hint && <span className="text-xs muted">{hint}</span>}
        </div>
      )}
      {children}
      {sub && <div className="field-sub">{sub}</div>}
    </div>
  );
}

function Swatch({ hex, name }) {
  return (
    <div>
      <div className="swatch" style={{ background: hex }}>
        <span className="hex">{hex.toUpperCase()}</span>
      </div>
      {name && <div className="text-xs muted mt-8 fw-6">{name}</div>}
    </div>
  );
}

function Drop({ title = "Drop files or click to upload", sub = "PNG, JPG, SVG, PDF — up to 25MB", icon = "upload" }) {
  return (
    <button className="drop" style={{ width: "100%" }}>
      <Icon name={icon} size={22} />
      <div className="t mt-8">{title}</div>
      <div className="s">{sub}</div>
    </button>
  );
}

function CopyBtn({ text, onCopy, size = "sm" }) {
  const ctx = React.useContext(AppCtx);
  return (
    <Btn
      size={size}
      icon="copy"
      onClick={() => { try { navigator.clipboard.writeText(text || ""); } catch(e) {} ctx?.showToast("Copied to clipboard"); onCopy?.(); }}
    >
      Copy
    </Btn>
  );
}

function ToggleRow({ label, sub, checked, onChange }) {
  return (
    <div className="row-between" style={{ padding: "10px 0" }}>
      <div>
        <div className="fw-6 text-sm">{label}</div>
        {sub && <div className="muted text-xs mt-4">{sub}</div>}
      </div>
      <button
        onClick={() => onChange?.(!checked)}
        style={{
          width: 36, height: 22, borderRadius: 99,
          background: checked ? "var(--yellow)" : "var(--surface-3)",
          border: "1px solid " + (checked ? "var(--yellow-deep)" : "var(--border-strong)"),
          position: "relative", transition: "background .15s, border-color .15s",
          flex: "none",
        }}
        aria-pressed={checked}
      >
        <span style={{
          position: "absolute", top: 2, left: checked ? 16 : 2,
          width: 16, height: 16, borderRadius: 999,
          background: checked ? "var(--fg)" : "white",
          boxShadow: "var(--shadow-sm)", transition: "left .15s",
        }} />
      </button>
    </div>
  );
}

function MetricRow({ label, value, bar, tone = "yellow" }) {
  return (
    <div className="col" style={{ gap: 6 }}>
      <div className="row-between text-sm">
        <div className="muted fw-6">{label}</div>
        <div className="fw-7">{value}</div>
      </div>
      {bar != null && (
        <div className="meter"><span style={{ width: bar + "%", background: tone === "yellow" ? "var(--yellow)" : tone === "blue" ? "var(--blue)" : "var(--green)" }} /></div>
      )}
    </div>
  );
}

function Steps({ steps, current }) {
  return (
    <div className="steps">
      {steps.map((s, i) => (
        <React.Fragment key={s}>
          <div className={"step" + (i === current ? " active" : i < current ? " done" : "")}>
            <span className="n">{i < current ? <Icon name="check" size={13} stroke={2.4} /> : i + 1}</span>
            <span>{s}</span>
          </div>
          {i < steps.length - 1 && <div className="step-line" />}
        </React.Fragment>
      ))}
    </div>
  );
}

function GenerationOverlay({ pack, progress }) {
  if (!pack) return null;
  return (
    <div className="scrim">
      <div className="sheet" style={{ maxWidth: 480 }}>
        <div className="card-pad-lg" style={{ textAlign: "center" }}>
          <div className="ai-chip mt-4" style={{ display: "inline-flex" }}>
            <Icon name="sparkle" size={11} stroke={2} />
            AI generating
          </div>
          <div style={{ marginTop: 16, fontSize: 20, fontWeight: 800, letterSpacing: "-0.02em" }}>{pack.name}</div>
          <div className="muted text-sm mt-8">{pack.desc}</div>
          <div className="gen-bar mt-24"><span /></div>
          <div className="row-between text-xs muted mt-12">
            <span>Analysing assets · drafting copy · scoring brand fit…</span>
            <span className="mono fw-7" style={{ color: "var(--fg)" }}>{Math.min(100, Math.round(progress))}%</span>
          </div>
        </div>
      </div>
    </div>
  );
}

/* small ZIP folder visual */
function ZipTree() {
  return (
    <pre className="tree" style={{ margin: 0 }}>{`📦 renoo-launch-pack-v1.zip
├─ 📁 social/
│  ├─ instagram-posts.md
│  ├─ instagram-carousels.md
│  ├─ linkedin.md
│  ├─ tiktok-captions.md
│  └─ calendar-30d.csv
├─ 📁 video/
│  ├─ youtube-outlines.md
│  ├─ shorts-scripts.md
│  ├─ reels-scripts.md
│  └─ shot-lists.md
├─ 📁 ads/
│  ├─ meta-ads.md
│  ├─ google-ads.md
│  ├─ tiktok-ads.md
│  └─ ab-variants.csv
├─ 📁 app-store/
│  ├─ app-store-listing.md
│  ├─ play-store-listing.md
│  └─ screenshot-captions.md
├─ 📁 landing/
│  ├─ landing-copy.md
│  └─ meta.md
├─ 📁 seo/
│  ├─ titles-meta.md
│  ├─ blog-ideas.md
│  └─ keyword-clusters.csv
├─ 📁 prompts/
│  ├─ claude-design/
│  └─ codex/
├─ 📁 press/
│  ├─ press-release.md
│  ├─ producthunt.md
│  └─ email-sequence.md
└─ 📄 project.json`}</pre>
  );
}

Object.assign(window, {
  Pill, Btn, IconBtn, Card, StatTile, AppIcon, ProjectStatus,
  Section, Empty, Tabs, Field, Swatch, Drop, CopyBtn, ToggleRow,
  MetricRow, Steps, GenerationOverlay, ZipTree,
});
