/* KitRate — admin benchmark / rate engine editor */

function NumCell({ value, onChange, width = 80, pct }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 3 }}>
      {!pct && <span style={{ color: "var(--muted)", fontSize: 12 }}>$</span>}
      <input className="kr-input kr-num" value={value ?? ""} style={{ width, padding: "5px 8px", fontSize: 12.5 }}
        onChange={(e) => {
          const v = e.target.value.replace(/[^0-9.]/g, "");
          onChange(v === "" ? 0 : parseFloat(v));
        }} />
      {pct && <span style={{ color: "var(--muted)", fontSize: 12 }}>%</span>}
    </span>
  );
}

function StatusSelect({ value, onChange }) {
  return (
    <select className="kr-select" value={value} style={{ width: 130, padding: "5px 26px 5px 8px", fontSize: 12 }} onChange={(e) => onChange(e.target.value)}>
      <option value="active">active</option>
      <option value="experimental">experimental</option>
      <option value="outdated">outdated</option>
    </select>
  );
}

/* live impact preview: shows a rate recomputed from current draft */
function ImpactStrip({ bm, profile }) {
  const rates = useMemo(() => KitRateEngine.computeRates(profile, bm), [bm, profile]);
  const reel = rates.items.find(i => i.id === "ig_reel") || rates.items[0];
  return (
    <div style={{ display: "flex", gap: 18, alignItems: "center", background: "var(--ink)", color: "var(--paper)", borderRadius: 10, padding: "12px 18px", flexWrap: "wrap" }}>
      <span style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.12em", textTransform: "uppercase", opacity: 0.6 }}>Live impact preview</span>
      <span style={{ fontSize: 13 }}>{profile.name} · {reel ? reel.label : "—"}:</span>
      <span className="kr-serif" style={{ fontSize: 19, color: "#9DB1E8", whiteSpace: "nowrap" }}>{reel ? KitRateEngine.fmtRange(reel.low, reel.high) : "—"}</span>
      <span style={{ fontSize: 11.5, opacity: 0.55 }}>Recomputes as you edit — every creator's dashboard updates the same way.</span>
    </div>
  );
}

function AdminBaseRates({ bm, update }) {
  const tiers = bm.followerTiers;
  return (
    <div>
      <p style={{ fontSize: 13, color: "var(--muted)", marginBottom: 16 }}>Base USD ranges by deliverable × follower tier. Deliverables marked <em>outdated</em> are excluded from creator rate cards.</p>
      {bm.baseRates.map((row, ri) => (
        <div key={row.id} className="kr-card" style={{ padding: "14px 18px", marginBottom: 12 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 10, flexWrap: "wrap" }}>
            <strong style={{ fontSize: 13.5 }}>{row.label}</strong>
            <span className="kr-chip" style={{ fontSize: 9.5 }}>{row.platform}</span>
            <div style={{ flex: 1 }}></div>
            <StatusSelect value={row.status} onChange={(v) => update(d => { d.baseRates[ri].status = v; })} />
          </div>
          <div style={{ display: "flex", gap: 16, flexWrap: "wrap" }}>
            {tiers.map(t => (
              <div key={t.id}>
                <div style={{ fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 4 }}>{t.label}</div>
                <div style={{ display: "flex", gap: 4, alignItems: "center" }}>
                  <NumCell value={row.tiers[t.id]?.[0]} width={68} onChange={(v) => update(d => { d.baseRates[ri].tiers[t.id][0] = v; })} />
                  <span style={{ color: "var(--muted)" }}>–</span>
                  <NumCell value={row.tiers[t.id]?.[1]} width={68} onChange={(v) => update(d => { d.baseRates[ri].tiers[t.id][1] = v; })} />
                </div>
              </div>
            ))}
          </div>
          <input className="kr-input" value={row.source} placeholder="Source note" style={{ marginTop: 10, fontSize: 12, color: "var(--muted)" }}
            onChange={(e) => update(d => { d.baseRates[ri].source = e.target.value; })} />
        </div>
      ))}
    </div>
  );
}

