// A/B testing across channels — compare caption variants, conclude, pick a winner.

function ExperimentsPage() {
  const hub = window.useClearCast();
  const data = hub.data || {};
  const experiments = data.experiments || [];
  const platformList = Object.keys(Platforms).slice(0, 7);
  const [name, setName] = React.useState("");
  const [platform, setPlatform] = React.useState("instagram");
  const [a, setA] = React.useState("");
  const [b, setB] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  const create = async () => {
    if (!name.trim()) { hub.toast("Name your test"); return; }
    if (!a.trim() || !b.trim()) { hub.toast("Fill in both variants"); return; }
    setBusy(true);
    try {
      await hub.actions.createExperiment({ name: name.trim(), platforms: [platform], variants: [{ label: "A", caption: a.trim() }, { label: "B", caption: b.trim() }] });
      setName(""); setA(""); setB("");
    } finally { setBusy(false); }
  };

  return (
    <div className="page experiments-page">
      <div className="card" style={{ padding: 20, marginBottom: 16 }}>
        <h3 style={{ margin: "0 0 4px", fontSize: 15 }}>New A/B test</h3>
        <div className="muted" style={{ fontSize: 12.5, marginBottom: 14 }}>Compare two captions, conclude the test, and we'll pick the higher-performing variant.</div>
        <div style={{ display: "flex", gap: 10, marginBottom: 10, flexWrap: "wrap" }}>
          <input className="input" placeholder="Test name (e.g. Spring hook test)" value={name} onChange={(e) => setName(e.target.value)} style={{ flex: 1, minWidth: 200 }} />
          <select className="input" value={platform} onChange={(e) => setPlatform(e.target.value)} style={{ width: 160 }}>
            {platformList.map((id) => <option key={id} value={id}>{Platforms[id]?.name || id}</option>)}
          </select>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          <textarea className="input" placeholder="Variant A caption" value={a} onChange={(e) => setA(e.target.value)} style={{ minHeight: 70, resize: "vertical" }} />
          <textarea className="input" placeholder="Variant B caption" value={b} onChange={(e) => setB(e.target.value)} style={{ minHeight: 70, resize: "vertical" }} />
        </div>
        <button className="btn btn-primary" disabled={busy} onClick={create} style={{ marginTop: 12 }}><Icon.Bar width="14" height="14" /> {busy ? "Starting…" : "Start test"}</button>
      </div>

      <div style={{ display: "grid", gap: 12 }}>
        {experiments.map((exp) => (
          <div key={exp.id} className="card" style={{ padding: 16 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
              <PlatformIcon id={exp.platforms[0]} size={18} />
              <b style={{ fontSize: 14 }}>{exp.name}</b>
              <span className={`pill ${exp.status === "complete" ? "ok" : "info"}`} style={{ padding: "2px 8px", fontSize: 10.5, textTransform: "capitalize" }}>{exp.status}</span>
              <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
                {exp.status === "running" && <button className="btn btn-sm btn-primary" onClick={() => hub.actions.concludeExperiment(exp.id)}>Conclude test</button>}
                <button className="btn btn-sm" onClick={() => hub.actions.deleteExperiment(exp.id)} style={{ color: "var(--danger)" }}>Delete</button>
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              {exp.variants.map((v) => {
                const won = exp.winner === v.label;
                return (
                  <div key={v.label} style={{ padding: 12, borderRadius: 12, background: won ? "var(--accent-softer)" : "var(--bg-2)", border: `1px solid ${won ? "rgba(20,184,138,0.4)" : "var(--border)"}` }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 6 }}>
                      <b style={{ fontSize: 13 }}>Variant {v.label}</b>
                      {won && <span className="pill ok" style={{ padding: "1px 7px", fontSize: 10 }}>Winner</span>}
                    </div>
                    <div className="muted" style={{ fontSize: 12.5, marginBottom: 8, lineHeight: 1.5 }}>{v.caption}</div>
                    {v.metrics ? (
                      <div style={{ display: "flex", gap: 14, fontSize: 12 }}>
                        <span><b>{v.metrics.impressions.toLocaleString()}</b> <span className="muted">impr</span></span>
                        <span><b>{v.metrics.ctr}%</b> <span className="muted">CTR</span></span>
                        <span><b>{v.metrics.engagementRate}%</b> <span className="muted">eng</span></span>
                      </div>
                    ) : <div className="faint" style={{ fontSize: 11.5 }}>Awaiting results — conclude to compare</div>}
                  </div>
                );
              })}
            </div>
          </div>
        ))}
        {!experiments.length && <div className="card" style={{ padding: 28, textAlign: "center" }}><div className="muted" style={{ fontSize: 13 }}>No tests yet — start one above to find your best-performing caption.</div></div>}
      </div>
    </div>
  );
}

window.ExperimentsPage = ExperimentsPage;
