/* global React, PR */
const { useState, useEffect, useCallback } = React;
const { I } = PR;

function CreativeThumb({ thumb, type, status, primaryMetric }) {
  const gid = `cvg_${(thumb.from + thumb.to).replace(/[^a-z0-9]/gi, "")}`;
  const playIcon = (() => {
    if (type === "playable") return (
      <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
        <path d="M9 7v10l7-5z" fill="currentColor" stroke="none"/>
        <circle cx="12" cy="12" r="10" strokeWidth="1.6"/>
      </svg>
    );
    if (type === "static") return (
      <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <rect x="4" y="5" width="16" height="14" rx="1.5"/>
        <circle cx="9" cy="10" r="1.5"/>
        <path d="M4 17l5-5 4 4 3-3 4 4"/>
      </svg>
    );
    return <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>;
  })();

  return (
    <div className="cv-thumb">
      <svg className="cv-thumb-bg" viewBox="0 0 320 200" preserveAspectRatio="none">
        <defs>
          <linearGradient id={gid} x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor={thumb.from} />
            <stop offset="100%" stopColor={thumb.to} />
          </linearGradient>
        </defs>
        <rect width="320" height="200" fill={`url(#${gid})`} />
        <g opacity="0.12" stroke="white" strokeWidth="1" fill="none">
          <circle cx="40" cy="160" r="60"/>
          <circle cx="280" cy="40" r="80"/>
          <path d="M0 100 Q80 60 160 100 T320 100"/>
        </g>
      </svg>
      <div className="cv-thumb-overlay"></div>

      <span className="cv-type-badge">
        {type === "video" && <svg viewBox="0 0 24 24" width="9" height="9" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>}
        {type === "playable" && <svg viewBox="0 0 24 24" width="9" height="9" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="9"/><path d="M9 9l6 3-6 3z" fill="currentColor"/></svg>}
        {type === "static" && <svg viewBox="0 0 24 24" width="9" height="9" fill="currentColor"><rect x="3" y="5" width="18" height="14" rx="1.5"/></svg>}
        {type}
      </span>

      <span className="cv-status-badge" data-s={status}>
        {status === "live" && <span className="pulse"></span>}
        {status}
      </span>

      <div className="cv-play">{playIcon}</div>

      {primaryMetric && (
        <div className="cv-thumb-metric">
          <span className="lbl">{primaryMetric.label}</span>
          <span className={"val " + (primaryMetric.cls || "")}>{primaryMetric.value}</span>
        </div>
      )}
    </div>
  );
}

function CreativeCard({ c }) {
  const targetCPI = c.target?.cpi;
  const cpiOk = c.metrics.cpi != null && targetCPI != null && c.metrics.cpi <= targetCPI;
  const cpiBad = c.metrics.cpi != null && targetCPI != null && c.metrics.cpi > targetCPI;
  const fmt = (v, prefix = "", suf = "") => v == null ? "—" : prefix + (typeof v === "number" ? v.toFixed(1) : v) + suf;

  const primary = c.metrics.cpi != null
    ? { label: "CPI", value: "$" + c.metrics.cpi.toFixed(2), cls: cpiOk ? "good" : cpiBad ? "bad" : "" }
    : null;

  return (
    <div className="cv-card">
      <CreativeThumb thumb={c.thumb} type={c.type} status={c.status} primaryMetric={primary} />
      <div className="cv-body">
        <div className="cv-title-row">
          <div className="cv-title">{c.title}</div>
          {c.network && <span className="cv-network">{c.network}</span>}
        </div>
        <div className="cv-metrics">
          <div className="m"><span className="k">CTR</span><span className={"v " + (c.metrics.ctr == null ? "muted" : "")}>{fmt(c.metrics.ctr, "", "%")}</span></div>
          <div className="m"><span className="k">Hook</span><span className={"v " + (c.metrics.hookRate == null ? "muted" : "")}>{c.metrics.hookRate == null ? "—" : c.metrics.hookRate + "%"}</span></div>
          <div className="m"><span className="k">CR</span><span className={"v " + (c.metrics.cr == null ? "muted" : "")}>{fmt(c.metrics.cr, "", "%")}</span></div>
          <div className="m"><span className="k">IPM</span><span className={"v " + (c.metrics.ipm == null ? "muted" : "")}>{fmt(c.metrics.ipm)}</span></div>
        </div>
        <div className="cv-foot">
          {c.tracker ? (
            <a className="tracker" href="#" onClick={(e) => e.preventDefault()}>
              <svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"><path d="M10 14a4 4 0 0 0 5.6 0l3-3a4 4 0 0 0-5.6-5.6l-1 1M14 10a4 4 0 0 0-5.6 0l-3 3a4 4 0 0 0 5.6 5.6l1-1"/></svg>
              {c.tracker}
            </a>
          ) : <span />}
          <span className="spacer"></span>
          <span>{c.metrics.impressions ? (c.metrics.impressions / 1000).toFixed(0) + "K imp" : "no spend"}</span>
        </div>
      </div>
    </div>
  );
}

