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

/* ============================================================
   Integrations · marketplace + implementation details
   ============================================================ */

const INTEGRATIONS = [
  // ───── Identity & Compliance ─────
  { id: "highway", name: "Highway", cat: "compliance", status: "connected", logo: { l: "H", c: "#FBBF24", bg: "#1A1A1A" },
    blurb: "Carrier identity, fraud prevention, instant onboarding.",
    auth: "OAuth · API key",
    powers: ["Carrier Onboarding", "Fraud Shield", "Carrier Match"],
    in: ["Identity score 0-100", "Fraud signals (voice, IP, banking)", "DOT / MC verification", "Insurance status"],
    out: ["Booking events", "Driver assignments"],
    activity: "Verified 312 carriers · blocked 2 fraud attempts (24h)",
    syncHz: "Realtime", monthlyCalls: "48,210" },
  { id: "rmis", name: "RMIS", cat: "compliance", status: "connected", logo: { l: "RM", c: "#FFFFFF", bg: "#003B71" },
    blurb: "Insurance certificate management · automated COI tracking.",
    auth: "API key · EDI",
    powers: ["Compliance · Insurance", "Carrier Onboarding"],
    in: ["COI documents", "Expiration dates", "Coverage amounts", "Cancellation alerts"],
    out: ["Carrier roster", "Required coverage"],
    activity: "12 COIs renewed automatically this week",
    syncHz: "Hourly", monthlyCalls: "8,420" },
  { id: "mycarrier", name: "MyCarrierPortal", cat: "compliance", status: "connected", logo: { l: "MCP", c: "#FFFFFF", bg: "#0066B2" },
    blurb: "Carrier packet collection · W9 · references · agreements.",
    auth: "API · webhook",
    powers: ["Carrier Onboarding"],
    in: ["W9", "References", "Driver license scans", "Signed broker-carrier agreement"],
    out: ["Onboarding invitations", "Carrier profile"],
    activity: "8 onboarding packets received today",
    syncHz: "Webhook", monthlyCalls: "1,840" },
  { id: "carrier411", name: "Carrier411 / Watchdog", cat: "compliance", status: "connected", logo: { l: "C4", c: "#FFFFFF", bg: "#8B0000" },
    blurb: "Broker complaints · double-broker watchlist · do-not-use list.",
    auth: "API key",
    powers: ["Fraud Shield", "Carrier Onboarding"],
    in: ["Broker complaints history", "Watchlist flags", "FreightGuard reports"],
    out: ["—"],
    activity: "3 carriers flagged · 1 added to do-not-use",
    syncHz: "Daily", monthlyCalls: "2,140" },
  { id: "safer", name: "FMCSA SAFER", cat: "compliance", status: "connected", logo: { l: "FM", c: "#FFFFFF", bg: "#1B3A6F" },
    blurb: "Federal authority · safety scores · operating status.",
    auth: "Public API",
    powers: ["Carrier Onboarding", "Compliance · CSA", "Fraud Shield"],
    in: ["Authority status", "CSA BASIC scores", "OOS rates", "Hazmat endorsements"],
    out: ["—"],
    activity: "Synced 842 carrier records",
    syncHz: "Daily", monthlyCalls: "4,820" },
  { id: "saferwatch", name: "SaferWatch", cat: "compliance", status: "available", logo: { l: "SW", c: "#FFFFFF", bg: "#005F73" },
    blurb: "Continuous carrier monitoring · safety event alerts.",
    auth: "API key",
    powers: ["Compliance · CSA"],
    in: ["Safety events", "Inspection results", "Score deltas"],
    out: ["Active carrier list"],
    activity: "—", syncHz: "—", monthlyCalls: "—" },

  // ───── Tracking & Visibility ─────
  { id: "macropoint", name: "MacroPoint", cat: "tracking", status: "connected", logo: { l: "MP", c: "#FFFFFF", bg: "#003366" },
    blurb: "Realtime GPS visibility via driver phone or ELD.",
    auth: "API key · per-load token",
    powers: ["Dispatch & Track", "Shipper Portal", "AI Check Calls"],
    in: ["GPS pings", "Geofence events", "ETA recalcs", "Driver app status"],
    out: ["Load → trip create", "Pickup/delivery geofences"],
    activity: "84 active trips · 312 pings/min",
    syncHz: "Realtime", monthlyCalls: "2.8M" },
  { id: "truckertools", name: "Trucker Tools", cat: "tracking", status: "connected", logo: { l: "TT", c: "#FFFFFF", bg: "#0066CC" },
    blurb: "Driver mobile app · load tracking · POD capture.",
    auth: "API key",
    powers: ["Dispatch & Track", "Document AI · POD"],
    in: ["GPS", "Status updates", "POD photos", "BOL scans"],
    out: ["Load offers", "Rate cons", "Driver instructions"],
    activity: "47 drivers active · 12 PODs received today",
    syncHz: "Realtime", monthlyCalls: "1.2M" },
  { id: "fourkites", name: "FourKites", cat: "tracking", status: "available", logo: { l: "4K", c: "#FFFFFF", bg: "#00A99D" },
    blurb: "Enterprise visibility · shipper-facing tracking link.",
    auth: "API · EDI 214",
    powers: ["Dispatch & Track", "Shipper Portal"],
    in: ["Predictive ETA", "Yard moves", "Multimodal visibility"],
    out: ["Load IDs", "Stops"],
    activity: "—", syncHz: "—", monthlyCalls: "—" },
  { id: "project44", name: "project44", cat: "tracking", status: "available", logo: { l: "p44", c: "#FFFFFF", bg: "#00C16E" },
    blurb: "Movement intelligence · cross-modal tracking.",
    auth: "OAuth",
    powers: ["Dispatch & Track", "Shipper Portal"],
    in: ["Multi-modal ETA", "Detention alerts", "Yard intelligence"],
    out: ["Load metadata"],
    activity: "—", syncHz: "—", monthlyCalls: "—" },

  // ───── ELD ─────
  { id: "samsara", name: "Samsara", cat: "eld", status: "connected", logo: { l: "S", c: "#FFFFFF", bg: "#003153" },
    blurb: "ELD · HOS · vehicle telematics · DEF · fuel.",
    auth: "OAuth",
    powers: ["Compliance · HOS", "Dispatch & Track", "Claims · Detention"],
    in: ["HOS clocks", "Drive/duty status", "Tractor diagnostics", "Hard brake events"],
    out: ["Trip start/end", "Geofences"],
    activity: "184 ELD-connected drivers",
    syncHz: "Realtime", monthlyCalls: "5.4M" },
  { id: "motive", name: "Motive", cat: "eld", status: "connected", logo: { l: "M", c: "#FFFFFF", bg: "#FF6B00" },
    blurb: "ELD · safety scoring · driver app · IFTA.",
    auth: "OAuth",
    powers: ["Compliance · HOS", "Dispatch & Track"],
    in: ["HOS", "ELD logs", "AI dashcam events", "IFTA mileage"],
    out: ["Driver assignments"],
    activity: "62 drivers · 4 HOS warnings cleared",
    syncHz: "Realtime", monthlyCalls: "2.2M" },
  { id: "geotab", name: "Geotab", cat: "eld", status: "available", logo: { l: "G", c: "#FFFFFF", bg: "#5C8A3A" },
    blurb: "ELD + telematics · global fleet vis.",
    auth: "API key",
    powers: ["Compliance · HOS", "Dispatch & Track"],
    in: ["HOS", "GPS", "Engine data"],
    out: ["—"],
    activity: "—", syncHz: "—", monthlyCalls: "—" },
  { id: "keeptruck", name: "KeepTruckin", cat: "eld", status: "available", logo: { l: "KT", c: "#FFFFFF", bg: "#FF6B00" },
    blurb: "Legacy Motive integration · ELD + DVIR.",
    auth: "API",
    powers: ["Compliance · HOS"],
    in: ["HOS"], out: ["—"],
    activity: "—", syncHz: "—", monthlyCalls: "—" },

  // ───── Load Boards / Market Data ─────
  { id: "dat", name: "DAT One", cat: "loadboard", status: "connected", logo: { l: "DAT", c: "#FFFFFF", bg: "#E03C31" },
    blurb: "Load board · capacity · carrier directory.",
    auth: "API · screen-scrape backup",
    powers: ["Load Board", "Rate Desk", "Carrier Match"],
    in: ["Carrier capacity posts", "Lane rates", "Reply emails"],
    out: ["Posted loads", "Lane queries", "Carrier verifications"],
    activity: "84 loads posted · 412 carrier matches",
    syncHz: "Realtime", monthlyCalls: "184k" },
  { id: "datrv", name: "DAT RateView", cat: "market", status: "connected", logo: { l: "RV", c: "#FFFFFF", bg: "#E03C31" },
    blurb: "Lane rate data · 7d / 30d / 1yr trends · L/T ratio.",
    auth: "API key",
    powers: ["Rate Desk", "RFP Engine", "Analytics"],
    in: ["Lane medians", "Trend percentages", "L/T ratios", "Capacity tightness"],
    out: ["Lane queries"],
    activity: "184 lane queries today",
    syncHz: "On-demand", monthlyCalls: "12k" },
  { id: "truckstop", name: "Truckstop", cat: "loadboard", status: "connected", logo: { l: "TS", c: "#FFFFFF", bg: "#0066CC" },
    blurb: "Load board · capacity · rate insights.",
    auth: "API · OAuth",
    powers: ["Load Board", "Rate Desk", "Carrier Match"],
    in: ["Capacity posts", "Carrier replies", "Rate Insights data"],
    out: ["Posted loads", "Bids"],
    activity: "42 active posts · 184 replies",
    syncHz: "Realtime", monthlyCalls: "64k" },
  { id: "greenscreens", name: "Greenscreens.ai", cat: "market", status: "connected", logo: { l: "GS", c: "#FFFFFF", bg: "#00C16E" },
    blurb: "Predictive lane pricing · ML-driven rate forecasts.",
    auth: "API key",
    powers: ["Rate Desk", "RFP Engine"],
    in: ["Predicted rates", "Confidence intervals", "Buy/sell guidance"],
    out: ["Lane queries"],
    activity: "Powering 218-lane Costco RFP",
    syncHz: "On-demand", monthlyCalls: "4,820" },
  { id: "123lb", name: "123Loadboard", cat: "loadboard", status: "available", logo: { l: "123", c: "#FFFFFF", bg: "#FF6B00" },
    blurb: "Secondary load board · backhaul sourcing.",
    auth: "API key",
    powers: ["Load Board", "Carrier Match"],
    in: ["Capacity", "Carrier replies"], out: ["Loads"],
    activity: "—", syncHz: "—", monthlyCalls: "—" },

  // ───── Payments & Factoring ─────
  { id: "triumphpay", name: "TriumphPay", cat: "payments", status: "connected", logo: { l: "T$", c: "#FFFFFF", bg: "#1A4480" },
    blurb: "Broker-to-carrier payments · QuickPay · ACH · factoring routing.",
    auth: "OAuth · API",
    powers: ["Accounting · Settlement", "Accounting · Advances"],
    in: ["Payment confirmations", "NOAs", "Factor company routing"],
    out: ["Payment instructions", "Carrier banking", "Invoice references"],
    activity: "$182k batch queued · Friday settlement",
    syncHz: "Daily batch", monthlyCalls: "8,420" },
  { id: "apex", name: "Apex Capital", cat: "payments", status: "connected", logo: { l: "A", c: "#FFFFFF", bg: "#0066B2" },
    blurb: "Factoring company · NOA lookup · lockbox routing.",
    auth: "API key",
    powers: ["Accounting · AR", "Accounting · Settlement"],
    in: ["NOA status", "Lockbox address changes", "Carrier verification"],
    out: ["Carrier IDs", "Invoice references"],
    activity: "22 carriers factor via Apex",
    syncHz: "Daily", monthlyCalls: "1,820" },
  { id: "tbs", name: "TBS Factoring", cat: "payments", status: "connected", logo: { l: "TBS", c: "#FFFFFF", bg: "#003366" },
    blurb: "Factoring · NOA + payment processing.",
    auth: "API",
    powers: ["Accounting · Settlement"],
    in: ["NOA", "Lockbox"], out: ["Invoice IDs"],
    activity: "8 carriers via TBS", syncHz: "Daily", monthlyCalls: "640" },
  { id: "otr", name: "OTR Capital", cat: "payments", status: "connected", logo: { l: "OTR", c: "#FFFFFF", bg: "#8B0000" },
    blurb: "Factoring partner.",
    auth: "API",
    powers: ["Accounting · Settlement"],
    in: ["NOA", "Verification"], out: ["Carrier IDs"],
    activity: "11 carriers via OTR", syncHz: "Daily", monthlyCalls: "880" },
  { id: "rts", name: "RTS Financial", cat: "payments", status: "available", logo: { l: "RTS", c: "#FFFFFF", bg: "#003B71" },
    blurb: "Factoring + fuel card combined.",
    auth: "API",
    powers: ["Accounting · Settlement", "Accounting · Advances"],
    in: ["—"], out: ["—"],
    activity: "—", syncHz: "—", monthlyCalls: "—" },
  { id: "comdata", name: "Comdata", cat: "payments", status: "connected", logo: { l: "CO", c: "#FFFFFF", bg: "#E03C31" },
    blurb: "Fuel cards · advances · OnRoad spend control.",
    auth: "API",
    powers: ["Accounting · Advances", "Accounting · Settlement"],
    in: ["Spend transactions", "Card events", "Decline alerts"],
    out: ["Card issue requests", "Advance authorizations"],
    activity: "$4,820 spend today · 22 cards active",
    syncHz: "Realtime", monthlyCalls: "12,400" },
  { id: "efs", name: "EFS / Wex", cat: "payments", status: "connected", logo: { l: "EFS", c: "#FFFFFF", bg: "#1B3A6F" },
    blurb: "Fuel card alternative · advances.",
    auth: "API",
    powers: ["Accounting · Advances"],
    in: ["Spend events"], out: ["Card requests"],
    activity: "$1,840 spend today", syncHz: "Realtime", monthlyCalls: "3,200" },

  // ───── Accounting ─────
  { id: "quickbooks", name: "QuickBooks Online", cat: "accounting", status: "connected", logo: { l: "QB", c: "#FFFFFF", bg: "#2CA01C" },
    blurb: "Push invoices · sync payments · expense categorization.",
    auth: "OAuth",
    powers: ["Accounting · AR", "Accounting · Settlement"],
    in: ["Payment confirmations", "Reconciliation status"],
    out: ["Invoices", "Bills (carrier payables)", "Customer records"],
    activity: "Last sync 13:01:42 · 412 invoices YTD",
    syncHz: "15 min", monthlyCalls: "4,840" },
  { id: "netsuite", name: "NetSuite", cat: "accounting", status: "available", logo: { l: "NS", c: "#FFFFFF", bg: "#1B5E20" },
    blurb: "Enterprise ERP · multi-entity broker accounting.",
    auth: "OAuth · SuiteTalk",
    powers: ["Accounting · AR", "Accounting · Settlement", "Analytics"],
    in: ["GL accounts", "Payments"], out: ["Invoices", "Bills"],
    activity: "—", syncHz: "—", monthlyCalls: "—" },
  { id: "sage", name: "Sage Intacct", cat: "accounting", status: "available", logo: { l: "SG", c: "#FFFFFF", bg: "#00C16E" },
    blurb: "Cloud accounting · multi-entity.",
    auth: "OAuth", powers: ["Accounting · AR"], in: [], out: [],
    activity: "—", syncHz: "—", monthlyCalls: "—" },

  // ───── EDI / Customer ─────
  { id: "sps", name: "SPS Commerce", cat: "edi", status: "connected", logo: { l: "SPS", c: "#FFFFFF", bg: "#FF6B00" },
    blurb: "EDI 204 (tender) · 990 (response) · 214 (status) · 210 (invoice).",
    auth: "EDI VAN · SFTP",
    powers: ["Inbox", "Load Board", "Shipper Portal"],
    in: ["204 tenders", "Customer profiles"],
    out: ["990 responses", "214 status updates", "210 invoices"],
    activity: "84 tenders received today (Walmart · Target · Costco)",
    syncHz: "Realtime", monthlyCalls: "—" },
  { id: "opentext", name: "OpenText EDI", cat: "edi", status: "available", logo: { l: "OT", c: "#FFFFFF", bg: "#003B71" },
    blurb: "Alternative EDI VAN · same X12 set.",
    auth: "EDI VAN", powers: ["Inbox", "Load Board"], in: [], out: [],
    activity: "—", syncHz: "—", monthlyCalls: "—" },

  // ───── Communications ─────
  { id: "twilio", name: "Twilio", cat: "comms", status: "connected", logo: { l: "Tw", c: "#FFFFFF", bg: "#F22F46" },
    blurb: "SMS + voice infrastructure · powers AI check calls.",
    auth: "API key",
    powers: ["AI Check Calls", "Inbox · SMS", "Driver Wellness"],
    in: ["Inbound SMS", "Call recordings", "Delivery receipts"],
    out: ["Outbound SMS", "Outbound calls", "Voice synthesis"],
    activity: "312 calls · 184 SMS today",
    syncHz: "Realtime", monthlyCalls: "84,200" },
  { id: "telnyx", name: "Telnyx", cat: "comms", status: "available", logo: { l: "Tn", c: "#FFFFFF", bg: "#00C16E" },
    blurb: "Voice/SMS alternative · lower latency for AI agents.",
    auth: "API key", powers: ["AI Check Calls"], in: [], out: [],
    activity: "—", syncHz: "—", monthlyCalls: "—" },
  { id: "gmail", name: "Gmail (Google Workspace)", cat: "comms", status: "connected", logo: { l: "G", c: "#FFFFFF", bg: "#E03C31" },
    blurb: "Inbox-native email triage · this is THE Keelway surface.",
    auth: "OAuth",
    powers: ["Agent Inbox", "Carrier Match · email replies"],
    in: ["Carrier reply emails", "Customer emails"],
    out: ["Drafted replies", "Send-as-broker"],
    activity: "412 emails processed today · 38 drafts sent",
    syncHz: "Realtime push", monthlyCalls: "—" },
  { id: "outlook", name: "Outlook · Microsoft 365", cat: "comms", status: "connected", logo: { l: "O", c: "#FFFFFF", bg: "#0078D4" },
    blurb: "Same triage surface for Outlook brokerages.",
    auth: "OAuth (MS Graph)", powers: ["Agent Inbox"], in: ["Emails"], out: ["Drafts"],
    activity: "—", syncHz: "Realtime push", monthlyCalls: "—" },
  { id: "slack", name: "Slack", cat: "comms", status: "connected", logo: { l: "S", c: "#FFFFFF", bg: "#4A154B" },
    blurb: "Pipe alerts and AI agent reports into broker channels.",
    auth: "OAuth",
    powers: ["AI Console · alerts", "Fraud Shield · pages"],
    in: ["—"],
    out: ["Channel alerts", "DMs to agents", "Daily digest"],
    activity: "47 alerts sent today",
    syncHz: "Realtime", monthlyCalls: "1,840" },

  // ───── AI / Data ─────
  { id: "openai", name: "OpenAI", cat: "ai", status: "connected", logo: { l: "AI", c: "#FFFFFF", bg: "#10A37F" },
    blurb: "LLM for email drafting · classification · summarization.",
    auth: "API key",
    powers: ["Agent Inbox", "Document AI", "AI Console", "Conversational Load Builder"],
    in: ["Generated text", "Embeddings", "Function calls"],
    out: ["Prompts with broker context"],
    activity: "8,420 LLM calls today",
    syncHz: "On-demand", monthlyCalls: "248k" },
  { id: "anthropic", name: "Anthropic Claude", cat: "ai", status: "connected", logo: { l: "C", c: "#1A1A1A", bg: "#C96442" },
    blurb: "Long-context reasoning for RFP pricing + rate explanation.",
    auth: "API key",
    powers: ["RFP Engine", "Rate Desk · reasoning"],
    in: ["Lane pricing rationale", "Multi-document analysis"],
    out: ["218-lane RFP context", "Historical bid data"],
    activity: "RFP pricing engine active",
    syncHz: "On-demand", monthlyCalls: "48k" },
  { id: "elevenlabs", name: "ElevenLabs", cat: "ai", status: "connected", logo: { l: "11", c: "#FFFFFF", bg: "#1A1A1A" },
    blurb: "Voice synthesis · broker voice clones (with consent).",
    auth: "API key",
    powers: ["AI Check Calls", "Voice Clone agent"],
    in: ["Audio streams"],
    out: ["Voice samples", "Synthesis prompts"],
    activity: "312 voice calls today",
    syncHz: "Realtime", monthlyCalls: "62k" },
  { id: "assembly", name: "AssemblyAI", cat: "ai", status: "connected", logo: { l: "AA", c: "#FFFFFF", bg: "#1E3A8A" },
    blurb: "Realtime call transcription + sentiment + intent.",
    auth: "API key",
    powers: ["AI Check Calls", "Driver Wellness"],
    in: ["Transcripts", "Sentiment scores", "Speaker diarization"],
    out: ["Audio streams"],
    activity: "312 calls transcribed",
    syncHz: "Realtime", monthlyCalls: "84k" },

  // ───── Mapping & Routing ─────
  { id: "pcmiler", name: "PC*MILER", cat: "mapping", status: "connected", logo: { l: "PC", c: "#FFFFFF", bg: "#1B5E20" },
    blurb: "Truck-routed mileage · HOS routing · fuel optimization.",
    auth: "API key",
    powers: ["Load Board · mileage", "Dispatch", "Rate Desk · cost basis"],
    in: ["Routed mileage", "Toll cost", "Practical route"],
    out: ["Origin / destination pairs"],
    activity: "412 mileage calcs today",
    syncHz: "On-demand", monthlyCalls: "12,200" },
  { id: "mapbox", name: "Mapbox", cat: "mapping", status: "connected", logo: { l: "MB", c: "#FFFFFF", bg: "#4264FB" },
    blurb: "Map tiles + geocoding · powers Dispatch map.",
    auth: "API key",
    powers: ["Dispatch & Track", "Appointments"],
    in: ["Tile rendering", "Geocoding"],
    out: ["Coordinates", "Bounds"],
    activity: "—", syncHz: "Realtime", monthlyCalls: "1.4M" },
];

