/* global React */
// Terminal LatAm — Optimize screen (real-time cost optimization)

const TO_T = window.T_THEME;
const TO_FM = window.T_FM;
const TO_FS = window.T_FS;
const TO_S = window.TerminalSectionLabel;
const TO_B = window.TerminalBtn;

const OptimizeScreen = () => {
  const D = window.MA_DATA;
  const O = D.optimize;

  // sankey-ish reallocations grouped
  const totalReallocated = O.reallocations.reduce((s,r) => s+r.amt, 0);
  const fromGroups = {};
  const toGroups = {};
  O.reallocations.forEach(r => {
    fromGroups[r.from] = (fromGroups[r.from]||0) + r.amt;
    toGroups[r.to] = (toGroups[r.to]||0) + r.amt;
  });
  const fromArr = Object.entries(fromGroups).sort((a,b)=>b[1]-a[1]);
  const toArr = Object.entries(toGroups).sort((a,b)=>b[1]-a[1]);

  return (
    <div className="ma-pad" style={{ padding: "20px 24px", display: "flex", flexDirection: "column", gap: 22 }}>
      <div>
        <div style={{ fontSize: 10, color: TO_T.mute, letterSpacing: "0.18em", marginBottom: 6 }}>// OPTIMIZE · agent decisions live</div>
        <div style={{ fontFamily: TO_FS, fontSize: 26, fontWeight: 600, color: TO_T.ink }}>El agente optimizando cada minuto · <span style={{ color: TO_T.green }}>{O.savings.today.actions} acciones hoy</span></div>
        <div style={{ fontSize: 11, color: TO_T.mute, marginTop: 4 }}>Bid adjustments · placement reallocations · ledger auditable · cada decisión revertible</div>
      </div>

      {/* SAVINGS LEDGER */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", border: `1px solid ${TO_T.line}` }}>
        {[
          { k: "Hoy", v: O.savings.today.amount, sub: `${O.savings.today.actions} acciones` },
          { k: "Esta semana", v: O.savings.week.amount, sub: `${O.savings.week.actions} acciones` },
          { k: "Este mes", v: O.savings.month.amount, sub: `${O.savings.month.actions} acciones` },
          { k: "YTD", v: O.savings.ytd.amount, sub: "agente desde Q1" },
        ].map((s,i) => (
          <div key={i} style={{ padding: "20px 22px", borderRight: i<3?`1px solid ${TO_T.line}`:"none", background: TO_T.surface }}>
            <div style={{ fontSize: 10, color: TO_T.mute, letterSpacing: "0.14em", marginBottom: 10 }}>AHORRADO · {s.k.toUpperCase()}</div>
            <div style={{ fontFamily: TO_FS, fontSize: 28, fontWeight: 600, color: TO_T.green, letterSpacing: "-0.01em" }}>S/ {s.v.toLocaleString()}</div>
            <div style={{ fontSize: 10, color: TO_T.muteDim, marginTop: 6 }}>{s.sub}</div>
          </div>
        ))}
      </div>

      {/* INTRADAY BIDS + REALLOCATIONS */}
      <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 16 }}>
        <div style={{ border: `1px solid ${TO_T.line}`, background: TO_T.surface, padding: "16px 18px" }}>
          <TO_S text="BID ADJUSTMENTS · CPM hour-by-hour" right={<span style={{ color: TO_T.mute }}>target {O.intradayBids[0].target} · last 24h</span>} />
          <svg width="100%" height="160" viewBox="0 0 600 160" preserveAspectRatio="none" style={{ marginTop: 12, display: "block" }}>
            <line x1="0" y1="80" x2="600" y2="80" stroke={TO_T.muteDim} strokeDasharray="3 3" />
            <text x="6" y="76" fill={TO_T.muteDim} fontSize="9">target {O.intradayBids[0].target}</text>
            {O.intradayBids.map((b, i) => {
              const x = (i / (O.intradayBids.length-1)) * 580 + 10;
              const y = 80 + (b.target - b.cpm) * 8;
              const above = b.cpm > b.target;
              return (
                <g key={i}>
                  <line x1={x} y1={80} x2={x} y2={y} stroke={above ? TO_T.red : TO_T.green} strokeWidth="2" />
                  <circle cx={x} cy={y} r="3" fill={above ? TO_T.red : TO_T.green} />
                  <text x={x} y={155} textAnchor="middle" fill={TO_T.muteDim} fontSize="9">{b.t}</text>
                </g>
              );
            })}
          </svg>
          <div style={{ marginTop: 10 }}>
            {O.intradayBids.slice(-5).reverse().map((b,i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "60px 80px 1fr 90px", gap: 10, padding: "5px 0", fontSize: 11, borderBottom: i<4?`1px dashed ${TO_T.line}`:"none" }}>
                <span style={{ color: TO_T.muteDim, fontFamily: TO_FM }}>{b.t}</span>
                <span style={{ color: b.cpm > b.target ? TO_T.red : TO_T.green, fontFamily: TO_FM }}>CPM {b.cpm}</span>
                <span style={{ color: TO_T.ink, fontSize: 10 }}>{b.action}</span>
                <span style={{ color: TO_T.muteDim, fontSize: 9, textAlign: "right" }}>auto · agent</span>
              </div>
            ))}
          </div>
        </div>

        {/* REALLOCATIONS */}
        <div style={{ border: `1px solid ${TO_T.line}`, background: TO_T.surface, padding: "16px 18px" }}>
          <TO_S text="REASIGNACIONES · today" right={<span style={{ color: TO_T.green }}>S/ {totalReallocated.toLocaleString()}</span>} />
          <div style={{ marginTop: 14, display: "grid", gridTemplateColumns: "1fr 24px 1fr", gap: 12 }}>
            <div>
              <div style={{ fontSize: 9, color: TO_T.red, letterSpacing: "0.14em", marginBottom: 8 }}>FROM · drained</div>
              {fromArr.map(([n,a]) => (
                <div key={n} style={{ marginBottom: 6 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10, color: TO_T.ink, marginBottom: 3 }}>
                    <span>{n}</span><span style={{ color: TO_T.red, fontFamily: TO_FM }}>−S/ {a.toLocaleString()}</span>
                  </div>
                  <div style={{ height: 3, background: TO_T.line }}>
                    <div style={{ width: `${(a/totalReallocated)*100}%`, height: "100%", background: TO_T.red, opacity: 0.75 }} />
                  </div>
                </div>
              ))}
            </div>
            <div style={{ alignSelf: "stretch", display: "flex", flexDirection: "column", justifyContent: "center", color: TO_T.amber, fontSize: 16, alignItems: "center" }}>
              <span>→</span>
            </div>
            <div>
              <div style={{ fontSize: 9, color: TO_T.green, letterSpacing: "0.14em", marginBottom: 8 }}>TO · funded</div>
              {toArr.map(([n,a]) => (
                <div key={n} style={{ marginBottom: 6 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10, color: TO_T.ink, marginBottom: 3 }}>
                    <span>{n}</span><span style={{ color: TO_T.green, fontFamily: TO_FM }}>+S/ {a.toLocaleString()}</span>
                  </div>
                  <div style={{ height: 3, background: TO_T.line }}>
                    <div style={{ width: `${(a/totalReallocated)*100}%`, height: "100%", background: TO_T.green, opacity: 0.75 }} />
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* BIDDERS STATUS + LEVERBOARD */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <div style={{ border: `1px solid ${TO_T.line}`, background: TO_T.surface, padding: "16px 18px" }}>
          <TO_S text="BIDDERS · live" right={<span style={{ color: TO_T.muteDim }}>auctions · last 24h</span>} />
          <div style={{ marginTop: 12 }}>
            {O.biddersStatus.map((b,i) => (
              <div key={i} style={{ padding: "10px 0", borderBottom: i<O.biddersStatus.length-1?`1px solid ${TO_T.line}`:"none", display: "grid", gridTemplateColumns: "1fr 1fr 100px", gap: 12, alignItems: "center" }}>
                <div>
                  <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 11, color: TO_T.ink }}>
                    <span style={{ width: 6, height: 6, borderRadius: 99, background: b.status === "live" ? TO_T.green : TO_T.amber, animation: "blink 2s infinite" }} />
                    {b.plat}
                  </div>
                  <div style={{ fontSize: 10, color: TO_T.muteDim, marginTop: 3 }}>{b.lastDecision}</div>
                </div>
                <div style={{ textAlign: "right", fontSize: 10, color: TO_T.mute }}>
                  <div style={{ color: TO_T.cyan, fontFamily: TO_FM, fontSize: 11 }}>{(b.auctions24h/1e6).toFixed(2)}M</div>
                  <div style={{ marginTop: 3 }}>auctions/24h</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <span style={{ fontSize: 10, color: b.status === "live" ? TO_T.green : TO_T.amber, padding: "3px 8px", border: `1px solid ${b.status === "live" ? TO_T.green : TO_T.amber}`, letterSpacing: "0.1em" }}>{b.status.toUpperCase()}</span>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={{ border: `1px solid ${TO_T.line}`, background: TO_T.surface, padding: "16px 18px" }}>
          <TO_S text="LEVERBOARD · contribución a -S/ CPL" right={<span style={{ color: TO_T.green }}>−S/ {O.leverboard.reduce((s,l)=>s+l.delta,0).toFixed(2)} total</span>} />
          <div style={{ marginTop: 12 }}>
            {O.leverboard.map((l,i) => {
              const max = Math.max(...O.leverboard.map(x => x.delta));
              return (
                <div key={i} style={{ padding: "9px 0", borderBottom: i<O.leverboard.length-1?`1px dashed ${TO_T.line}`:"none" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, marginBottom: 4 }}>
                    <span style={{ color: TO_T.ink }}>{l.lever}</span>
                    <span style={{ color: TO_T.green, fontFamily: TO_FM }}>−S/ {l.delta.toFixed(2)}</span>
                  </div>
                  <div style={{ height: 4, background: TO_T.line }}>
                    <div style={{ width: `${(l.delta/max)*100}%`, height: "100%", background: l.tier === "high" ? TO_T.green : l.tier === "med" ? TO_T.amber : TO_T.cyan, opacity: 0.85 }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* AGENT NOTE */}
      <div style={{ border: `1px solid ${TO_T.amber}`, borderLeftWidth: 3, padding: "14px 18px", background: TO_T.surface }}>
        <div style={{ fontSize: 10, color: TO_T.amber, letterSpacing: "0.16em", marginBottom: 8 }}>AGENT · próxima ventana de optimización</div>
        <div style={{ fontSize: 11, color: TO_T.ink, lineHeight: 1.6 }}>
          12 min · revisión de bid pacing intra-hora. Cualquier acción &gt; <b style={{ color: TO_T.amber }}>S/ {D.actions.autoApproveBudget.toLocaleString()}</b> aparecerá en tu Inbox.
          Cambios entre <b>S/ 100 - {D.actions.autoApproveBudget.toLocaleString()}</b> se ejecutan auto y quedan en este ledger, revertibles 14d.
        </div>
      </div>
    </div>
  );
};

window.OptimizeScreen = OptimizeScreen;
