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

function CRM() {
  const [side, setSide] = React.useState("customer");
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Relationships</div>
          <div className="page-sub">Customer & carrier CRM · pipeline · contracts · scorecards</div>
        </div>
        <div className="page-actions">
          <button className="btn ghost"><Ic.filter style={{ width: 12, height: 12 }} /> Segment</button>
          <button className="btn primary"><Ic.plus style={{ width: 12, height: 12 }} /> New {side === "customer" ? "customer" : "carrier"}</button>
        </div>
      </div>

      <div className="tabs">
        <div className={`tab ${side === "customer" ? "active" : ""}`} onClick={() => setSide("customer")}>Customers <span className="count">217</span></div>
        <div className={`tab ${side === "carrier" ? "active" : ""}`} onClick={() => setSide("carrier")}>Carriers <span className="count">842</span></div>
        <div className={`tab ${side === "pipeline" ? "active" : ""}`} onClick={() => setSide("pipeline")}>Sales Pipeline <span className="count">18</span></div>
      </div>

      {side === "customer" && <CustomerView />}
      {side === "carrier" && <CarrierCRMView />}
      {side === "pipeline" && <PipelineView />}
    </div>
  );
}

function CustomerView() {
  return (
    <div style={{ padding: 16 }}>
      <div className="grid cols-4" style={{ marginBottom: 16 }}>
        <KPI label="Active Customers" value="217" delta="14 new MTD" />
        <KPI label="Revenue MTD" value="$2.84M" delta="22%" />
        <KPI label="Top 10 = " value="62%" delta="of revenue" />
        <KPI label="Net Retention" value="114%" delta="6pt" />
      </div>

      <Panel title="CUSTOMER ACCOUNTS · BY HEALTH" actions={
        <div className="toggle-row"><button className="on">ALL</button><button>HEALTHY</button><button>AT RISK</button><button>CHURNED</button></div>
      }>
        <table className="tbl">
          <thead>
            <tr>
              <th>Customer</th>
              <th>Tier</th>
              <th className="num">Loads YTD</th>
              <th className="num">Rev YTD</th>
              <th className="num">GM %</th>
              <th>On-time</th>
              <th>Health</th>
              <th>AI Insight</th>
            </tr>
          </thead>
          <tbody>
            {[
              ["Walmart", "PLATINUM", 217, "$612k", 17.2, 98.4, "ok", "STABLE", "Q3 lane bid renewal in 4 weeks · pre-stage proposal"],
              ["Target", "GOLD", 148, "$408k", 18.4, 97.2, "ok", "GROWING", "Volume up 22% · upsell Newark dedicated"],
              ["Home Depot", "GOLD", 124, "$362k", 19.2, 96.8, "ok", "STABLE", "Margin healthy · maintain rates"],
              ["Costco", "GOLD", 98, "$284k", 17.8, 95.4, "ok", "STABLE", "Q3 RFP in progress · 218 lanes"],
              ["Publix", "SILVER", 72, "$184k", 18.9, 98.2, "ok", "STABLE", "Florida expansion opportunity"],
              ["Meijer", "SILVER", 58, "$148k", 16.4, 92.8, "warn", "AT RISK", "Volume -18% past 60d · check w/ buyer"],
              ["Sprouts", "BRONZE", 48, "$84k", 18.2, 96.4, "warn", "AT RISK", "Slow pay 44d avg · push QuickPay terms"],
              ["Kroger", "GOLD", 84, "$224k", 17.8, 94.2, "ok", "STABLE", "Lost 2 lanes to competitor · win back?"],
              ["Wegmans", "SILVER", 32, "$92k", 19.4, 97.8, "ok", "GROWING", "+44% YoY · expand Northeast lanes"],
              ["Albertsons", "BRONZE", 18, "$48k", 16.2, 88.4, "danger", "CHURNING", "0 loads in 14d · 60+ past due · escalate"],
            ].map((r, i) => (
              <tr key={i}>
                <td style={{ fontWeight: 500 }}>{r[0]}</td>
                <td><Chip kind={r[1] === "PLATINUM" ? "magenta" : r[1] === "GOLD" ? "warn" : r[1] === "SILVER" ? "" : ""}>{r[1]}</Chip></td>
                <td className="num">{r[2]}</td>
                <td className="num">{r[3]}</td>
                <td className="num">{r[4]}%</td>
                <td className="num" style={{ color: r[5] > 95 ? "var(--ok)" : "var(--warn)" }}>{r[5]}%</td>
                <td><Chip kind={r[6]}>{r[7]}</Chip></td>
                <td style={{ fontSize: 11, color: "var(--text-mid)", maxWidth: 320, overflow: "hidden", textOverflow: "ellipsis" }}>{r[8]}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Panel>

      <div className="grid cols-2" style={{ marginTop: 16 }}>
        <Panel title="WALMART · SCORECARD">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, fontSize: 12 }}>
            <Stat3 label="LOADS YTD" v="217" />
            <Stat3 label="REVENUE" v="$612k" />
            <Stat3 label="GROSS MARGIN" v="17.2%" />
            <Stat3 label="ON-TIME" v="98.4%" />
            <Stat3 label="ACCEPT RATE" v="76%" />
            <Stat3 label="AVG INVOICE" v="3.1 days" />
          </div>
          <div className="h-rule" style={{ marginTop: 16, marginBottom: 8 }}>TOP LANES</div>
          <div style={{ fontSize: 11, lineHeight: 1.8 }}>
            <div>Bentonville, AR → Austin, TX <span className="dim">· 48 loads · 18.2% GM</span></div>
            <div>Laredo, TX → Memphis, TN <span className="dim">· 42 loads · 17.8% GM</span></div>
            <div>Houston, TX → Tampa, FL <span className="dim">· 28 loads · 18.4% GM</span></div>
          </div>
        </Panel>
        <Panel title="UPCOMING ACTIVITY">
          <div style={{ fontSize: 12, display: "flex", flexDirection: "column", gap: 8 }}>
            <Activity t="MON 06/02" what="Walmart QBR · 90min · Bentonville" tag="QBR" />
            <Activity t="WED 06/04" what="Costco RFP response due · 218 lanes" tag="RFP" />
            <Activity t="THU 06/05" what="Target lane bid review · Newark dedicated" tag="BID" />
            <Activity t="FRI 06/06" what="Sprouts collections call · 43d past due" tag="AR" />
            <Activity t="MON 06/09" what="Home Depot expansion proposal" tag="GROWTH" />
          </div>
        </Panel>
      </div>
    </div>
  );
}

function CarrierCRMView() {
  return (
    <div style={{ padding: 16 }}>
      <div className="grid cols-4" style={{ marginBottom: 16 }}>
        <KPI label="Carrier Network" value="842" delta="14 onboarded MTD" />
        <KPI label="Active 30d" value="412" delta="49% utilization" />
        <KPI label="Preferred" value="84" delta="A-rated · top tier" />
        <KPI label="Do-Not-Use" value="22" delta="auto-blocked" />
      </div>

      <Panel title="CARRIER RELATIONSHIPS" actions={
        <div className="toggle-row"><button className="on">PREFERRED · 84</button><button>ACTIVE</button><button>WATCH</button><button>BLOCKED</button></div>
      }>
        <table className="tbl">
          <thead>
            <tr><th>Carrier</th><th className="num">Score</th><th className="num">Loads 90d</th><th>Preferred Lanes</th><th>Payment</th><th>Safety</th><th>Last Load</th><th>AI Note</th></tr>
          </thead>
          <tbody>
            {[
              ["Western Mountain Trans", 98, 142, "SLC↔DEN · SLC↔PHX", "Net 30", "A", "Today", "Top 1% · prioritize for premium lanes"],
              ["BluePeak Carriers", 94, 89, "BOI↔SEA · BOI↔SLC", "QuickPay 1.5%", "A", "Today", "Reliable · expand SE coverage"],
              ["Coastal Freight", 91, 64, "LB↔PHX · reefer", "Net 7", "A", "Yesterday", "Reefer specialist · increase volume"],
              ["Hidalgo Logistics", 88, 51, "Cross-border MX/TX", "QuickPay 1.5%", "A", "Today", "Cross-border specialist · keep close"],
              ["Eastern Star Transport", 86, 73, "NC↔NE corridor", "Net 15", "B", "2 weeks", "Watch detention pattern"],
              ["Heartland Hauling", 82, 38, "IN↔OH · MI", "Net 30", "B", "5 days", "Mid-tier reliable"],
              ["Pinecone Hauling", 71, 27, "OR↔NV", "Net 30 (TBS)", "C", "Today", "Chronic detention · cap at 4 loads/mo"],
            ].map((r, i) => (
              <tr key={i}>
                <td>{r[0]}</td>
                <td style={{ minWidth: 100 }}><ScoreBar value={r[1]} color={r[1] > 90 ? "var(--ok)" : r[1] > 80 ? "var(--accent)" : "var(--warn)"} /></td>
                <td className="num">{r[2]}</td>
                <td className="mono dim" style={{ fontSize: 11 }}>{r[3]}</td>
                <td className="mono dim" style={{ fontSize: 11 }}>{r[4]}</td>
                <td><Chip kind={r[5] === "A" ? "ok" : r[5] === "B" ? "warn" : "danger"}>{r[5]}</Chip></td>
                <td className="mono dim" style={{ fontSize: 11 }}>{r[6]}</td>
                <td style={{ fontSize: 11, color: "var(--text-mid)" }}>{r[7]}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Panel>
    </div>
  );
}

function PipelineView() {
  const stages = [
    { name: "PROSPECT", count: 8, value: "$1.4M" },
    { name: "DISCOVERY", count: 4, value: "$840k" },
    { name: "RFP", count: 3, value: "$2.1M" },
    { name: "PROPOSAL", count: 2, value: "$680k" },
    { name: "CLOSING", count: 1, value: "$240k" },
  ];
  const deals = [
    { co: "Sysco Foods",       stage: 0, value: "$320k/yr",  contact: "P. Reilly", lastTouch: "2d", nextStep: "Discovery call Thursday" },
    { co: "PepsiCo Bottling",  stage: 0, value: "$540k/yr",  contact: "M. Chen",   lastTouch: "5d", nextStep: "Email intro to VP Logistics" },
    { co: "Performance Food",  stage: 1, value: "$280k/yr",  contact: "K. Singh",  lastTouch: "1d", nextStep: "Send lane density analysis" },
    { co: "Hershey",           stage: 2, value: "$1.8M/yr",  contact: "D. Mitchell", lastTouch: "Today", nextStep: "RFP 144 lanes · due 06/14" },
    { co: "Smucker's",         stage: 2, value: "$180k/yr",  contact: "L. Ortega", lastTouch: "3d", nextStep: "Awaiting customer response" },
    { co: "Tyson Foods",       stage: 3, value: "$480k/yr",  contact: "R. Brooks", lastTouch: "Today", nextStep: "Reviewing pricing internally" },
    { co: "Nestlé USA",        stage: 3, value: "$200k/yr",  contact: "J. Park",   lastTouch: "4d", nextStep: "Contract redlines back to us" },
    { co: "Mondelez",          stage: 4, value: "$240k/yr",  contact: "S. Adams",  lastTouch: "Today", nextStep: "Final signature this week" },
  ];
  return (
    <div style={{ padding: 16 }}>
      <div style={{ display: "grid", gridTemplateColumns: `repeat(${stages.length}, 1fr)`, gap: 10, marginBottom: 16 }}>
        {stages.map((s, i) => (
          <div key={i} style={{ background: "var(--bg-1)", border: "1px solid var(--line)", borderLeft: `2px solid ${["var(--text-dim)", "var(--blue)", "var(--magenta)", "var(--warn)", "var(--ok)"][i]}`, borderRadius: 4, padding: 12 }}>
            <div className="kpi-label">{s.name}</div>
            <div className="mono" style={{ fontSize: 22 }}>{s.count}</div>
            <div className="dim" style={{ fontSize: 11 }}>{s.value} pipeline</div>
          </div>
        ))}
      </div>

      <Panel title="OPEN DEALS · 18">
        <table className="tbl">
          <thead><tr><th>Company</th><th>Stage</th><th>Contact</th><th className="num">Annual value</th><th>Last touch</th><th>Next step</th></tr></thead>
          <tbody>
            {deals.map((d, i) => (
              <tr key={i}>
                <td style={{ fontWeight: 500 }}>{d.co}</td>
                <td><Chip kind={d.stage === 4 ? "ok" : d.stage === 3 ? "warn" : d.stage === 2 ? "magenta" : "info"}>{stages[d.stage].name}</Chip></td>
                <td>{d.contact}</td>
                <td className="num">{d.value}</td>
                <td className="mono dim" style={{ fontSize: 11 }}>{d.lastTouch}</td>
                <td style={{ fontSize: 12, color: "var(--text-mid)" }}>{d.nextStep}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Panel>
    </div>
  );
}

function Stat3({ label, v }) {
  return <div><div className="kpi-label">{label}</div><div className="mono" style={{ fontSize: 18 }}>{v}</div></div>;
}
function Activity({ t, what, tag }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "84px 1fr auto", gap: 8, padding: 8, background: "var(--bg-2)", borderRadius: 3 }}>
      <span className="mono accent" style={{ color: "var(--accent)", fontSize: 11 }}>{t}</span>
      <span style={{ fontSize: 12 }}>{what}</span>
      <Chip>{tag}</Chip>
    </div>
  );
}

window.CRM = CRM;