const CATEGORIES = [
  { id: "all",         label: "All",                   icon: "◇" },
  { id: "compliance",  label: "Identity & Compliance", icon: "✓" },
  { id: "tracking",    label: "Tracking & Visibility", icon: "◉" },
  { id: "eld",         label: "ELD · HOS",             icon: "⏱" },
  { id: "loadboard",   label: "Load Boards",           icon: "▦" },
  { id: "market",      label: "Market Data",           icon: "▲" },
  { id: "payments",    label: "Payments & Factoring",  icon: "$" },
  { id: "accounting",  label: "Accounting",            icon: "Σ" },
  { id: "edi",         label: "EDI · Customer",        icon: "⇄" },
  { id: "comms",       label: "Communications",        icon: "✉" },
  { id: "ai",          label: "AI · Data",             icon: "∗" },
  { id: "mapping",     label: "Mapping",               icon: "⊙" },
];

function Integrations() {
  const [tab, setTab] = React.useState("all");
  const [sel, setSel] = React.useState(INTEGRATIONS[0]);
  const [view, setView] = React.useState("grid"); // grid | flow

  const filtered = tab === "all" ? INTEGRATIONS : INTEGRATIONS.filter(x => x.cat === tab);
  const connectedCount = INTEGRATIONS.filter(x => x.status === "connected").length;
  const availableCount = INTEGRATIONS.filter(x => x.status === "available").length;

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Integrations</div>
          <div className="page-sub">{connectedCount} connected · {availableCount} available · powering 18 TMS surfaces</div>
        </div>
        <div className="page-actions">
          <span className="chip ok"><span className="dot" /> ALL HEALTHY</span>
          <div className="toggle-row">
            <button className={view === "grid" ? "on" : ""} onClick={() => setView("grid")}>MARKETPLACE</button>
            <button className={view === "flow" ? "on" : ""} onClick={() => setView("flow")}>DATA FLOW</button>
          </div>
          <button className="btn primary"><Ic.plus style={{ width: 12, height: 12 }} /> Connect</button>
        </div>
      </div>

      <div className="grid cols-4 pad" style={{ paddingBottom: 0 }}>
        <KPI label="Connected" value={connectedCount.toString()} delta={`${availableCount} more available`} />
        <KPI label="API Calls (30d)" value="9.2M" delta="14%" />
        <KPI label="Avg Sync Latency" value="184ms" delta="22ms" deltaKind="down" />
        <KPI label="Error Rate" value="0.04%" delta="3 issues 24h" />
      </div>

      {view === "grid" ? (
        <>
          <div className="tabs" style={{ marginTop: 16 }}>
            {CATEGORIES.map(c => {
              const count = c.id === "all" ? INTEGRATIONS.length : INTEGRATIONS.filter(x => x.cat === c.id).length;
              return (
                <div key={c.id} className={`tab ${tab === c.id ? "active" : ""}`} onClick={() => setTab(c.id)}>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-dim)" }}>{c.icon}</span>
                  {c.label}
                  <span className="count">{count}</span>
                </div>
              );
            })}
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 440px", minHeight: 600 }}>
            <div style={{ padding: 16, display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 10, alignContent: "flex-start" }}>
              {filtered.map(i => (
                <IntCard key={i.id} i={i} active={sel.id === i.id} onClick={() => setSel(i)} />
              ))}
            </div>
            <IntInspector i={sel} />
          </div>
        </>
      ) : (
        <DataFlowView />
      )}
    </div>
  );
}

