// Pricing Matrix board — shows the OXIDE pricing matrix (language × platform ×
// deliverable × CPM/CPV) as a departure-board style panel, plus a YouTube
// creator selector that fetches live stats via the YouTube API and compares
// the creator's real CPM/CPV against the matrix expected range.
const { useState: usePB, useMemo: usePBMemo } = React;

function PricingMatrixBoard({ creators }) {
  const T = window.t || (s => s);
  const M = (window.CRM && window.CRM.PRICING_MATRIX) || {};
  const [sel, setSel] = usePB("");
  const [loading, setLoading] = usePB(false);
  const [result, setResult] = usePB(null);
  const [error, setError] = usePB(null);

  // YouTube creators only (have a youtube channel with a URL)
  const ytCreators = usePBMemo(() => {
    return (creators || []).filter(c => {
      if (c.backlogAddedAt) return false;
      const chans = (c.channels && c.channels.length) ? c.channels : [{ platform: c.platform, url: c.channelUrl || c.url }];
      return chans.some(ch => ch.platform === "youtube" && ch.url);
    });
  }, [creators]);

  const LANGS = [
    { k: "en", label: "EN", name: "English", accent: "#ef4444" },
    { k: "de", label: "DE", name: "German", accent: "#3b82f6" },
    { k: "fr", label: "FR", name: "French", accent: "#f59e0b" },
  ];
  const ROWS = [
    { key: "youtube_dedicated", platform: "youtube", label: "YouTube · Dedicated", unit: "CPM" },
    { key: "youtube", platform: "youtube", label: "YouTube · Integration", unit: "CPM" },
    { key: "twitch", platform: "twitch", label: "Twitch · 1h stream", unit: "CPV" },
    { key: "tiktok", platform: "tiktok", label: "TikTok · Video + Spark", unit: "CPM" },
  ];

  const runCompare = async () => {
    setError(null); setResult(null);
    const c = ytCreators.find(x => x.id === sel);
    if (!c) { setError(T("Pick a YouTube creator first")); return; }
    if (!window.youtube || !window.youtube.hasKey()) { setError("YouTube API key not set"); return; }
    const chans = (c.channels && c.channels.length) ? c.channels : [{ platform: c.platform, url: c.channelUrl || c.url }];
    const yt = chans.find(ch => ch.platform === "youtube" && ch.url);
    setLoading(true);
    try {
      const stats = await window.youtube.fetchChannelStats(yt.url, { sampleSize: 20 });
      const views = stats.medianViews || stats.avgViews || 0;
      const priceEUR = c.priceEUR != null ? c.priceEUR : (window.fx ? Math.round(window.fx.toEUR(c.price || 0, c.currency || "RUB")) : (c.price || 0));
      const realCpm = views > 0 && priceEUR > 0 ? +((priceEUR / views) * 1000).toFixed(2) : null;
      const realCpv = views > 0 && priceEUR > 0 ? +((priceEUR / views)).toFixed(4) : null;
      // Matrix expectation for this creator's language + deliverable form
      const mp = window.CRM.marketPrice({ ...c, subs: stats.subs || c.subs, avgViews: views });
      setResult({ creator: c, stats, views, priceEUR, realCpm, realCpv, mp });
    } catch (e) {
      setError(e.message || String(e));
    } finally {
      setLoading(false);
    }
  };

  const fmtRange = (arr, suffix) => `${arr[0]}–${arr[1]}${suffix || ""}`;

  return (
    <div className="section-block">
      <div className="section-block-title">
        <span className="icon"><IconChart size={14} /></span>
        {T("Pricing Matrix")}
        <span className="meta">{T("CPM / CPV reference · all in source currency")}</span>
      </div>

      {/* Board */}
      <div className="pm-board">
        <div className="pm-row pm-head">
          <div className="pm-deliv">{T("Deliverable")}</div>
          {LANGS.map(l => (
            <div key={l.k} className="pm-cell" style={{ color: l.accent }}>
              <b>{l.label}</b> <span className="pm-langname">{l.name}</span>
            </div>
          ))}
        </div>
        {ROWS.map(r => (
          <div key={r.key} className="pm-row">
            <div className="pm-deliv">
              <PlatformBadge platform={r.platform} size={14} />
              <span>{r.label}</span>
            </div>
            {LANGS.map(l => {
              const tbl = M[l.k] || {};
              const range = tbl[r.key];
              const cur = tbl.currency === "USD" ? "$" : "€";
              return (
                <div key={l.k} className="pm-cell pm-price" style={{ color: l.accent }}>
                  {range ? `${cur}${fmtRange(range)}` : "—"}
                  <span className="pm-unit">{r.unit}</span>
                </div>
              );
            })}
          </div>
        ))}
      </div>

      {/* YouTube live compare */}
      <div className="pm-compare">
        <div className="pm-compare-head">
          <IconYTInlineSm />
          <b>{T("Compare a YouTube creator live")}</b>
        </div>
        <div className="row gap-8" style={{ flexWrap: "wrap", alignItems: "center" }}>
          <select value={sel} onChange={e => { setSel(e.target.value); setResult(null); setError(null); }} style={{ minWidth: 220, padding: "7px 10px", borderRadius: 8, border: "1px solid var(--border-default)", background: "var(--bg-app)", color: "var(--text-primary)" }}>
            <option value="">{T("Select YouTube creator…")}</option>
            {ytCreators.map(c => (
              <option key={c.id} value={c.id}>{c.name} — {c.deliverableForm || "integration"}</option>
            ))}
          </select>
          <button className="btn primary" onClick={runCompare} disabled={loading || !sel}>
            {loading ? T("Fetching…") : T("Fetch & compare")}
          </button>
          {ytCreators.length === 0 && <span className="small muted">{T("No creators with a YouTube channel yet")}</span>}
        </div>
        {error && <div className="small" style={{ color: "var(--danger)", marginTop: 10 }}>{error}</div>}
        {result && <CompareResult r={result} T={T} />}
      </div>
    </div>
  );
}

