/* global React, Ic, Chip, ScoreBar, KPI, Panel, AiBand */

function RFPEngine() {
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">RFP Engine</div>
          <div className="page-sub">Inbound RFP · Costco Q3 Lane Bid · 218 lanes · received 11:14 today</div>
        </div>
        <div className="page-actions">
          <span className="chip accent"><span className="dot pulse" /> AGENT PRICING · 197/218</span>
          <span className="mono dim" style={{ fontSize: 11 }}>EST 4MIN REMAINING</span>
          <button className="btn ghost">Reject RFP</button>
          <button className="btn primary">Send response</button>
        </div>
      </div>

      <div className="grid cols-4 pad" style={{ paddingBottom: 0 }}>
        <KPI label="RFP Volume" value="$4.8M" delta="218 lanes" />
        <KPI label="Priced" value="197" delta="of 218" />
        <KPI label="Avg GM Target" value="18.6%" delta="±1.2pt" />
        <KPI label="Time vs Manual" value="22 min" delta="3 days" deltaKind="down" />
      </div>

      <AiBand
        confidence={91}
        text={<>Keelway priced 197 of 218 lanes in 22 minutes (vs. 3 days manual). <b>12 lanes flagged</b> for human review — capacity tight or insufficient history.</>}
        actions={<>
          <button className="btn ghost sm">Review flagged</button>
          <button className="btn primary sm">Accept all priced</button>
        </>}
      />

      <div style={{ padding: 16 }}>
        <Panel title="LANE-LEVEL PRICING · 218 LANES" actions={
          <div style={{ display: "flex", gap: 6 }}>
            <div className="toggle-row"><button className="on">ALL · 218</button><button>WIN-LIKELY · 142</button><button>FLAGGED · 12</button><button>RISKY · 9</button></div>
          </div>
        }>
          <div style={{ maxHeight: 460, overflowY: "auto" }}>
            <table className="tbl">
              <thead>
                <tr>
                  <th>Lane</th>
                  <th className="num">Volume/wk</th>
                  <th className="num">DAT</th>
                  <th className="num">Our cost</th>
                  <th className="num">Quote</th>
                  <th className="num">GM %</th>
                  <th>Win Prob</th>
                  <th>Reasoning</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {generateRfpLanes(20).map((r, i) => (
                  <tr key={i} className={r.flag ? "ai-row" : ""}>
                    <td style={{ fontSize: 12 }}>{r.lane}</td>
                    <td className="num">{r.vol}</td>
                    <td className="num dim">${r.dat}</td>
                    <td className="num dim">${r.cost}</td>
                    <td className="num">${r.quote}</td>
                    <td className="num" style={{ color: r.gm > 19 ? "var(--ok)" : r.gm > 16 ? "var(--text)" : "var(--warn)" }}>{r.gm}%</td>
                    <td style={{ minWidth: 110 }}>
                      <ScoreBar value={r.win} color={r.win > 70 ? "var(--ok)" : r.win > 50 ? "var(--accent)" : "var(--warn)"} />
                    </td>
                    <td style={{ fontSize: 11, color: "var(--text-mid)", maxWidth: 280, overflow: "hidden", textOverflow: "ellipsis" }}>{r.why}</td>
                    <td>{r.flag && <Chip kind="warn">REVIEW</Chip>}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Panel>

        <div className="grid cols-2" style={{ marginTop: 16 }}>
          <Panel title="PRICING REASONING · ATL → CHI">
            <div style={{ fontSize: 13, lineHeight: 1.7 }}>
              <span className="ai-tag" style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.14em", color: "var(--accent)", padding: "2px 6px", border: "1px solid var(--accent)", borderRadius: 2, marginRight: 8 }}>WHY $3.02</span>
              Quoting <b className="mono">$3.02/mi</b> — <b>14% over DAT median</b>.
              <ul style={{ marginTop: 10, paddingLeft: 18, color: "var(--text-mid)", lineHeight: 1.8 }}>
                <li>DAT 7d median: $2.84/mi · trend +6%</li>
                <li>Costco paid $2.98 on this lane in April (84% renewal probability)</li>
                <li>Our cost basis on lane: $2.46/mi avg (Heartland, Blue Peak)</li>
                <li>Capacity tight — L/T ratio 4.2 (industry avg 2.8)</li>
                <li>Weather risk moderate · OH/PA storms expected</li>
                <li>Walmart pays $3.06 same lane — Costco priced slightly under to win 3yr deal</li>
              </ul>
              <div style={{ marginTop: 10, padding: 10, background: "var(--accent-bg)", borderRadius: 3 }}>
                <span className="mono accent" style={{ fontSize: 10, letterSpacing: "0.12em", color: "var(--accent)" }}>WIN PROBABILITY</span>
                <div className="mono" style={{ fontSize: 22, marginTop: 2 }}>72%</div>
                <div className="dim" style={{ fontSize: 11 }}>at $3.02 · drops to 48% at $3.12 · climbs to 86% at $2.95</div>
              </div>
            </div>
          </Panel>

          <Panel title="FLAGGED LANES · 12">
            <div style={{ fontSize: 12, display: "flex", flexDirection: "column", gap: 8 }}>
              <FlagRow lane="Houston, TX → Boise, ID" why="No historical · low truck density · suggest skip" sev="high" />
              <FlagRow lane="Miami, FL → Seattle, WA" why="Lane too long for our network · partner needed" sev="high" />
              <FlagRow lane="Stockton, CA → Reno, NV" why="Margin shows -2% at competitive bid · pass or skim" sev="med" />
              <FlagRow lane="Bentonville, AR → Boston, MA" why="Capacity volatile · ±18% from week to week" sev="med" />
              <FlagRow lane="Denver, CO → SLC, UT" why="Customer (Costco) historically rejects above $2.20 — they pay $2.04 elsewhere" sev="med" />
              <FlagRow lane="Long Beach, CA → Memphis, TN" why="Backhaul thin from Memphis · GM realistic 12%" sev="low" />
            </div>
          </Panel>
        </div>
      </div>
    </div>
  );
}

function FlagRow({ lane, why, sev }) {
  const color = sev === "high" ? "var(--danger)" : sev === "med" ? "var(--warn)" : "var(--text-mid)";
  return (
    <div style={{ display: "flex", gap: 8, padding: 8, background: "var(--bg-2)", borderLeft: `2px solid ${color}`, borderRadius: 2 }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 12, fontWeight: 500 }}>{lane}</div>
        <div className="dim" style={{ fontSize: 11, marginTop: 2 }}>{why}</div>
      </div>
      <Chip kind={sev === "high" ? "danger" : sev === "med" ? "warn" : ""}>{sev.toUpperCase()}</Chip>
    </div>
  );
}

function generateRfpLanes(n) {
  const cities = [
    ["Atlanta, GA", "Chicago, IL"], ["Dallas, TX", "Newark, NJ"], ["LA, CA", "Phoenix, AZ"],
    ["Seattle, WA", "Denver, CO"], ["Houston, TX", "Tampa, FL"], ["Charlotte, NC", "Boston, MA"],
    ["Minneapolis, MN", "St Louis, MO"], ["Memphis, TN", "Detroit, MI"], ["Bentonville, AR", "Austin, TX"],
    ["Cincinnati, OH", "Nashville, TN"], ["Portland, OR", "Reno, NV"], ["Long Beach, CA", "SLC, UT"],
    ["Indianapolis, IN", "Detroit, MI"], ["Jacksonville, FL", "Charlotte, NC"], ["Kansas City, MO", "Denver, CO"],
    ["Boise, ID", "Portland, OR"], ["Lakeland, FL", "Charlotte, NC"], ["Grand Rapids, MI", "Cleveland, OH"],
    ["SLC, UT", "Phoenix, AZ"], ["Stockton, CA", "Las Vegas, NV"],
  ];
  const why = [
    "Lane priced 6% over DAT · capacity tight · L/T 4.1",
    "Our cost $2.46 · margin healthy · win@72%",
    "Customer paid $X on prior cycle · 84% renew likely",
    "Backhaul opportunity from this DC · 22% GM possible",
    "Capacity tight + weather risk · price elevated",
    "Strong carrier relationship · 14 prior loads same lane",
    "Soft lane · price down 4% vs DAT to win",
    "Volume scale on this lane unlocks tier discount",
    "Low truck density · risky but margin justifies",
    "Customer cap-sensitive · priced 2% under to win",
  ];
  const out = [];
  for (let i = 0; i < n; i++) {
    const c = cities[i % cities.length];
    const dat = 2 + (i % 10) * 0.18;
    const cost = dat - 0.4 - (i % 5) * 0.06;
    const quote = dat + 0.12 + (i % 4) * 0.06;
    const gm = ((quote - cost) / quote * 100);
    out.push({
      lane: `${c[0]} → ${c[1]}`,
      vol: 4 + (i % 8),
      dat: dat.toFixed(2),
      cost: cost.toFixed(2),
      quote: quote.toFixed(2),
      gm: gm.toFixed(1),
      win: 50 + ((i * 7) % 45),
      why: why[i % why.length],
      flag: i % 11 === 5,
    });
  }
  return out;
}

window.RFPEngine = RFPEngine;