function IntCard({ i, active, onClick }) {
  const statusKind = i.status === "connected" ? "ok" : i.status === "available" ? "" : "warn";
  return (
    <div onClick={onClick} style={{
      background: active ? "var(--bg-sel)" : "var(--bg-1)",
      border: `1px solid ${active ? "var(--accent)" : "var(--line)"}`,
      borderLeft: `3px solid ${active ? "var(--accent)" : "transparent"}`,
      borderRadius: "var(--radius)",
      padding: 14,
      cursor: "pointer",
      display: "flex",
      gap: 12,
      alignItems: "flex-start",
    }}>
      <Logo logo={i.logo} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }}>
          <span style={{ fontSize: 13, fontWeight: 600 }}>{i.name}</span>
          <Chip kind={statusKind}>{i.status.toUpperCase()}</Chip>
        </div>
        <div style={{ fontSize: 11, color: "var(--text-mid)", lineHeight: 1.5, marginBottom: 8 }}>{i.blurb}</div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-dim)", letterSpacing: "0.08em" }}>
          POWERS: {i.powers.slice(0, 2).join(" · ")}{i.powers.length > 2 ? ` +${i.powers.length - 2}` : ""}
        </div>
      </div>
    </div>
  );
}

function Logo({ logo }) {
  return (
    <div style={{
      width: 40, height: 40,
      flexShrink: 0,
      borderRadius: 6,
      background: logo.bg,
      color: logo.c,
      display: "grid",
      placeItems: "center",
      fontFamily: "var(--font-mono)",
      fontSize: logo.l.length > 2 ? 10 : 14,
      fontWeight: 700,
      letterSpacing: logo.l.length > 2 ? "0.05em" : "0",
      border: "1px solid rgba(0,0,0,0.08)",
    }}>
      {logo.l}
    </div>
  );
}