function CompareResult({ r, T }) {
  const mp = r.mp || {};
  const cur = mp.matrixCur === "USD" ? "$" : "€";
  // Matrix CPM range is in source currency; show as-is for reference.
  const cpmRange = mp.cpmRange ? `${cur}${mp.cpmRange[0]}–${mp.cpmRange[1]}` : "—";
  const cpvRange = mp.cpvRange ? `${cur}${mp.cpvRange[0].toFixed(3)}–${mp.cpvRange[1].toFixed(3)}` : "—";
  const formLabel = mp.deliverable === "youtube_dedicated" ? "Dedicated" : "Integration";
  // Verdict: compare real CPM (EUR) vs matrix midpoint (convert matrix to EUR)
  const toEUR = (v) => mp.matrixCur === "USD" && window.fx ? window.fx.toEUR(v, "USD") : v;
  const matMidEur = mp.cpmRange ? (toEUR(mp.cpmRange[0]) + toEUR(mp.cpmRange[1])) / 2 : null;
  let verdict = null, color = "var(--text-tertiary)";
  if (r.realCpm != null && matMidEur) {
    if (r.realCpm > toEUR(mp.cpmRange[1]) * 1.1) { verdict = T("Above market"); color = "var(--danger)"; }
    else if (r.realCpm < toEUR(mp.cpmRange[0]) * 0.9) { verdict = T("Below market"); color = "#3b82f6"; }
    else { verdict = T("At market"); color = "var(--success)"; }
  }
  return (
    <div className="pm-result" style={{ marginTop: 14 }}>
      <div className="row" style={{ justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
        <div className="row gap-8" style={{ alignItems: "center" }}>
          <b>{r.creator.name}</b>
          <span className="small muted">{(mp.lang || "en").toUpperCase()} · YouTube {formLabel}</span>
        </div>
        {verdict && <span className="small" style={{ color, fontWeight: 700, textTransform: "uppercase", padding: "3px 9px", borderRadius: 999, border: `1px solid ${color}` }}>{verdict}</span>}
      </div>
      <div className="metrics-grid">
        <MetricTile label={T("Median views (last 20)")} value={window.CRM.fmtNum(r.views)} />
        <MetricTile label={T("Subscribers")} value={window.CRM.fmtNum(r.stats.subs)} />
        <MetricTile label={T("Price (EUR)")} value={`${r.priceEUR.toLocaleString("en-US")} €`} />
      </div>
      <div className="metrics-grid" style={{ marginTop: 10 }}>
        <MetricTile label={<>{T("Real CPM")} <span className="small muted">EUR</span></>} value={r.realCpm != null ? `${r.realCpm} €` : "—"} trend={`${T("matrix")}: ${cpmRange}`} />
        <MetricTile label={<>{T("Real CPV")} <span className="small muted">EUR</span></>} value={r.realCpv != null ? `${r.realCpv} €` : "—"} trend={`${T("matrix")}: ${cpvRange}`} />
        <MetricTile label={T("Long / Shorts median")} value={`${window.CRM.fmtNum(r.stats.medianLongFormViews || 0)} / ${window.CRM.fmtNum(r.stats.medianShortsViews || 0)}`} />
      </div>
      <div className="small muted" style={{ marginTop: 8 }}>
        {T("Real CPM/CPV computed from live median views and the agreed price. Matrix shows the expected range for this language and deliverable form.")}
      </div>

      {/* Plain-language report + verdict explanation */}
      {(() => {
        const cpmMatEur = mp.cpmRange ? `${toEUR(mp.cpmRange[0]).toFixed(1)}–${toEUR(mp.cpmRange[1]).toFixed(1)} €` : "—";
        const cpvMatEur = mp.cpvRange ? `${toEUR(mp.cpvRange[0]).toFixed(3)}–${toEUR(mp.cpvRange[1]).toFixed(3)} €` : "—";
        const explainEN = verdict === T("Below market")
          ? `Our CPM (${r.realCpm} €) is below the matrix range (${cpmMatEur}) — we're paying less than the market rate for this format. Good deal.`
          : verdict === T("Above market")
          ? `Our CPM (${r.realCpm} €) is above the matrix range (${cpmMatEur}) — we're overpaying for this format. Consider negotiating down.`
          : `Our CPM (${r.realCpm} €) sits inside the matrix range (${cpmMatEur}) — priced at market for this format.`;
        const explainRU = verdict === T("Below market")
          ? `Наш CPM (${r.realCpm} €) ниже диапазона матрицы (${cpmMatEur}) — платим меньше рынка за этот формат. Выгодно.`
          : verdict === T("Above market")
          ? `Наш CPM (${r.realCpm} €) выше диапазона матрицы (${cpmMatEur}) — переплачиваем за этот формат. Стоит торговаться.`
          : `Наш CPM (${r.realCpm} €) внутри диапазона матрицы (${cpmMatEur}) — цена в рынке для этого формата.`;
        return (
          <div className="pm-report" style={{ marginTop: 12, padding: "12px 14px", borderRadius: 10, background: "var(--bg-app)", border: "1px solid var(--border-subtle)" }}>
            <div className="small" style={{ fontWeight: 700, marginBottom: 6 }}>📋 {T("Report")}</div>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
              <tbody>
                <tr>
                  <td style={{ padding: "3px 0", color: "var(--text-secondary)" }}>CPM</td>
                  <td className="num" style={{ textAlign: "right", fontWeight: 700 }}>{r.realCpm != null ? `${r.realCpm} €` : "—"}</td>
                  <td className="num" style={{ textAlign: "right", color: "var(--text-tertiary)" }}>{T("matrix")} {cpmMatEur}</td>
                </tr>
                <tr>
                  <td style={{ padding: "3px 0", color: "var(--text-secondary)" }}>CPV</td>
                  <td className="num" style={{ textAlign: "right", fontWeight: 700 }}>{r.realCpv != null ? `${r.realCpv} €` : "—"}</td>
                  <td className="num" style={{ textAlign: "right", color: "var(--text-tertiary)" }}>{T("matrix")} {cpvMatEur}</td>
                </tr>
              </tbody>
            </table>
            <div className="small" style={{ marginTop: 8, color: color }}>{explainEN}</div>
            <div className="small" style={{ marginTop: 4, color: color }}>{explainRU}</div>
          </div>
        );
      })()}
    </div>
  );
}

function IconYTInlineSm() {
  return <span style={{ color: "#ff0033", display: "inline-flex" }}><svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor"><path d="M21.6 7.2s-.2-1.4-.8-2c-.7-.8-1.5-.8-1.9-.9C16.2 4.1 12 4.1 12 4.1h0s-4.2 0-6.9.2c-.4.1-1.2.1-1.9.9-.6.6-.8 2-.8 2S2.2 8.8 2.2 10.5v1.6c0 1.7.2 3.3.2 3.3s.2 1.4.8 2c.7.8 1.7.8 2.1.9 1.5.1 6.7.2 6.7.2s4.2 0 6.9-.2c.4-.1 1.2-.1 1.9-.9.6-.6.8-2 .8-2s.2-1.6.2-3.3v-1.6c0-1.7-.2-3.3-.2-3.3zM9.9 14.6V8.9l5.4 2.9-5.4 2.8z"/></svg></span>;
}

Object.assign(window, { PricingMatrixBoard });