function MultTable({ title, desc, rows, cols, update, path }) {
  return (
    <div className="kr-card" style={{ padding: "16px 20px", marginBottom: 16 }}>
      <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 2 }}>{title}</div>
      <p style={{ fontSize: 12.5, color: "var(--muted)", marginBottom: 12 }}>{desc}</p>
      <table className="kr-table">
        <thead><tr>{cols.map(c => <th key={c[0]}>{c[1]}</th>)}</tr></thead>
        <tbody>
          {rows.map((r, i) => (
            <tr key={r.id}>
              {cols.map(([key]) => (
                <td key={key}>
                  {key === "mult" ? (
                    <input className="kr-input kr-num" value={r.mult} style={{ width: 70, padding: "5px 8px", fontSize: 12.5 }}
                      onChange={(e) => update(d => { d[path][i].mult = parseFloat(e.target.value.replace(/[^0-9.]/g, "")) || 0; })} />
                  ) : key === "status" && r.status !== undefined ? (
                    <StatusSelect value={r.status} onChange={(v) => update(d => { d[path][i].status = v; })} />
                  ) : key === "maxRatio" || key === "maxRate" ? (
                    <span className="kr-num" style={{ color: "var(--muted)" }}>{r[key] == null ? "∞" : "< " + r[key]}</span>
                  ) : (
                    <span style={{ fontSize: 13 }}>{r[key]}</span>
                  )}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function AdminMultipliers({ bm, update }) {
  return (
    <div>
      <MultTable title="Average-view performance tiers" desc="Avg short-form views ÷ followers. Rewards creators whose reach beats their audience size." path="viewTiers" update={update}
        rows={bm.viewTiers} cols={[["label", "Tier"], ["maxRatio", "Views/followers"], ["mult", "Multiplier"]]} />
      <MultTable title="Engagement-rate multipliers" desc="(Likes + comments) ÷ followers, trailing 30 days." path="engagementTiers" update={update}
        rows={bm.engagementTiers} cols={[["label", "Tier"], ["maxRate", "ER %"], ["mult", "Multiplier"]]} />
      <MultTable title="Niche / category multipliers" desc="Demand-side adjustment by content category." path="nicheMults" update={update}
        rows={bm.nicheMults} cols={[["label", "Niche"], ["mult", "Multiplier"], ["status", "Status"]]} />
      <MultTable title="Regional adjustments" desc="Relative to the US/Canada baseline." path="regionMults" update={update}
        rows={bm.regionMults} cols={[["label", "Region"], ["mult", "Multiplier"], ["status", "Status"]]} />
    </div>
  );
}

function AdminAddons({ bm, update }) {
  return (
    <div className="kr-card" style={{ padding: "16px 20px" }}>
      <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 2 }}>Add-ons & licensing fees</div>
      <p style={{ fontSize: 12.5, color: "var(--muted)", marginBottom: 12 }}>Expressed as % of the deliverable rate they attach to.</p>
      <table className="kr-table">
        <thead><tr><th>Add-on</th><th>Uplift</th><th>Status</th><th>Source</th></tr></thead>
        <tbody>
          {bm.addons.map((a, i) => (
            <tr key={a.id}>
              <td style={{ fontWeight: 500, fontSize: 13 }}>{a.label}</td>
              <td><NumCell pct value={a.pct} width={56} onChange={(v) => update(d => { d.addons[i].pct = v; })} /></td>
              <td><StatusSelect value={a.status} onChange={(v) => update(d => { d.addons[i].status = v; })} /></td>
              <td><input className="kr-input" value={a.source} style={{ fontSize: 12, padding: "5px 8px" }} onChange={(e) => update(d => { d.addons[i].source = e.target.value; })} /></td>
            </tr>
          ))}
        </tbody>
      </table>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 16, paddingTop: 14, borderTop: "1px solid var(--line)" }}>
        <span style={{ fontSize: 13, fontWeight: 500 }}>Monthly retainer discount</span>
        <NumCell pct value={bm.retainer.discountPct} width={56} onChange={(v) => update(d => { d.retainer.discountPct = v; })} />
        <span style={{ fontSize: 12, color: "var(--muted)" }}>vs. à-la-carte totals</span>
      </div>
    </div>
  );
}

function AdminSources({ bm, update }) {
  return (
    <div>
      <div className="kr-card" style={{ padding: "16px 20px", marginBottom: 16 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
          <div>
            <div style={{ fontWeight: 600, fontSize: 14 }}>Benchmark sources</div>
            <p style={{ fontSize: 12.5, color: "var(--muted)" }}>What the “Current research” panel shows creators.</p>
          </div>
          <button className="kr-btn kr-btn-secondary kr-btn-sm" onClick={() => update(d => { d.sources.push({ id: "s" + Date.now(), name: "New source", category: "Agency pricing guide", checked: new Date().toISOString().slice(0, 10), status: "experimental" }); })}>
            <KrIcon d={ICONS.plus} size={13} /> Add source
          </button>
        </div>
        <table className="kr-table">
          <thead><tr><th>Name</th><th>Category</th><th>Last checked</th><th>Status</th><th></th></tr></thead>
          <tbody>
            {bm.sources.map((s, i) => (
              <tr key={s.id}>
                <td><input className="kr-input" value={s.name} style={{ fontSize: 12.5, padding: "5px 8px", minWidth: 200 }} onChange={(e) => update(d => { d.sources[i].name = e.target.value; })} /></td>
                <td><input className="kr-input" value={s.category} style={{ fontSize: 12.5, padding: "5px 8px" }} onChange={(e) => update(d => { d.sources[i].category = e.target.value; })} /></td>
                <td><input className="kr-input kr-num" value={s.checked} style={{ fontSize: 12, padding: "5px 8px", width: 110 }} onChange={(e) => update(d => { d.sources[i].checked = e.target.value; })} /></td>
                <td><StatusSelect value={s.status} onChange={(v) => update(d => { d.sources[i].status = v; })} /></td>
                <td><button className="kr-btn kr-btn-ghost kr-btn-sm" onClick={() => update(d => { d.sources.splice(i, 1); })} aria-label="Remove source"><KrIcon d={ICONS.x} size={12} /></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <IntegrationNote>
        In production, sources and benchmark rows live in an admin database with role-based access; the “Current research” panel and rate engine read the published version via API. A research workflow (quarterly review reminders, diff view) would hang off this table.
      </IntegrationNote>
    </div>
  );
}

function AdminHistory({ bm }) {
  return (
    <div className="kr-card" style={{ padding: "16px 20px" }}>
      <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 14 }}>Version history</div>
      {bm.history.map((h, i) => (
        <div key={i} style={{ display: "grid", gridTemplateColumns: "110px 90px 1fr", gap: 16, padding: "10px 0", borderBottom: i < bm.history.length - 1 ? "1px solid var(--line)" : "none", fontSize: 13 }}>
          <span className="kr-num" style={{ color: "var(--accent)", fontWeight: 500 }}>v{h.version}</span>
          <span className="kr-num" style={{ color: "var(--muted)" }}>{h.date}</span>
          <span style={{ color: "var(--ink-2)" }}>{h.note} <em style={{ color: "var(--muted)" }}>— {h.author}</em></span>
        </div>
      ))}
    </div>
  );
}

function Admin({ bm, setBm, profile }) {
  const [tab, setTab] = useState("rates");
  const [toast, toastNode] = useToast();
  const [dirty, setDirty] = useState(false);

  const update = (fn) => {
    const draft = JSON.parse(JSON.stringify(bm));
    fn(draft);
    setBm(draft); // persists + live-recomputes creator rates
    setDirty(true);
  };

  const publish = () => {
    const draft = JSON.parse(JSON.stringify(bm));
    const today = new Date().toISOString().slice(0, 10);
    const parts = draft.version.split(".");
    draft.version = parts[0] + "." + parts[1] + "." + (parseInt(parts[2] || 0) + 1);
    draft.updatedAt = today;
    draft.history.unshift({ version: draft.version, date: today, author: "You (admin)", note: "Manual benchmark update via admin rate engine." });
    setBm(draft); setDirty(false);
    toast("Published v" + draft.version + " — creator rates updated");
  };

  const tabs = [["rates", "Base rates"], ["mults", "Multipliers"], ["addons", "Add-ons"], ["sources", "Sources"], ["history", "History"]];

  return (
    <div style={{ maxWidth: 1080, margin: "0 auto", padding: "40px 32px 80px" }} data-screen-label="Admin rate engine" className="kr-fade-in">
      <SectionHead eyebrow="Internal · Admin" title="Benchmark rate engine"
        desc="Edit benchmarks, multipliers and fees without redeploying. Changes recompute every creator's suggested rates instantly."
        right={<>
          <button className="kr-btn kr-btn-secondary" onClick={() => { setBm(window.resetBenchmarks()); setDirty(false); toast("Reset to default benchmarks"); }}>
            <KrIcon d={ICONS.refresh} size={14} /> Reset defaults
          </button>
          <button className="kr-btn kr-btn-primary" onClick={publish}>{dirty ? "Publish update" : "Publish version bump"}</button>
        </>} />

      <div style={{ display: "flex", gap: 14, alignItems: "center", marginBottom: 18, flexWrap: "wrap" }}>
        <span className="kr-chip kr-chip-accent">v{bm.version}</span>
        <span style={{ fontSize: 12.5, color: "var(--muted)" }}>Last updated {bm.updatedAt}</span>
        {dirty && <span className="kr-chip kr-chip-warn">Unpublished edits — live for creators, not yet versioned</span>}
      </div>

      <div style={{ marginBottom: 22 }}><ImpactStrip bm={bm} profile={profile} /></div>

      <div style={{ display: "flex", gap: 4, borderBottom: "1px solid var(--line-strong)", marginBottom: 22, overflowX: "auto" }}>
        {tabs.map(([k, lbl]) => (
          <button key={k} onClick={() => setTab(k)} style={{
            background: "none", border: "none", padding: "9px 16px", fontSize: 13.5, whiteSpace: "nowrap",
            fontWeight: tab === k ? 600 : 500, color: tab === k ? "var(--ink)" : "var(--muted)",
            borderBottom: "2px solid " + (tab === k ? "var(--accent)" : "transparent"), marginBottom: -1
          }}>{lbl}</button>
        ))}
      </div>

      <div className="kr-fade-in" key={tab}>
        {tab === "rates" && <AdminBaseRates bm={bm} update={update} />}
        {tab === "mults" && <AdminMultipliers bm={bm} update={update} />}
        {tab === "addons" && <AdminAddons bm={bm} update={update} />}
        {tab === "sources" && <AdminSources bm={bm} update={update} />}
        {tab === "history" && <AdminHistory bm={bm} />}
      </div>
      {toastNode}
    </div>
  );
}

window.Admin = Admin;