function IntInspector({ i }) {
  const statusKind = i.status === "connected" ? "ok" : i.status === "available" ? "" : "warn";
  return (
    <aside className="inspector" style={{ background: "var(--bg-1)" }}>
      {/* Header */}
      <div style={{ padding: 16, borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 14 }}>
        <Logo logo={i.logo} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 18, fontWeight: 600 }}>{i.name}</div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-dim)", letterSpacing: "0.08em", marginTop: 2 }}>
            {CATEGORIES.find(c => c.id === i.cat)?.label}
          </div>
        </div>
        <Chip kind={statusKind}>{i.status.toUpperCase()}</Chip>
      </div>

      {/* Blurb */}
      <div style={{ padding: 16, borderBottom: "1px solid var(--line)", fontSize: 13, color: "var(--text)", lineHeight: 1.6 }}>
        {i.blurb}
      </div>

      {/* Implementation: Auth + Sync */}
      <div style={{ padding: 16, borderBottom: "1px solid var(--line)" }}>
        <div className="h-rule" style={{ marginBottom: 10 }}>IMPLEMENTATION</div>
        <KV k="Auth" v={i.auth} />
        <KV k="Sync rate" v={i.syncHz} />
        <KV k="API calls (30d)" v={i.monthlyCalls} />
      </div>

      {/* Data flow */}
      <div style={{ padding: 16, borderBottom: "1px solid var(--line)" }}>
        <div className="h-rule" style={{ marginBottom: 10 }}>DATA FLOW</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--accent)", letterSpacing: "0.14em", marginBottom: 6 }}>← INBOUND</div>
            {i.in.length > 0 ? i.in.map((x, k) => (
              <div key={k} style={{ display: "flex", gap: 6, padding: "3px 0", fontSize: 12 }}>
                <span style={{ color: "var(--accent)" }}>→</span>
                <span>{x}</span>
              </div>
            )) : <div style={{ fontSize: 11, color: "var(--text-faint)" }}>—</div>}
          </div>
          <div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--blue)", letterSpacing: "0.14em", marginBottom: 6 }}>OUTBOUND →</div>
            {i.out.length > 0 ? i.out.map((x, k) => (
              <div key={k} style={{ display: "flex", gap: 6, padding: "3px 0", fontSize: 12 }}>
                <span style={{ color: "var(--blue)" }}>→</span>
                <span>{x}</span>
              </div>
            )) : <div style={{ fontSize: 11, color: "var(--text-faint)" }}>—</div>}
          </div>
        </div>
      </div>

      {/* Powers */}
      <div style={{ padding: 16, borderBottom: "1px solid var(--line)" }}>
        <div className="h-rule" style={{ marginBottom: 10 }}>POWERS THESE TMS SURFACES</div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
          {i.powers.map((p, k) => <Chip key={k} kind="accent">{p}</Chip>)}
        </div>
      </div>

      {/* Activity */}
      {i.status === "connected" && (
        <div style={{ padding: 16, borderBottom: "1px solid var(--line)" }}>
          <div className="h-rule" style={{ marginBottom: 8 }}>RECENT ACTIVITY</div>
          <div style={{ fontSize: 12, color: "var(--text-mid)", lineHeight: 1.6 }}>{i.activity}</div>
        </div>
      )}

      {/* Actions */}
      <div style={{ padding: 16, display: "flex", gap: 6 }}>
        {i.status === "connected" ? (
          <>
            <button className="btn ghost" style={{ flex: 1 }}>Configure</button>
            <button className="btn ghost" style={{ flex: 1 }}>View logs</button>
            <button className="btn danger" style={{ flex: 1 }}>Disconnect</button>
          </>
        ) : (
          <>
            <button className="btn ghost" style={{ flex: 1 }}>Docs</button>
            <button className="btn primary" style={{ flex: 2 }}>Connect</button>
          </>
        )}
      </div>
    </aside>
  );
}