function AddCreativeModal({ hypothesisId, onClose, onAdded }) {
  const [form, setForm] = useState({ type: "video", title: "", network: "", status: "draft", tracker: "", target_cpi: "", thumb_from: "#3a2a55", thumb_to: "#7c5fc4" });
  const [saving, setSaving] = useState(false);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSaving(true);
    try {
      const payload = {
        ...form,
        target_cpi: form.target_cpi ? parseFloat(form.target_cpi) : null,
      };
      await fetch(`/api/hypotheses/${hypothesisId}/creatives`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      onAdded();
      onClose();
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 460 }}>
        <div className="modal-head">
          <div className="modal-title">Add creative test</div>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="modal-body">
            <div className="form-row">
              <label className="form-label">Type</label>
              <select className="form-select" value={form.type} onChange={e => set("type", e.target.value)}>
                <option value="video">Video</option>
                <option value="playable">Playable</option>
                <option value="static">Static</option>
              </select>
            </div>
            <div className="form-row">
              <label className="form-label">Title *</label>
              <input className="form-input" required value={form.title} onChange={e => set("title", e.target.value)} placeholder="e.g. Hero loop · 15s" />
            </div>
            <div className="form-row">
              <label className="form-label">Network</label>
              <select className="form-select" value={form.network} onChange={e => set("network", e.target.value)}>
                <option value="">— pick network —</option>
                {["TikTok","Facebook","AppLovin","Unity Ads","Google Ads","ironSource","Applovin MAX"].map(n => <option key={n}>{n}</option>)}
              </select>
            </div>
            <div className="form-row">
              <label className="form-label">Status</label>
              <select className="form-select" value={form.status} onChange={e => set("status", e.target.value)}>
                <option value="draft">Draft</option>
                <option value="live">Live</option>
                <option value="done">Done</option>
                <option value="killed">Killed</option>
              </select>
            </div>
            <div className="form-row">
              <label className="form-label">Target CPI ($)</label>
              <input className="form-input" type="number" step="0.01" value={form.target_cpi} onChange={e => set("target_cpi", e.target.value)} placeholder="e.g. 1.50" />
            </div>
            <div className="form-row">
              <label className="form-label">Tracker ID</label>
              <input className="form-input" value={form.tracker} onChange={e => set("tracker", e.target.value)} placeholder="e.g. JIRA-1234" />
            </div>
            <div className="form-row">
              <label className="form-label">Thumbnail gradient</label>
              <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                <input type="color" value={form.thumb_from} onChange={e => set("thumb_from", e.target.value)} style={{ width: 36, height: 28, border: "1px solid var(--border)", borderRadius: 4, cursor: "pointer" }} />
                <span style={{ color: "var(--text-3)" }}>→</span>
                <input type="color" value={form.thumb_to} onChange={e => set("thumb_to", e.target.value)} style={{ width: 36, height: 28, border: "1px solid var(--border)", borderRadius: 4, cursor: "pointer" }} />
                <div style={{ width: 60, height: 28, borderRadius: 4, background: `linear-gradient(135deg, ${form.thumb_from}, ${form.thumb_to})` }} />
              </div>
            </div>
          </div>
          <div className="modal-foot">
            <button type="button" className="btn btn-ghost" onClick={onClose}>Cancel</button>
            <button type="submit" className="btn btn-primary" disabled={saving}>{saving ? "Adding…" : "Add creative"}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function CreativesPanel({ data, hypothesisId }) {
  const [creatives, setCreatives] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showAdd, setShowAdd] = useState(false);

  const load = useCallback(async () => {
    const resp = await fetch(`/api/hypotheses/${hypothesisId}/creatives`);
    if (resp.ok) setCreatives(await resp.json());
    setLoading(false);
  }, [hypothesisId]);

  useEffect(() => { load(); }, [load]);

  if (loading) return <div style={{ padding: "20px 0", color: "var(--text-3)", fontSize: 13 }}>Loading creatives…</div>;

  const all = creatives;

  if (all.length === 0) {
    return (
      <div className="cv-empty">
        <div className="h">No creative tests yet</div>
        <div>Creative testing runs in parallel to the main pipeline. Add a video, playable, or static creative to start measuring CPI / Hook Rate / CTR.</div>
        <button className="btn btn-primary" style={{ marginTop: 14 }} onClick={() => setShowAdd(true)}>+ Add creative test</button>
        {showAdd && <AddCreativeModal hypothesisId={hypothesisId} onClose={() => setShowAdd(false)} onAdded={load} />}
      </div>
    );
  }

  const live = all.filter(c => c.status === "live").length;
  const cpis = all.filter(c => c.metrics.cpi != null && c.status !== "draft").map(c => c.metrics.cpi);
  const bestCPI = cpis.length ? Math.min(...cpis) : null;
  const totalSpend = all.reduce((s, c) => s + (c.metrics.spend || 0), 0);
  const totalImp = all.reduce((s, c) => s + (c.metrics.impressions || 0), 0);
  const targetCPI = all.find(c => c.target?.cpi)?.target?.cpi;
  const cpiOk = bestCPI != null && targetCPI != null && bestCPI <= targetCPI;

  return (
    <div>
      <div className="cv-summary">
        <div className="cv-stat">
          <span className="k">Best CPI</span>
          <span className={"v " + (cpiOk ? "good" : bestCPI != null ? "bad" : "")}>
            {bestCPI != null ? "$" + bestCPI.toFixed(2) : "—"}
          </span>
        </div>
        {targetCPI && (
          <div className="cv-stat">
            <span className="k">Target</span>
            <span className="v" style={{ color: "var(--text-2)" }}>≤ ${targetCPI.toFixed(2)}</span>
          </div>
        )}
        <div className="cv-divider"></div>
        <div className="cv-stat">
          <span className="k">Live</span>
          <span className="v">{live}<span style={{ color: "var(--text-3)", fontSize: 12 }}>/{all.length}</span></span>
        </div>
        <div className="cv-stat">
          <span className="k">Spend</span>
          <span className="v">{totalSpend >= 1000 ? "$" + (totalSpend / 1000).toFixed(1) + "K" : "$" + totalSpend}</span>
        </div>
        <div className="cv-stat">
          <span className="k">Impressions</span>
          <span className="v">{totalImp >= 1000000 ? (totalImp / 1000000).toFixed(2) + "M" : (totalImp / 1000).toFixed(0) + "K"}</span>
        </div>
        <div style={{ flex: 1 }}></div>
        <button className="btn btn-primary" onClick={() => setShowAdd(true)}>+ Add creative</button>
      </div>

      <div className="cv-grid">
        {all.map(c => <CreativeCard key={c.id} c={c} />)}
      </div>

      {showAdd && <AddCreativeModal hypothesisId={hypothesisId} onClose={() => setShowAdd(false)} onAdded={load} />}
    </div>
  );
}

window.PRCreatives = { CreativesPanel, CreativeThumb };