function KV({ k, v }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "5px 0", fontSize: 12 }}>
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-dim)", letterSpacing: "0.1em" }}>{k.toUpperCase()}</span>
      <span style={{ fontFamily: "var(--font-mono)", color: "var(--text)" }}>{v}</span>
    </div>
  );
}

/* ============================================================
   Data Flow architecture diagram
   ============================================================ */
function DataFlowView() {
  return (
    <div style={{ padding: 20 }}>
      <div style={{ background: "var(--bg-1)", border: "1px solid var(--line)", borderRadius: "var(--radius-lg)", padding: 30, position: "relative", overflow: "hidden" }}>
        <div className="h-rule" style={{ marginBottom: 20 }}>SYSTEM ARCHITECTURE · INBOUND → KEELWAY CORE → OUTBOUND</div>

        <FlowDiagram />

        <div style={{ marginTop: 30, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-dim)", letterSpacing: "0.1em", textAlign: "center" }}>
          ALL INTEGRATIONS WRITE THROUGH THE KEELWAY CORE · SHARED EVENT BUS · NO POINT-TO-POINT COUPLING
        </div>
      </div>

      {/* Implementation notes */}
      <div className="grid cols-3" style={{ marginTop: 16 }}>
        <Panel title="EVENT BUS">
          <div style={{ fontSize: 13, lineHeight: 1.7, color: "var(--text-mid)" }}>
            Every integration emits typed events on a central bus (Kafka-style). Subscribers (AI agents, screens, downstream integrations) react. No integration knows about another.
          </div>
          <div style={{ marginTop: 12, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-dim)", letterSpacing: "0.08em" }}>
            EVENT TYPES · 84<br/>
            SUBSCRIBERS · 312<br/>
            P99 LATENCY · 18ms
          </div>
        </Panel>
        <Panel title="WEBHOOKS · OUTBOUND">
          <div style={{ fontSize: 13, lineHeight: 1.7, color: "var(--text-mid)" }}>
            Any partner can subscribe to load events, status changes, settlements. We sign every payload (HMAC) and retry with exponential backoff up to 24h.
          </div>
          <div style={{ marginTop: 12, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-dim)", letterSpacing: "0.08em" }}>
            ACTIVE WEBHOOKS · 22<br/>
            DELIVERIES (30D) · 1.84M<br/>
            FAILURE RATE · 0.04%
          </div>
        </Panel>
        <Panel title="API · INBOUND">
          <div style={{ fontSize: 13, lineHeight: 1.7, color: "var(--text-mid)" }}>
            REST + GraphQL. OAuth or scoped API keys. Idempotency keys on all writes. Rate-limited per partner. Full audit log on every call.
          </div>
          <div style={{ marginTop: 12, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-dim)", letterSpacing: "0.08em" }}>
            ENDPOINTS · 142<br/>
            CALLS (30D) · 9.2M<br/>
            P50 LATENCY · 64ms
          </div>
        </Panel>
      </div>
    </div>
  );
}

function FlowDiagram() {
  const inbound = [
    ["DAT", "loads + capacity"],
    ["Highway", "carrier identity"],
    ["MacroPoint", "GPS"],
    ["Samsara", "HOS · ELD"],
    ["RMIS", "insurance"],
    ["SAFER", "authority"],
    ["SPS Commerce", "EDI 204/214"],
    ["Twilio", "calls + SMS"],
    ["Gmail", "carrier emails"],
  ];
  const outbound = [
    ["DAT", "load posts"],
    ["TriumphPay", "payments"],
    ["QuickBooks", "invoices"],
    ["MacroPoint", "trip refs"],
    ["Shipper portal", "ETA + POD"],
    ["Slack", "alerts"],
    ["EDI 990/210", "responses"],
    ["Comdata", "fuel · advances"],
    ["Apex Capital", "factor NOAs"],
  ];

  return (
    <div style={{ display: "grid", gridTemplateColumns: "240px 1fr 240px", gap: 30, alignItems: "stretch", minHeight: 480 }}>
      {/* LEFT: inbound */}
      <div style={{ display: "flex", flexDirection: "column", gap: 8, justifyContent: "space-evenly" }}>
        {inbound.map((x, i) => (
          <div key={i} style={{
            display: "flex", alignItems: "center", justifyContent: "space-between",
            padding: "10px 14px",
            background: "var(--bg-2)",
            borderLeft: "2px solid var(--accent)",
            borderRadius: 3,
            fontSize: 12,
          }}>
            <span style={{ fontWeight: 600 }}>{x[0]}</span>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-dim)" }}>{x[1]}</span>
          </div>
        ))}
      </div>

      {/* CENTER: the core */}
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", position: "relative" }}>
        {/* Connecting lines */}
        <svg viewBox="0 0 400 480" preserveAspectRatio="none" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
          {/* in lines */}
          {inbound.map((_, i) => {
            const y = 30 + i * (420 / inbound.length);
            return <path key={`in-${i}`} d={`M0,${y} C100,${y} 100,240 200,240`} stroke="var(--accent)" strokeWidth="1" fill="none" opacity="0.4" />;
          })}
          {outbound.map((_, i) => {
            const y = 30 + i * (420 / outbound.length);
            return <path key={`out-${i}`} d={`M200,240 C300,240 300,${y} 400,${y}`} stroke="var(--blue)" strokeWidth="1" fill="none" opacity="0.4" />;
          })}
        </svg>

        {/* The keel — center node */}
        <div style={{ position: "relative", zIndex: 1, textAlign: "center" }}>
          <div style={{
            width: 180, height: 180,
            borderRadius: "50%",
            background: "var(--bg-1)",
            border: "3px solid var(--accent)",
            display: "grid", placeItems: "center",
            boxShadow: "0 0 0 12px var(--accent-bg), 0 8px 32px rgba(0,0,0,0.08)",
            position: "relative",
          }}>
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--accent)", letterSpacing: "0.2em", textAlign: "center" }}>KEELWAY</div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-dim)", letterSpacing: "0.16em", textAlign: "center", marginTop: 4 }}>CORE</div>
              <div style={{ marginTop: 12, fontSize: 11, color: "var(--text-mid)", textAlign: "center", lineHeight: 1.4 }}>
                Loads · Carriers<br/>Quotes · Settlements<br/>AI Agents
              </div>
            </div>
          </div>
          <div style={{ marginTop: 18, fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-dim)", letterSpacing: "0.14em" }}>
            EVENT BUS · 84 EVENT TYPES
          </div>
        </div>
      </div>

      {/* RIGHT: outbound */}
      <div style={{ display: "flex", flexDirection: "column", gap: 8, justifyContent: "space-evenly" }}>
        {outbound.map((x, i) => (
          <div key={i} style={{
            display: "flex", alignItems: "center", justifyContent: "space-between",
            padding: "10px 14px",
            background: "var(--bg-2)",
            borderRight: "2px solid var(--blue)",
            borderRadius: 3,
            fontSize: 12,
          }}>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-dim)" }}>{x[1]}</span>
            <span style={{ fontWeight: 600 }}>{x[0]}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

window.Integrations = Integrations;
