import { useState, useEffect, useRef, useCallback } from "react";

// ─── Mock Data ──────────────────────────────────────────────────────────────
const MOCK_USER = {
  name: "Sarah Mitchell",
  email: "smitchell@jnj.com",
  department: "Manufacturing Operations",
  site: "2847",
  siteName: "Janssen Beerse",
  role: "Site Service Owner",
  avatar: "SM",
};

const HISTORICAL_TICKETS = [
  {
    id: "RITM0041287",
    jiraKey: "ABFZ-3421",
    type: "Network Request",
    title: "LAN/WAN Port Enablement – Building 4, Floor 2",
    site: "2847",
    status: "Completed",
    date: "2025-11-14",
    similarity: 0.94,
    description: "Enable 24 new LAN drops in Building 4, Floor 2 for new lab workstations. Switch: SW-BLD4-F2-01. ICE network zone.",
    priority: "P3",
    assignedTo: "Pete Ward",
    assignedEmail: "pward@jnj.com",
    capabilityCenter: "Approved Project Demand",
    nexusId: "NX-2024-0891",
    completionDays: 14,
    complexityTier: "SIMPLE",
    complexityItems: 3,
    costEstimate: {
      baseCost: 18400,
      geoMultiplier: 1.0,
      geoRegion: "US",
      networkSurcharge: 2400,
      firewallFee: 0,
      medDeviceCompliance: 0,
      totalEstimated: 20800,
      confidence: 0.89,
    },
    quotation: {
      vendor: "Panduit Corporation",
      invoiceNumber: "INV-2025-PAN-1184",
      invoiceDate: "2025-10-28",
      poNumber: "PO-4500923187",
      lineItems: [
        { desc: "Cat6A Patch Cable (10ft)", qty: 24, unitCost: 28.50, total: 684.00 },
        { desc: "RJ45 Keystone Jack (Cat6A)", qty: 48, unitCost: 12.00, total: 576.00 },
        { desc: "Cable Drop Installation (per drop)", qty: 24, unitCost: 450.00, total: 10800.00 },
        { desc: "Switch Port Activation (per port)", qty: 24, unitCost: 75.00, total: 1800.00 },
        { desc: "Network Testing & Certification", qty: 1, unitCost: 2500.00, total: 2500.00 },
        { desc: "Project Management", qty: 1, unitCost: 2040.00, total: 2040.00 },
      ],
      subtotal: 18400.00,
      tax: 0,
      total: 18400.00,
      pdfFileName: "AESR_Panduit_OCT_28_2025.pdf",
    },
  },
  {
    id: "RITM0039854",
    jiraKey: "ABFZ-3198",
    type: "Solution Intake",
    title: "mPOD Deployment – Clean Room Monitoring System",
    site: "2847",
    status: "In Progress",
    date: "2025-12-02",
    similarity: 0.72,
    description: "Deploy mPOD sensors across clean room facilities for real-time environmental monitoring. Integration with existing SCADA system required.",
    priority: "P2",
    assignedTo: "Joe Ryan",
    assignedEmail: "jryan3@jnj.com",
    capabilityCenter: "Agile Demand",
    nexusId: "NX-2025-0134",
    completionDays: 18,
    complexityTier: "COMPLEX",
    complexityItems: 28,
    costEstimate: {
      baseCost: 98200,
      geoMultiplier: 1.0,
      geoRegion: "US",
      networkSurcharge: 4200,
      firewallFee: 0,
      medDeviceCompliance: 14730,
      totalEstimated: 117130,
      confidence: 0.92,
    },
    quotation: {
      vendor: "Crown Equipment Corporation",
      invoiceNumber: "INV-2024-AESR-0847",
      invoiceDate: "2024-08-08",
      poNumber: "PO-4500891234",
      lineItems: [
        { desc: "InfoLink Terminal IT5000 (forklift-mounted)", qty: 24, unitCost: 1850.00, total: 44400.00 },
        { desc: "InfoLink Gateway Server (rack-mount)", qty: 2, unitCost: 6500.00, total: 13000.00 },
        { desc: "Wireless Access Point (industrial-grade)", qty: 8, unitCost: 1200.00, total: 9600.00 },
        { desc: "Installation & Configuration (per unit)", qty: 34, unitCost: 350.00, total: 11900.00 },
        { desc: "Crown InfoLink Software License (annual)", qty: 24, unitCost: 450.00, total: 10800.00 },
        { desc: "Project Management & Training", qty: 1, unitCost: 8500.00, total: 8500.00 },
      ],
      subtotal: 98200.00,
      tax: 0,
      total: 98200.00,
      pdfFileName: "AESR_Crown_Equipment_AUG_08_2024.pdf",
    },
  },
  {
    id: "RITM0038221",
    jiraKey: "ABFZ-2987",
    type: "Network Request",
    title: "Firewall MACD – Vendor VPN Access for Site 2847",
    site: "2847",
    status: "Pending Approval",
    date: "2026-01-08",
    similarity: 0.67,
    description: "Open firewall rules for vendor VPN tunnel. Vendor: Siemens AG. Required for PLC programming access during March shutdown.",
    priority: "P2",
    assignedTo: "Katherine Diaz",
    assignedEmail: "kdiaz2@jnj.com",
    capabilityCenter: "TS Internal Demand",
    completionDays: 8,
    complexityTier: "MEDIUM",
    complexityItems: 12,
    costEstimate: {
      baseCost: 8400,
      geoMultiplier: 1.3,
      geoRegion: "EU",
      networkSurcharge: 0,
      firewallFee: 3200,
      medDeviceCompliance: 0,
      totalEstimated: 14120,
      confidence: 0.85,
    },
    quotation: {
      vendor: "Siemens AG",
      invoiceNumber: "INV-2025-SIE-2901",
      invoiceDate: "2025-12-15",
      poNumber: "PO-4500934521",
      lineItems: [
        { desc: "Firewall Rule Configuration (per rule)", qty: 8, unitCost: 450.00, total: 3600.00 },
        { desc: "VPN Tunnel Setup & Configuration", qty: 1, unitCost: 2800.00, total: 2800.00 },
        { desc: "Security Assessment & Pen Test", qty: 1, unitCost: 1500.00, total: 1500.00 },
        { desc: "Documentation & Compliance", qty: 1, unitCost: 500.00, total: 500.00 },
      ],
      subtotal: 8400.00,
      tax: 0,
      total: 8400.00,
      pdfFileName: "AESR_Siemens_DEC_15_2025.pdf",
    },
  },
];

const LIVE_TICKET = {
  id: "RITM0041287", jiraKey: "ABFZ-3421",
  title: "LAN/WAN Port Enablement – Building 4, Floor 2",
  status: "In Progress", priority: "P3",
  createdDate: "2025-11-14", updatedDate: "2026-02-14",
  estimatedCompletion: "2026-02-28",
  complexityTier: "SIMPLE", totalCost: "$20,800",
  assignedTo: { name: "Pete Ward", email: "pward@jnj.com", phone: "+1 (732) 555-0147", team: "MLL Network Team" },
  approver: { name: "Katherine Diaz", email: "kdiaz2@jnj.com" },
  timeline: [
    { date: "2025-11-14", event: "RITM Created", status: "complete", agent: "System" },
    { date: "2025-11-14", event: "Jira Epic ABFZ-3421 auto-created", status: "complete", agent: "IRIS Automation" },
    { date: "2025-11-18", event: "Gather User Stories task assigned", status: "complete", agent: "Service Owner" },
    { date: "2025-12-02", event: "Network RITM created & linked", status: "complete", agent: "Sarah Mitchell" },
    { date: "2025-12-09", event: "Reviewed on intake triage call", status: "complete", agent: "Katherine Diaz" },
    { date: "2026-01-06", event: "Approved – assigned to Pete Ward's team", status: "complete", agent: "Pete Ward" },
    { date: "2026-01-20", event: "Switch configuration in progress", status: "active", agent: "Network Team" },
    { date: "2026-02-28", event: "Target: Cable drops installation", status: "pending", agent: "Vendor" },
  ],
};

const COMPLEXITY_CONFIG = {
  SIMPLE: { color: "#4ade80", bg: "rgba(34,197,94,0.12)", border: "rgba(34,197,94,0.3)", icon: "🟢", label: "Simple", items: "1–5 items", range: "$5K–$25K", days: "12–15 days", agents: ["Intake Agent", "Status Agent"] },
  MEDIUM: { color: "#fbbf24", bg: "rgba(251,191,36,0.12)", border: "rgba(251,191,36,0.3)", icon: "🟡", label: "Medium", items: "5–20 items", range: "$25K–$100K", days: "15–18 days", agents: ["Intake Agent", "Network Agent", "Status Agent"] },
  COMPLEX: { color: "#f87171", bg: "rgba(248,113,113,0.12)", border: "rgba(248,113,113,0.3)", icon: "🔴", label: "Complex", items: "20+ items", range: "$100K–$500K+", days: "18–20+ days", agents: ["Intake Agent", "Network Agent", "Knowledge Agent", "Status Agent", "Escalation to Human"] },
};

const CLASSIFICATION_STAGES = [
  { name: "NER", label: "Entity Recognition", icon: "🔍", desc: "Extracting: SITE, REQUEST_TYPE, COMPONENT" },
  { name: "Ontology", label: "Ontology Reasoning", icon: "🧠", desc: "SWRL rules → Network Request detected" },
  { name: "Embedding", label: "Semantic Matching", icon: "📊", desc: "384-dim cosine similarity (>0.87)" },
  { name: "Context", label: "Graph Enrichment", icon: "🔗", desc: "Team patterns & resolution history" },
];

// ─── Icons ──────────────────────────────────────────────────────────────────
const Icons = {
  Send: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>,
  Bot: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="10" rx="2"/><circle cx="12" cy="5" r="2"/><path d="M12 7v4"/><line x1="8" y1="16" x2="8" y2="16"/><line x1="16" y1="16" x2="16" y2="16"/></svg>,
  Check: () => <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>,
  Phone: () => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 16.92z"/></svg>,
  Mail: () => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>,
  Edit: () => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>,
  Track: () => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>,
  Sparkle: () => <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0L14.59 8.41L23 12L14.59 15.59L12 24L9.41 15.59L1 12L9.41 8.41Z"/></svg>,
  Arrow: () => <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>,
  PDF: () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>,
  Dollar: () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>,
  ChevDown: () => <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>,
  ChevUp: () => <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="18 15 12 9 6 15"/></svg>,
  Upload: () => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="16 16 12 12 8 16"/><line x1="12" y1="12" x2="12" y2="21"/><path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3"/></svg>,
};

const fmt = (n) => "$" + n.toLocaleString("en-US", { minimumFractionDigits: 0 });

// ─── Typing Indicator ───────────────────────────────────────────────────────
const TypingIndicator = () => (
  <div style={{ display: "flex", gap: 4, padding: "8px 0", alignItems: "center" }}>
    {[0, 1, 2].map((i) => <div key={i} style={{ width: 7, height: 7, borderRadius: "50%", background: "#6366f1", animation: `typingBounce 1.4s infinite ${i * 0.2}s` }} />)}
  </div>
);

// ─── Complexity Tier Badge ──────────────────────────────────────────────────
const ComplexityBadge = ({ tier, size = "sm" }) => {
  const c = COMPLEXITY_CONFIG[tier];
  if (!c) return null;
  const isSm = size === "sm";
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: isSm ? 4 : 6,
      padding: isSm ? "2px 8px" : "4px 12px", borderRadius: 20,
      background: c.bg, border: `1px solid ${c.border}`,
      fontSize: isSm ? 10 : 12, fontWeight: 700, color: c.color,
    }}>
      {c.icon} {c.label}
    </span>
  );
};

// ─── PDF Invoice Viewer ─────────────────────────────────────────────────────
const InvoiceViewer = ({ quotation, isExpanded, onToggle }) => {
  if (!quotation) return null;
  return (
    <div style={{
      background: "rgba(99,102,241,0.04)", border: "1px solid rgba(99,102,241,0.15)",
      borderRadius: 10, overflow: "hidden", marginTop: 8,
    }}>
      <button onClick={onToggle} style={{
        width: "100%", padding: "10px 14px", border: "none", cursor: "pointer",
        background: "transparent", display: "flex", alignItems: "center", gap: 8,
        justifyContent: "space-between",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <div style={{ width: 28, height: 28, borderRadius: 6, background: "rgba(239,68,68,0.15)", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icons.PDF />
          </div>
          <div style={{ textAlign: "left" }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: "#e2e8f0" }}>{quotation.pdfFileName}</div>
            <div style={{ fontSize: 10, color: "#64748b" }}>{quotation.vendor} · {quotation.invoiceDate} · {fmt(quotation.total)}</div>
          </div>
        </div>
        <span style={{ color: "#64748b" }}>{isExpanded ? <Icons.ChevUp /> : <Icons.ChevDown />}</span>
      </button>
      {isExpanded && (
        <div style={{ padding: "0 14px 14px", animation: "fadeSlideIn 0.2s ease" }}>
          <div style={{ display: "flex", gap: 12, marginBottom: 10, flexWrap: "wrap" }}>
            {[["Invoice #", quotation.invoiceNumber], ["PO #", quotation.poNumber], ["Vendor", quotation.vendor]].map(([k, v]) => (
              <div key={k}><span style={{ fontSize: 9, color: "#64748b", textTransform: "uppercase", letterSpacing: 0.5 }}>{k}</span><div style={{ fontSize: 11, color: "#c7d2fe", fontFamily: "'JetBrains Mono', monospace", marginTop: 1 }}>{v}</div></div>
            ))}
          </div>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 10 }}>
            <thead>
              <tr style={{ borderBottom: "1px solid rgba(255,255,255,0.08)" }}>
                {["Line Item", "Qty", "Unit Cost", "Total"].map((h) => (
                  <th key={h} style={{ padding: "6px 8px", textAlign: h === "Line Item" ? "left" : "right", color: "#64748b", fontWeight: 600, textTransform: "uppercase", letterSpacing: 0.5, fontSize: 9 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {quotation.lineItems.map((item, i) => (
                <tr key={i} style={{ borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
                  <td style={{ padding: "6px 8px", color: "#cbd5e1" }}>{item.desc}</td>
                  <td style={{ padding: "6px 8px", textAlign: "right", color: "#94a3b8", fontFamily: "'JetBrains Mono', monospace" }}>{item.qty}</td>
                  <td style={{ padding: "6px 8px", textAlign: "right", color: "#94a3b8", fontFamily: "'JetBrains Mono', monospace" }}>{fmt(item.unitCost)}</td>
                  <td style={{ padding: "6px 8px", textAlign: "right", color: "#e2e8f0", fontWeight: 600, fontFamily: "'JetBrains Mono', monospace" }}>{fmt(item.total)}</td>
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr style={{ borderTop: "2px solid rgba(99,102,241,0.3)" }}>
                <td colSpan={3} style={{ padding: "8px", textAlign: "right", color: "#a5b4fc", fontWeight: 700 }}>TOTAL</td>
                <td style={{ padding: "8px", textAlign: "right", color: "#a5b4fc", fontWeight: 800, fontFamily: "'JetBrains Mono', monospace", fontSize: 12 }}>{fmt(quotation.total)}</td>
              </tr>
            </tfoot>
          </table>
        </div>
      )}
    </div>
  );
};

// ─── Cost Estimation Card ───────────────────────────────────────────────────
const CostEstimationCard = ({ ticket }) => {
  const c = ticket.costEstimate;
  const tier = COMPLEXITY_CONFIG[ticket.complexityTier];
  return (
    <div style={{
      background: "linear-gradient(135deg, rgba(99,102,241,0.06), rgba(139,92,246,0.04))",
      border: `1px solid ${tier.border}`, borderRadius: 12, padding: 16, margin: "8px 0",
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <Icons.Dollar />
          <span style={{ fontSize: 12, fontWeight: 700, color: "#c7d2fe" }}>AI Cost Estimation</span>
          <span style={{ fontSize: 9, color: "#64748b", background: "rgba(255,255,255,0.06)", padding: "2px 8px", borderRadius: 10 }}>65% confidence · instant</span>
        </div>
        <ComplexityBadge tier={ticket.complexityTier} size="md" />
      </div>

      {/* Complexity Tier Info */}
      <div style={{
        display: "flex", gap: 16, padding: "10px 14px", background: tier.bg,
        borderRadius: 8, marginBottom: 12, border: `1px solid ${tier.border}`,
      }}>
        <div><div style={{ fontSize: 9, color: "#64748b" }}>SCOPE</div><div style={{ fontSize: 11, color: tier.color, fontWeight: 600 }}>{ticket.complexityItems} items → {tier.label}</div></div>
        <div><div style={{ fontSize: 9, color: "#64748b" }}>RANGE</div><div style={{ fontSize: 11, color: "#e2e8f0", fontWeight: 600 }}>{tier.range}</div></div>
        <div><div style={{ fontSize: 9, color: "#64748b" }}>TIMELINE</div><div style={{ fontSize: 11, color: "#e2e8f0", fontWeight: 600 }}>{tier.days}</div></div>
      </div>

      {/* Cost Formula Breakdown */}
      <div style={{ fontSize: 10, fontFamily: "'JetBrains Mono', monospace", color: "#94a3b8", marginBottom: 10, padding: "8px 12px", background: "rgba(0,0,0,0.2)", borderRadius: 6, lineHeight: 1.8 }}>
        <span style={{ color: "#64748b" }}>Est_Cost = </span>
        <span style={{ color: "#e2e8f0" }}>Σ(Unit×Qty)</span>
        <span style={{ color: "#64748b" }}> × </span>
        <span style={{ color: "#fbbf24" }}>Geo({c.geoRegion} {c.geoMultiplier}x)</span>
        <span style={{ color: "#64748b" }}> + </span>
        <span style={{ color: "#818cf8" }}>Surcharges</span>
      </div>

      {/* Line items breakdown */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6, marginBottom: 10 }}>
        {[
          ["Base Cost (from invoice)", c.baseCost, "#e2e8f0"],
          [`Geo Multiplier (${c.geoRegion})`, `×${c.geoMultiplier}`, "#fbbf24"],
          ["Network Surcharge", c.networkSurcharge, "#818cf8"],
          ["Firewall Fee", c.firewallFee, "#818cf8"],
          ["Med Device Compliance (+15%)", c.medDeviceCompliance, c.medDeviceCompliance > 0 ? "#f87171" : "#475569"],
        ].map(([label, val, color]) => (
          <div key={label} style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
            <span style={{ fontSize: 10, color: "#94a3b8" }}>{label}</span>
            <span style={{ fontSize: 10, color, fontWeight: 600, fontFamily: "'JetBrains Mono', monospace" }}>
              {typeof val === "number" ? fmt(val) : val}
            </span>
          </div>
        ))}
      </div>

      {/* Total */}
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        padding: "10px 14px", background: "rgba(99,102,241,0.1)", borderRadius: 8,
        border: "1px solid rgba(99,102,241,0.25)",
      }}>
        <span style={{ fontSize: 12, fontWeight: 700, color: "#a5b4fc" }}>TOTAL ESTIMATED COST</span>
        <span style={{ fontSize: 18, fontWeight: 800, color: "#e2e8f0", fontFamily: "'JetBrains Mono', monospace" }}>{fmt(c.totalEstimated)}</span>
      </div>

      {/* Agents Called for this Tier */}
      <div style={{ marginTop: 10 }}>
        <div style={{ fontSize: 9, color: "#64748b", textTransform: "uppercase", letterSpacing: 1, marginBottom: 6 }}>Agents Activated for {tier.label} Tier</div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
          {tier.agents.map((a) => (
            <span key={a} style={{
              fontSize: 9, padding: "3px 8px", borderRadius: 12,
              background: a.includes("Escalation") ? "rgba(248,113,113,0.12)" : "rgba(99,102,241,0.1)",
              color: a.includes("Escalation") ? "#f87171" : "#a5b4fc",
              border: `1px solid ${a.includes("Escalation") ? "rgba(248,113,113,0.3)" : "rgba(99,102,241,0.2)"}`,
              fontWeight: 600,
            }}>
              {a}
            </span>
          ))}
        </div>
      </div>
    </div>
  );
};

// ─── Classification Pipeline Visual ─────────────────────────────────────────
const ClassificationPipeline = ({ activeStage, completedStages }) => (
  <div style={{ background: "linear-gradient(135deg, #0f172a, #1e1b4b)", borderRadius: 12, padding: "16px 20px", margin: "8px 0", border: "1px solid rgba(99,102,241,0.3)" }}>
    <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 12 }}>
      <Icons.Sparkle />
      <span style={{ fontSize: 11, fontWeight: 700, color: "#a5b4fc", letterSpacing: 1.5, textTransform: "uppercase" }}>4-Stage Semantic Classification</span>
    </div>
    <div style={{ display: "flex", gap: 8 }}>
      {CLASSIFICATION_STAGES.map((stage, i) => {
        const isComplete = completedStages.includes(i);
        const isActive = activeStage === i;
        return (
          <div key={stage.name} style={{
            flex: 1, padding: "10px 8px", borderRadius: 8, textAlign: "center",
            background: isComplete ? "rgba(34,197,94,0.15)" : isActive ? "rgba(99,102,241,0.2)" : "rgba(255,255,255,0.04)",
            border: `1px solid ${isComplete ? "rgba(34,197,94,0.4)" : isActive ? "rgba(99,102,241,0.5)" : "rgba(255,255,255,0.08)"}`,
            transition: "all 0.4s", transform: isActive ? "scale(1.03)" : "scale(1)",
          }}>
            <div style={{ fontSize: 18, marginBottom: 4 }}>{stage.icon}</div>
            <div style={{ fontSize: 10, fontWeight: 600, color: isComplete ? "#4ade80" : isActive ? "#a5b4fc" : "#64748b", marginBottom: 2 }}>{stage.label}</div>
            {(isActive || isComplete) && <div style={{ fontSize: 9, color: "#94a3b8", lineHeight: 1.3, marginTop: 4 }}>{stage.desc}</div>}
            {isActive && <div style={{ width: "100%", height: 2, background: "rgba(99,102,241,0.2)", borderRadius: 1, marginTop: 6, overflow: "hidden" }}><div style={{ height: "100%", background: "#6366f1", borderRadius: 1, animation: "pipelineProgress 1.5s ease-in-out infinite" }}/></div>}
          </div>
        );
      })}
    </div>
  </div>
);

// ─── Ticket Card ────────────────────────────────────────────────────────────
const TicketCard = ({ ticket, onSelect, onTrack, compact, expandedInvoice, onToggleInvoice }) => {
  const statusColor = { Completed: "#4ade80", "In Progress": "#fbbf24", "Pending Approval": "#f97316" }[ticket.status] || "#94a3b8";
  return (
    <div style={{
      background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)",
      borderRadius: 10, padding: compact ? 12 : 16, cursor: "default",
      transition: "all 0.2s", position: "relative", overflow: "hidden",
    }}
      onMouseEnter={(e) => { e.currentTarget.style.borderColor = "rgba(99,102,241,0.4)"; e.currentTarget.style.background = "rgba(99,102,241,0.04)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.borderColor = "rgba(255,255,255,0.08)"; e.currentTarget.style.background = "rgba(255,255,255,0.03)"; }}
    >
      {/* Top row: match + complexity */}
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
        <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
          <span style={{ fontSize: 11, fontWeight: 700, color: "#818cf8", fontFamily: "'JetBrains Mono', monospace" }}>{ticket.id}</span>
          <span style={{ fontSize: 9, color: "#475569" }}>→</span>
          <span style={{ fontSize: 11, color: "#94a3b8", fontFamily: "'JetBrains Mono', monospace" }}>{ticket.jiraKey}</span>
        </div>
        <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
          {ticket.similarity && (
            <span style={{
              background: ticket.similarity > 0.9 ? "rgba(34,197,94,0.15)" : "rgba(251,191,36,0.15)",
              color: ticket.similarity > 0.9 ? "#4ade80" : "#fbbf24", fontSize: 10, fontWeight: 700,
              padding: "2px 8px", borderRadius: 20,
            }}>{Math.round(ticket.similarity * 100)}% match</span>
          )}
          <ComplexityBadge tier={ticket.complexityTier} />
        </div>
      </div>
      <div style={{ fontSize: 13, fontWeight: 600, color: "#e2e8f0", marginBottom: 4, lineHeight: 1.4 }}>{ticket.title}</div>
      {!compact && <div style={{ fontSize: 11, color: "#94a3b8", marginBottom: 8, lineHeight: 1.5 }}>{ticket.description}</div>}

      {/* Tags row */}
      <div style={{ display: "flex", flexWrap: "wrap", gap: 5, alignItems: "center", marginBottom: 8 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 10, color: statusColor, background: `${statusColor}15`, padding: "2px 8px", borderRadius: 20 }}>
          <span style={{ width: 5, height: 5, borderRadius: "50%", background: statusColor }}/> {ticket.status}
        </span>
        <span style={{ fontSize: 10, color: "#64748b", background: "rgba(255,255,255,0.05)", padding: "2px 8px", borderRadius: 20 }}>{ticket.type}</span>
        <span style={{ fontSize: 10, color: "#64748b", background: "rgba(255,255,255,0.05)", padding: "2px 8px", borderRadius: 20 }}>{ticket.priority}</span>
        <span style={{ fontSize: 10, color: "#a5b4fc", background: "rgba(99,102,241,0.1)", padding: "2px 8px", borderRadius: 20, fontWeight: 600, fontFamily: "'JetBrains Mono', monospace" }}>
          {fmt(ticket.costEstimate.totalEstimated)}
        </span>
        <span style={{ fontSize: 10, color: "#94a3b8", background: "rgba(255,255,255,0.05)", padding: "2px 8px", borderRadius: 20 }}>
          ~{ticket.completionDays}d
        </span>
      </div>

      {/* PDF Invoice Viewer */}
      {ticket.quotation && !compact && (
        <InvoiceViewer quotation={ticket.quotation} isExpanded={expandedInvoice === ticket.id} onToggle={() => onToggleInvoice?.(ticket.id)} />
      )}

      {/* Action buttons */}
      {(onSelect || onTrack) && (
        <div style={{ display: "flex", gap: 8, marginTop: 10 }}>
          {onSelect && (
            <button onClick={(e) => { e.stopPropagation(); onSelect(); }} style={{
              flex: 1, padding: "7px 0", borderRadius: 6, border: "1px solid rgba(99,102,241,0.3)",
              background: "rgba(99,102,241,0.1)", color: "#a5b4fc", fontSize: 11, fontWeight: 600, cursor: "pointer",
              display: "flex", alignItems: "center", justifyContent: "center", gap: 4,
            }}><Icons.Edit /> Reuse & Edit</button>
          )}
          {onTrack && (
            <button onClick={(e) => { e.stopPropagation(); onTrack(); }} style={{
              flex: 1, padding: "7px 0", borderRadius: 6, border: "1px solid rgba(251,191,36,0.3)",
              background: "rgba(251,191,36,0.1)", color: "#fbbf24", fontSize: 11, fontWeight: 600, cursor: "pointer",
              display: "flex", alignItems: "center", justifyContent: "center", gap: 4,
            }}><Icons.Track /> Track Status</button>
          )}
        </div>
      )}
    </div>
  );
};

// ─── Live Tracker ───────────────────────────────────────────────────────────
const LiveTracker = ({ ticket, onBack }) => (
  <div style={{ padding: 20 }}>
    <button onClick={onBack} style={{ background: "none", border: "none", color: "#818cf8", cursor: "pointer", fontSize: 12, fontWeight: 600, marginBottom: 16, display: "flex", alignItems: "center", gap: 4 }}>← Back to Chat</button>
    <div style={{ background: "linear-gradient(135deg, rgba(99,102,241,0.08), rgba(139,92,246,0.05))", border: "1px solid rgba(99,102,241,0.2)", borderRadius: 14, padding: 20, marginBottom: 16 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 6 }}>
            <span style={{ fontSize: 13, fontWeight: 700, color: "#818cf8", fontFamily: "'JetBrains Mono', monospace" }}>{ticket.id}</span>
            <span style={{ fontSize: 11, color: "#64748b" }}>→</span>
            <span style={{ fontSize: 13, color: "#94a3b8", fontFamily: "'JetBrains Mono', monospace" }}>{ticket.jiraKey}</span>
          </div>
          <div style={{ fontSize: 16, fontWeight: 700, color: "#f1f5f9", lineHeight: 1.4 }}>{ticket.title}</div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 4, alignItems: "flex-end" }}>
          <span style={{ background: "rgba(251,191,36,0.15)", color: "#fbbf24", fontSize: 11, fontWeight: 700, padding: "4px 12px", borderRadius: 20 }}>{ticket.status}</span>
          <ComplexityBadge tier={ticket.complexityTier} size="md" />
        </div>
      </div>
      <div style={{ display: "flex", gap: 20, marginTop: 16 }}>
        {[["Priority", `${ticket.priority} – Standard`], ["Est. Cost", ticket.totalCost], ["Est. Completion", ticket.estimatedCompletion]].map(([k, v]) => (
          <div key={k}><div style={{ fontSize: 9, color: "#64748b", textTransform: "uppercase", letterSpacing: 1 }}>{k}</div><div style={{ fontSize: 13, color: "#e2e8f0", fontWeight: 600, marginTop: 2 }}>{v}</div></div>
        ))}
      </div>
    </div>
    {/* Contacts */}
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 16 }}>
      {[ticket.assignedTo, ticket.approver].map((p, i) => (
        <div key={i} style={{ background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)", borderRadius: 10, padding: 14 }}>
          <div style={{ fontSize: 9, color: "#64748b", textTransform: "uppercase", letterSpacing: 1, marginBottom: 6 }}>{i === 0 ? "Assigned To" : "Approver"}</div>
          <div style={{ fontSize: 13, fontWeight: 600, color: "#e2e8f0", marginBottom: 2 }}>{p.name}</div>
          {p.team && <div style={{ fontSize: 11, color: "#94a3b8", marginBottom: 8 }}>{p.team}</div>}
          <div style={{ display: "flex", gap: 6 }}>
            <a href={`mailto:${p.email}`} style={{ display: "inline-flex", alignItems: "center", gap: 4, padding: "4px 10px", borderRadius: 6, background: "rgba(99,102,241,0.1)", border: "1px solid rgba(99,102,241,0.3)", color: "#a5b4fc", fontSize: 10, fontWeight: 600, textDecoration: "none", cursor: "pointer" }}><Icons.Mail /> Email</a>
            {p.phone && <a href={`tel:${p.phone}`} style={{ display: "inline-flex", alignItems: "center", gap: 4, padding: "4px 10px", borderRadius: 6, background: "rgba(34,197,94,0.1)", border: "1px solid rgba(34,197,94,0.3)", color: "#4ade80", fontSize: 10, fontWeight: 600, textDecoration: "none", cursor: "pointer" }}><Icons.Phone /> Call</a>}
          </div>
        </div>
      ))}
    </div>
    {/* Timeline */}
    <div style={{ background: "rgba(255,255,255,0.02)", border: "1px solid rgba(255,255,255,0.06)", borderRadius: 12, padding: 16 }}>
      <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", textTransform: "uppercase", letterSpacing: 1, marginBottom: 14 }}>Live Timeline</div>
      {ticket.timeline.map((item, i) => (
        <div key={i} style={{ display: "flex", gap: 12 }}>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", minWidth: 20 }}>
            <div style={{ width: 12, height: 12, borderRadius: "50%", flexShrink: 0, background: item.status === "complete" ? "#4ade80" : item.status === "active" ? "#6366f1" : "#334155", border: item.status === "active" ? "2px solid rgba(99,102,241,0.4)" : "none", boxShadow: item.status === "active" ? "0 0 8px rgba(99,102,241,0.5)" : "none", display: "flex", alignItems: "center", justifyContent: "center" }}>
              {item.status === "complete" && <Icons.Check />}
            </div>
            {i < ticket.timeline.length - 1 && <div style={{ width: 1, flex: 1, minHeight: 24, background: item.status === "complete" ? "rgba(74,222,128,0.3)" : "rgba(255,255,255,0.06)" }}/>}
          </div>
          <div style={{ paddingBottom: 16 }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: item.status === "pending" ? "#64748b" : "#e2e8f0" }}>{item.event}</div>
            <div style={{ fontSize: 10, color: "#64748b", marginTop: 2 }}>{item.date} · {item.agent}</div>
          </div>
        </div>
      ))}
    </div>
  </div>
);

// ─── Smart Form ─────────────────────────────────────────────────────────────
const SmartForm = ({ ticket, onSubmit, onCancel }) => {
  const [fields, setFields] = useState({
    site: ticket?.site || MOCK_USER.site, title: ticket?.title || "", description: ticket?.description || "",
    type: ticket?.type || "Network Request", priority: ticket?.priority || "P3",
    capabilityCenter: ticket?.capabilityCenter || "", nexusId: ticket?.nexusId || "",
    networkType: "LAN/WAN", cableDrops: "24", switchName: "", iceNetwork: "Yes",
  });
  const [uploadedFile, setUploadedFile] = useState(ticket?.quotation?.pdfFileName || null);
  const handleChange = (k, v) => setFields((p) => ({ ...p, [k]: v }));

  const fs = { width: "100%", padding: "8px 12px", borderRadius: 8, border: "1px solid rgba(255,255,255,0.1)", background: "rgba(255,255,255,0.04)", color: "#e2e8f0", fontSize: 12, fontFamily: "inherit", outline: "none", boxSizing: "border-box" };
  const ls = { fontSize: 10, fontWeight: 600, color: "#94a3b8", textTransform: "uppercase", letterSpacing: 1, marginBottom: 4, display: "block" };

  return (
    <div style={{ background: "rgba(255,255,255,0.02)", border: "1px solid rgba(255,255,255,0.08)", borderRadius: 12, padding: 16, margin: "8px 0" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 14 }}>
        <Icons.Edit />
        <span style={{ fontSize: 12, fontWeight: 700, color: "#a5b4fc" }}>{ticket ? "Edit Previous Request" : "New Request Form"}</span>
        {ticket && <span style={{ fontSize: 10, color: "#64748b", marginLeft: "auto" }}>Pre-filled from {ticket.id}</span>}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        <div><label style={ls}>Site ID</label><input style={fs} value={fields.site} onChange={(e) => handleChange("site", e.target.value)} /></div>
        <div><label style={ls}>Priority</label><select style={{ ...fs, cursor: "pointer" }} value={fields.priority} onChange={(e) => handleChange("priority", e.target.value)}><option value="P1">P1 – Emergency</option><option value="P2">P2 – High</option><option value="P3">P3 – Standard</option><option value="P4">P4 – Deferred</option></select></div>
        <div style={{ gridColumn: "1 / -1" }}><label style={ls}>Request Title</label><input style={fs} value={fields.title} onChange={(e) => handleChange("title", e.target.value)} /></div>
        <div><label style={ls}>Capability Center</label><select style={{ ...fs, cursor: "pointer" }} value={fields.capabilityCenter} onChange={(e) => handleChange("capabilityCenter", e.target.value)}><option value="Agile Demand">Agile Demand</option><option value="Approved Project Demand">Approved Project Demand</option><option value="BP Estimate">BP Estimate</option><option value="TS Internal Demand">TS Internal Demand</option></select></div>
        <div><label style={ls}>Nexus ID</label><input style={fs} value={fields.nexusId} onChange={(e) => handleChange("nexusId", e.target.value)} placeholder="NX-YYYY-NNNN" /></div>
        <div><label style={ls}>Network Change Type</label><select style={{ ...fs, cursor: "pointer" }} value={fields.networkType} onChange={(e) => handleChange("networkType", e.target.value)}><option>LAN/WAN</option><option>Firewall MACD</option><option>Switch Configuration</option></select></div>
        <div><label style={ls}>Cable Drops</label><input style={fs} type="number" value={fields.cableDrops} onChange={(e) => handleChange("cableDrops", e.target.value)} /></div>
        <div style={{ gridColumn: "1 / -1" }}><label style={ls}>Business Problem & Value</label><textarea style={{ ...fs, minHeight: 70, resize: "vertical" }} value={fields.description} onChange={(e) => handleChange("description", e.target.value)} /></div>

        {/* PDF Upload Section */}
        <div style={{ gridColumn: "1 / -1" }}>
          <label style={ls}>Vendor Quotation (PDF)</label>
          <div style={{
            padding: 12, borderRadius: 8, border: "1px dashed rgba(99,102,241,0.3)",
            background: "rgba(99,102,241,0.04)", display: "flex", alignItems: "center", gap: 10,
          }}>
            {uploadedFile ? (
              <>
                <div style={{ width: 32, height: 32, borderRadius: 6, background: "rgba(239,68,68,0.15)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icons.PDF /></div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 11, fontWeight: 600, color: "#e2e8f0" }}>{uploadedFile}</div>
                  <div style={{ fontSize: 10, color: "#4ade80" }}>✓ OCR parsed · Line items extracted · Cost factors computed</div>
                </div>
                <button onClick={() => setUploadedFile(null)} style={{ fontSize: 10, color: "#f87171", background: "none", border: "none", cursor: "pointer" }}>Remove</button>
              </>
            ) : (
              <>
                <Icons.Upload />
                <div>
                  <div style={{ fontSize: 11, color: "#a5b4fc", fontWeight: 600 }}>Drop vendor invoice PDF here or click to browse</div>
                  <div style={{ fontSize: 10, color: "#64748b" }}>System will OCR-parse line items, costs, and vendor info automatically</div>
                </div>
              </>
            )}
          </div>
        </div>
      </div>
      <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
        <button onClick={() => onSubmit(fields)} style={{ flex: 1, padding: "10px 0", borderRadius: 8, border: "none", background: "linear-gradient(135deg, #6366f1, #8b5cf6)", color: "white", fontSize: 12, fontWeight: 700, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", gap: 6 }}><Icons.Send /> Submit Request</button>
        {onCancel && <button onClick={onCancel} style={{ padding: "10px 20px", borderRadius: 8, border: "1px solid rgba(255,255,255,0.1)", background: "transparent", color: "#94a3b8", fontSize: 12, fontWeight: 600, cursor: "pointer" }}>Cancel</button>}
      </div>
    </div>
  );
};

// ─── Quick Actions ──────────────────────────────────────────────────────────
const QuickActions = ({ actions, onAction }) => (
  <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 8 }}>
    {actions.map((a) => (
      <button key={a.id} onClick={() => onAction(a)} style={{
        padding: "7px 14px", borderRadius: 20, border: "1px solid rgba(99,102,241,0.3)",
        background: "rgba(99,102,241,0.08)", color: "#a5b4fc", fontSize: 12, fontWeight: 500, cursor: "pointer",
        display: "flex", alignItems: "center", gap: 5, transition: "all 0.2s",
      }}
        onMouseEnter={(e) => { e.currentTarget.style.background = "rgba(99,102,241,0.2)"; }}
        onMouseLeave={(e) => { e.currentTarget.style.background = "rgba(99,102,241,0.08)"; }}
      ><span>{a.icon}</span> {a.label}</button>
    ))}
  </div>
);

// ─── Success Banner ─────────────────────────────────────────────────────────
const SuccessBanner = ({ ritmId, jiraKey, tier }) => (
  <div style={{ background: "linear-gradient(135deg, rgba(34,197,94,0.1), rgba(16,185,129,0.05))", border: "1px solid rgba(34,197,94,0.3)", borderRadius: 12, padding: 16, margin: "8px 0" }}>
    <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
      <div style={{ width: 28, height: 28, borderRadius: "50%", background: "rgba(34,197,94,0.2)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icons.Check /></div>
      <span style={{ fontSize: 14, fontWeight: 700, color: "#4ade80" }}>Request Submitted Successfully!</span>
      <ComplexityBadge tier={tier} />
    </div>
    <div style={{ display: "flex", gap: 16, fontSize: 12 }}>
      <div><span style={{ color: "#64748b" }}>RITM: </span><span style={{ color: "#e2e8f0", fontWeight: 600, fontFamily: "'JetBrains Mono', monospace" }}>{ritmId}</span></div>
      <div><span style={{ color: "#64748b" }}>Jira: </span><span style={{ color: "#e2e8f0", fontWeight: 600, fontFamily: "'JetBrains Mono', monospace" }}>{jiraKey}</span></div>
    </div>
    <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 8, lineHeight: 1.5 }}>
      IRIS automation will create Jira Epic and "Gather User Stories" task. Vendor quotation attached. Network RITM will be reviewed on next intake triage call.
    </div>
  </div>
);

// ═══════════════════════════════════════════════════════════════════════════
// MAIN APP
// ═══════════════════════════════════════════════════════════════════════════
export default function MLLIntakeSystem() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");
  const [phase, setPhase] = useState("init");
  const [classifyStage, setClassifyStage] = useState(-1);
  const [classifyComplete, setClassifyComplete] = useState([]);
  const [showTracker, setShowTracker] = useState(false);
  const [sidebarTab, setSidebarTab] = useState("pipeline");
  const [expandedInvoice, setExpandedInvoice] = useState(null);
  const [detectedTier, setDetectedTier] = useState(null);
  const chatEndRef = useRef(null);

  const scrollToBottom = () => setTimeout(() => chatEndRef.current?.scrollIntoView({ behavior: "smooth" }), 50);
  const addMessage = useCallback((msg) => { setMessages((p) => [...p, { ...msg, id: Date.now() + Math.random(), time: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) }]); scrollToBottom(); }, []);
  const addBot = useCallback((content, extra = {}) => addMessage({ role: "bot", content, ...extra }), [addMessage]);
  const addUser = useCallback((content) => addMessage({ role: "user", content }), [addMessage]);

  // Init
  useEffect(() => {
    if (phase !== "init") return;
    const t = setTimeout(() => {
      addBot(`Good morning, ${MOCK_USER.name}! 👋 Welcome to MLL Intake. I'm your AI assistant for IT service requests.\n\nHow can I help you today?`, {
        actions: [
          { id: "new_request", icon: "📝", label: "Raise a New Request" },
          { id: "track_status", icon: "📍", label: "Track Existing Ticket" },
          { id: "report_incident", icon: "🚨", label: "Report an Incident" },
          { id: "get_access", icon: "🔑", label: "Request Access" },
        ],
      });
      setPhase("greeting");
    }, 600);
    return () => clearTimeout(t);
  }, [phase, addBot]);

  // Classification pipeline
  const runClassification = useCallback(() => {
    setPhase("classifying");
    setClassifyStage(0);
    setClassifyComplete([]);
    addBot("Analyzing your request through our semantic classification pipeline...", { showPipeline: true });

    [0, 1, 2, 3].forEach((i) => {
      setTimeout(() => { setClassifyStage(i); if (i > 0) setClassifyComplete((p) => [...p, i - 1]); }, i * 1200);
    });

    setTimeout(() => {
      setClassifyComplete([0, 1, 2, 3]);
      setClassifyStage(-1);
      setDetectedTier("SIMPLE");

      addBot("", { showCostEstimation: true, costTicket: HISTORICAL_TICKETS[0] });

      setTimeout(() => {
        addBot(
          `✅ **Classification & Cost Estimation Complete!**\n\n• **Type:** Network Request (LAN/WAN)\n• **Complexity:** 🟢 Simple (3 items, single site)\n• **Confidence:** 94.2% classification · 89% cost confidence\n• **Estimated Cost:** $20,800 (incl. network surcharge)\n• **Timeline:** 12–15 days\n• **Routing:** Pete Ward's Network Team\n• **Agents Activated:** Intake Agent → Network Agent → Status Agent\n\nI found ${HISTORICAL_TICKETS.length} similar historical requests with vendor quotation data. The top match is **94% similar** with an attached PDF invoice from Panduit Corporation.`,
          { showHistory: true }
        );
        setPhase("history");
      }, 800);
    }, 5800);
  }, [addBot]);

  const handleAction = useCallback((action) => {
    switch (action.id) {
      case "new_request":
        addUser("I'd like to raise a new request");
        setTimeout(() => {
          addBot("Of course! Tell me about your request in as much detail as you can — the site, what kind of work is needed, any equipment or vendor details.\n\nFor example: *\"I need 30 new LAN drops in Building 7 for workstations at site 2847, vendor quote from Panduit attached\"*\n\nIf you have a **vendor quotation PDF**, I'll OCR-parse it to extract line items, costs, and automatically estimate the total project cost with the right complexity tier.");
          setPhase("intent");
        }, 500);
        break;
      case "track_status":
        addUser("I want to track an existing ticket");
        setTimeout(() => { addBot("Sure! Here are your recent tickets. Click Track Status on any to see the live timeline and contact the assignee.", { showTrackableTickets: true }); setPhase("tracking"); }, 500);
        break;
      case "reuse_ticket":
        addUser("I'll reuse the previous request and modify it");
        setTimeout(() => { addBot("Great! I've pre-filled from your top match including the vendor quotation. The cost will recalculate based on any changes you make.", { showForm: true, formTicket: HISTORICAL_TICKETS[0] }); setPhase("form"); }, 500);
        break;
      case "new_from_scratch":
        addUser("I'll start a brand new request");
        setTimeout(() => { addBot("No problem! Fresh form with your site pre-filled. Upload a vendor quotation PDF if you have one — I'll OCR-parse it automatically.", { showForm: true, formTicket: null }); setPhase("form"); }, 500);
        break;
      case "track_ticket": setShowTracker(true); break;
      default: break;
    }
  }, [addBot, addUser]);

  const handleSend = () => {
    const text = input.trim();
    if (!text) return;
    addUser(text);
    setInput("");
    if (phase === "greeting") {
      setTimeout(() => { addBot("Got it! Could you provide more details?\n\n• Which **site** is this for?\n• What **type of work** (network, firewall, server, workstation, mPOD)?\n• Any **vendor** involved or **quotation** to attach?\n• How many items/connections needed?"); setPhase("intent"); }, 500);
    } else if (phase === "intent") {
      setTimeout(() => runClassification(), 500);
    } else if (phase === "submitted") {
      if (text.toLowerCase().includes("track") || text.toLowerCase().includes("status")) setShowTracker(true);
    }
  };

  const handleFormSubmit = (fields) => {
    setPhase("submitting");
    addBot("Submitting request to IRIS with vendor quotation data...", { showTyping: true });
    setTimeout(() => {
      addBot("", { showSuccess: true, ritmId: "RITM0043891", jiraKey: "ABFZ-3689", tier: detectedTier || "SIMPLE" });
      setTimeout(() => {
        addBot("Your request is live! Here's the automation chain:\n\n1. IRIS RITM **RITM0043891** created with vendor quotation attached\n2. Jira Epic **ABFZ-3689** auto-created\n3. Cost estimation: **$20,800** (🟢 Simple tier) → 65% confidence\n4. \"Gather User Stories\" task assigned to you\n5. Network RITM auto-created & linked\n6. Will be reviewed on next **intake triage call**\n7. After human review → refined to **95% confidence** estimate\n\nWould you like to do anything else?", {
          actions: [
            { id: "track_ticket", icon: "📍", label: "Track This Ticket" },
            { id: "new_request", icon: "📝", label: "Raise Another Request" },
          ],
        });
        setPhase("submitted");
      }, 600);
    }, 2200);
  };

  if (showTracker) {
    return (
      <div style={rootStyle}><style>{globalCSS}</style>
        <div style={containerStyle}>
          <div style={headerStyle}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div style={logoStyle}><Icons.Bot /></div>
              <div><div style={{ fontSize: 15, fontWeight: 800, color: "#f1f5f9" }}>MLL Intake</div><div style={{ fontSize: 10, color: "#6366f1", fontWeight: 600 }}>LIVE TICKET TRACKER</div></div>
            </div>
          </div>
          <div style={{ flex: 1, overflowY: "auto" }}><LiveTracker ticket={LIVE_TICKET} onBack={() => setShowTracker(false)} /></div>
        </div>
      </div>
    );
  }

  return (
    <div style={rootStyle}>
      <style>{globalCSS}</style>
      <div style={{ display: "flex", width: "100%", maxWidth: 1240, height: "100%", maxHeight: 850 }}>
        {/* Chat */}
        <div style={containerStyle}>
          <div style={headerStyle}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div style={logoStyle}><Icons.Bot /></div>
              <div>
                <div style={{ fontSize: 15, fontWeight: 800, color: "#f1f5f9" }}>MLL Intake</div>
                <div style={{ fontSize: 10, color: "#4ade80", fontWeight: 600, display: "flex", alignItems: "center", gap: 4 }}>
                  <span style={{ width: 5, height: 5, borderRadius: "50%", background: "#4ade80" }}/> AI Assistant Online
                </div>
              </div>
            </div>
            <div style={{ width: 32, height: 32, borderRadius: "50%", background: "linear-gradient(135deg, #6366f1, #8b5cf6)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 700, color: "white" }}>{MOCK_USER.avatar}</div>
          </div>

          <div style={messagesStyle}>
            {messages.map((msg) => (
              <div key={msg.id} style={{ display: "flex", justifyContent: msg.role === "user" ? "flex-end" : "flex-start", marginBottom: 12, animation: "fadeSlideIn 0.3s ease" }}>
                {msg.role === "bot" && <div style={{ width: 28, height: 28, borderRadius: 8, background: "rgba(99,102,241,0.15)", display: "flex", alignItems: "center", justifyContent: "center", marginRight: 8, flexShrink: 0, marginTop: 2 }}><Icons.Bot /></div>}
                <div style={{
                  maxWidth: msg.role === "user" ? "75%" : "88%",
                  padding: msg.content ? "10px 14px" : "4px 0",
                  borderRadius: msg.role === "user" ? "14px 14px 4px 14px" : "14px 14px 14px 4px",
                  background: msg.role === "user" ? "linear-gradient(135deg, #6366f1, #7c3aed)" : "rgba(255,255,255,0.04)",
                  border: msg.role === "user" ? "none" : "1px solid rgba(255,255,255,0.06)",
                  color: "#e2e8f0", fontSize: 13, lineHeight: 1.6,
                }}>
                  {msg.content && <div style={{ whiteSpace: "pre-wrap" }} dangerouslySetInnerHTML={{ __html: msg.content.replace(/\*\*(.*?)\*\*/g, '<strong style="color:#a5b4fc">$1</strong>').replace(/\*(.*?)\*/g, '<em style="color:#94a3b8">$1</em>') }} />}
                  {msg.showPipeline && <ClassificationPipeline activeStage={classifyStage} completedStages={classifyComplete} />}
                  {msg.showCostEstimation && <CostEstimationCard ticket={msg.costTicket} />}
                  {msg.showHistory && (
                    <div style={{ marginTop: 10 }}>
                      <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", textTransform: "uppercase", letterSpacing: 1, marginBottom: 8 }}>Similar Historical Requests (with Vendor Quotations)</div>
                      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                        {HISTORICAL_TICKETS.map((t) => <TicketCard key={t.id} ticket={t} onSelect={() => handleAction({ id: "reuse_ticket" })} onTrack={() => setShowTracker(true)} expandedInvoice={expandedInvoice} onToggleInvoice={(id) => setExpandedInvoice(expandedInvoice === id ? null : id)} />)}
                      </div>
                      <QuickActions actions={[{ id: "reuse_ticket", icon: "✏️", label: "Reuse Top Match & Edit" }, { id: "new_from_scratch", icon: "🆕", label: "Start Fresh" }]} onAction={handleAction} />
                    </div>
                  )}
                  {msg.showTrackableTickets && (
                    <div style={{ marginTop: 8, display: "flex", flexDirection: "column", gap: 8 }}>
                      {HISTORICAL_TICKETS.map((t) => <TicketCard key={t.id} ticket={t} compact onTrack={() => setShowTracker(true)} />)}
                    </div>
                  )}
                  {msg.showForm && <SmartForm ticket={msg.formTicket} onSubmit={handleFormSubmit} onCancel={() => { addBot("No problem! Let me know how else I can help."); setPhase("greeting"); }} />}
                  {msg.showSuccess && <SuccessBanner ritmId={msg.ritmId} jiraKey={msg.jiraKey} tier={msg.tier} />}
                  {msg.showTyping && <TypingIndicator />}
                  {msg.actions && <QuickActions actions={msg.actions} onAction={handleAction} />}
                  <div style={{ fontSize: 9, color: "#475569", marginTop: 4, textAlign: msg.role === "user" ? "right" : "left" }}>{msg.time}</div>
                </div>
              </div>
            ))}
            <div ref={chatEndRef} />
          </div>

          <div style={inputContainerStyle}>
            <div style={{ display: "flex", gap: 8, alignItems: "flex-end" }}>
              <input value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => e.key === "Enter" && handleSend()}
                placeholder={phase === "intent" ? "Describe your request in detail..." : "Type a message..."}
                style={inputStyle} />
              <button onClick={handleSend} style={sendBtnStyle} disabled={!input.trim()}><Icons.Send /></button>
            </div>
            <div style={{ fontSize: 9, color: "#475569", marginTop: 6, textAlign: "center" }}>
              Powered by 4-Stage Semantic Classification · Cost Estimation Engine · LangGraph Multi-Agent · J&J MLL
            </div>
          </div>
        </div>

        {/* Sidebar */}
        <div style={sidebarStyle}>
          <div style={{ padding: "14px 16px", borderBottom: "1px solid rgba(255,255,255,0.06)" }}>
            <div style={{ fontSize: 11, fontWeight: 800, color: "#94a3b8", textTransform: "uppercase", letterSpacing: 1.5 }}>Decision Analysis</div>
          </div>
          <div style={{ display: "flex", borderBottom: "1px solid rgba(255,255,255,0.06)" }}>
            {["pipeline", "cost", "agents"].map((tab) => (
              <button key={tab} onClick={() => setSidebarTab(tab)} style={{
                flex: 1, padding: "8px 0", border: "none", cursor: "pointer",
                background: sidebarTab === tab ? "rgba(99,102,241,0.1)" : "transparent",
                color: sidebarTab === tab ? "#a5b4fc" : "#64748b",
                fontSize: 10, fontWeight: 600, textTransform: "uppercase",
                borderBottom: sidebarTab === tab ? "2px solid #6366f1" : "2px solid transparent",
              }}>{tab}</button>
            ))}
          </div>
          <div style={{ padding: 14, overflowY: "auto", flex: 1 }}>
            {sidebarTab === "pipeline" && (
              <div>
                <div style={{ fontSize: 10, fontWeight: 700, color: "#94a3b8", marginBottom: 10 }}>CLASSIFICATION PIPELINE</div>
                {CLASSIFICATION_STAGES.map((s, i) => (
                  <div key={i} style={{ display: "flex", gap: 8, marginBottom: 10 }}>
                    <div style={{ width: 24, height: 24, borderRadius: 6, fontSize: 14, background: classifyComplete.includes(i) ? "rgba(34,197,94,0.15)" : "rgba(255,255,255,0.04)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>{s.icon}</div>
                    <div><div style={{ fontSize: 11, fontWeight: 600, color: classifyComplete.includes(i) ? "#4ade80" : "#94a3b8" }}>{s.label}</div><div style={{ fontSize: 9, color: "#64748b", marginTop: 1 }}>{s.desc}</div></div>
                  </div>
                ))}
                {classifyComplete.length === 4 && (
                  <div style={{ marginTop: 12, padding: 10, background: "rgba(34,197,94,0.08)", borderRadius: 8, border: "1px solid rgba(34,197,94,0.2)" }}>
                    <div style={{ fontSize: 10, fontWeight: 700, color: "#4ade80", marginBottom: 6 }}>RESULT</div>
                    <div style={{ fontSize: 11, color: "#e2e8f0" }}>Network Request (LAN/WAN)</div>
                    <div style={{ fontSize: 10, color: "#94a3b8", marginTop: 2 }}>Confidence: 94.2%</div>
                    <div style={{ fontSize: 10, color: "#94a3b8" }}>Route → Pete Ward's Team</div>
                  </div>
                )}
              </div>
            )}
            {sidebarTab === "cost" && (
              <div>
                <div style={{ fontSize: 10, fontWeight: 700, color: "#94a3b8", marginBottom: 10 }}>COST ESTIMATION ENGINE</div>
                <div style={{ fontSize: 9, color: "#64748b", padding: "8px 10px", background: "rgba(0,0,0,0.2)", borderRadius: 6, fontFamily: "'JetBrains Mono', monospace", lineHeight: 1.7, marginBottom: 12 }}>
                  Est = Σ(Unit×Qty) × Geo<br/>+ Network_Surcharge<br/>+ Firewall_Fee<br/>+ MedDevice_Compliance
                </div>
                <div style={{ fontSize: 10, fontWeight: 700, color: "#94a3b8", marginBottom: 8 }}>COMPLEXITY TIERS</div>
                {Object.entries(COMPLEXITY_CONFIG).map(([k, v]) => (
                  <div key={k} style={{ padding: 8, background: v.bg, border: `1px solid ${v.border}`, borderRadius: 8, marginBottom: 6 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                      <span style={{ fontSize: 11, fontWeight: 700, color: v.color }}>{v.icon} {v.label}</span>
                      <span style={{ fontSize: 10, color: "#94a3b8" }}>{v.range}</span>
                    </div>
                    <div style={{ fontSize: 9, color: "#64748b", marginTop: 3 }}>{v.items} · {v.days}</div>
                  </div>
                ))}
                <div style={{ fontSize: 10, fontWeight: 700, color: "#94a3b8", marginTop: 12, marginBottom: 8 }}>GEO MULTIPLIERS</div>
                {[["US", "1.0x", "#4ade80"], ["EU", "1.3x", "#fbbf24"], ["APAC", "1.1x", "#818cf8"], ["LATAM", "0.8x", "#94a3b8"]].map(([r, m, c]) => (
                  <div key={r} style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
                    <span style={{ fontSize: 10, color: "#94a3b8" }}>{r}</span>
                    <span style={{ fontSize: 10, color: c, fontWeight: 600, fontFamily: "'JetBrains Mono', monospace" }}>{m}</span>
                  </div>
                ))}
                <div style={{ fontSize: 10, fontWeight: 700, color: "#94a3b8", marginTop: 12, marginBottom: 8 }}>SURCHARGES</div>
                {[["Network Drops", "$100/drop"], ["Firewall MACD", "$400–$800/rule"], ["Med Device (+15%)", "GxP regulated"]].map(([k, v]) => (
                  <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
                    <span style={{ fontSize: 10, color: "#94a3b8" }}>{k}</span>
                    <span style={{ fontSize: 10, color: "#e2e8f0" }}>{v}</span>
                  </div>
                ))}
              </div>
            )}
            {sidebarTab === "agents" && (
              <div>
                <div style={{ fontSize: 10, fontWeight: 700, color: "#94a3b8", marginBottom: 10 }}>AGENT ROUTING BY TIER</div>
                {Object.entries(COMPLEXITY_CONFIG).map(([k, v]) => (
                  <div key={k} style={{ marginBottom: 12 }}>
                    <div style={{ fontSize: 11, fontWeight: 700, color: v.color, marginBottom: 6 }}>{v.icon} {v.label} Tier</div>
                    {v.agents.map((a) => (
                      <div key={a} style={{ display: "flex", alignItems: "center", gap: 6, padding: "3px 0" }}>
                        <span style={{ width: 5, height: 5, borderRadius: "50%", background: detectedTier === k ? "#4ade80" : "#334155" }} />
                        <span style={{ fontSize: 10, color: detectedTier === k ? "#e2e8f0" : "#64748b" }}>{a}</span>
                      </div>
                    ))}
                  </div>
                ))}
                <div style={{ fontSize: 10, fontWeight: 700, color: "#94a3b8", marginTop: 16, marginBottom: 8 }}>TWO-TIER CONFIDENCE</div>
                {[["65% – AI Instant", "Ballpark estimate from embeddings + historical cost data", "#fbbf24"], ["95% – Human Refined", "After approver review on triage call", "#4ade80"]].map(([k, v, c]) => (
                  <div key={k} style={{ padding: 8, background: `${c}08`, border: `1px solid ${c}30`, borderRadius: 8, marginBottom: 6 }}>
                    <div style={{ fontSize: 10, fontWeight: 700, color: c }}>{k}</div>
                    <div style={{ fontSize: 9, color: "#94a3b8", marginTop: 2 }}>{v}</div>
                  </div>
                ))}
                <div style={{ fontSize: 10, fontWeight: 700, color: "#94a3b8", marginTop: 16, marginBottom: 8 }}>PDF OCR PIPELINE</div>
                {["Tesseract + PyMuPDF + pdfplumber", "Extract line items & unit costs", "Vendor pricing tier lookup", "Auto-populate cost formula", "~2,200 historical invoices indexed"].map((s, i) => (
                  <div key={i} style={{ display: "flex", alignItems: "center", gap: 6, padding: "3px 0" }}>
                    <span style={{ fontSize: 10, color: "#818cf8" }}>→</span>
                    <span style={{ fontSize: 10, color: "#94a3b8" }}>{s}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Styles ─────────────────────────────────────────────────────────────────
const rootStyle = { width: "100vw", height: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: "#080b14", fontFamily: "'DM Sans', 'Segoe UI', system-ui, sans-serif", color: "#e2e8f0", padding: 16, boxSizing: "border-box" };
const containerStyle = { width: "100%", maxWidth: 720, height: "100%", maxHeight: 850, background: "linear-gradient(180deg, #0c1021, #0e1225)", border: "1px solid rgba(255,255,255,0.06)", borderRadius: "16px 0 0 16px", display: "flex", flexDirection: "column", overflow: "hidden", boxShadow: "0 25px 60px rgba(0,0,0,0.5)" };
const headerStyle = { padding: "14px 20px", borderBottom: "1px solid rgba(255,255,255,0.06)", display: "flex", justifyContent: "space-between", alignItems: "center", background: "rgba(255,255,255,0.02)" };
const logoStyle = { width: 36, height: 36, borderRadius: 10, background: "linear-gradient(135deg, #6366f1, #8b5cf6)", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 4px 12px rgba(99,102,241,0.3)" };
const messagesStyle = { flex: 1, overflowY: "auto", padding: "16px 20px", scrollbarWidth: "thin", scrollbarColor: "#1e293b transparent" };
const inputContainerStyle = { padding: "12px 16px 14px", borderTop: "1px solid rgba(255,255,255,0.06)", background: "rgba(255,255,255,0.02)" };
const inputStyle = { flex: 1, padding: "11px 16px", borderRadius: 12, border: "1px solid rgba(255,255,255,0.1)", background: "rgba(255,255,255,0.04)", color: "#e2e8f0", fontSize: 13, fontFamily: "inherit", outline: "none" };
const sendBtnStyle = { width: 42, height: 42, borderRadius: 12, border: "none", background: "linear-gradient(135deg, #6366f1, #7c3aed)", color: "white", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", flexShrink: 0 };
const sidebarStyle = { width: 300, height: "100%", maxHeight: 850, background: "linear-gradient(180deg, #0a0e1a, #0c1021)", border: "1px solid rgba(255,255,255,0.06)", borderLeft: "none", borderRadius: "0 16px 16px 0", display: "flex", flexDirection: "column", overflow: "hidden" };

const globalCSS = `
  @import url('https://fonts.googleapis.com/css2?family=DM+Sans:ital,wght@0,400;0,500;0,600;0,700;0,800&family=JetBrains+Mono:wght@400;500;600;700&display=swap');
  * { box-sizing: border-box; margin: 0; padding: 0; }
  ::-webkit-scrollbar { width: 4px; }
  ::-webkit-scrollbar-track { background: transparent; }
  ::-webkit-scrollbar-thumb { background: #1e293b; border-radius: 4px; }
  select option { background: #1e293b; color: #e2e8f0; }
  @keyframes fadeSlideIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
  @keyframes typingBounce { 0%, 60%, 100% { transform: translateY(0); opacity: 0.4; } 30% { transform: translateY(-6px); opacity: 1; } }
  @keyframes pipelineProgress { 0% { width: 0%; } 50% { width: 80%; } 100% { width: 100%; } }
  button:hover { opacity: 0.9; }
  button:disabled { opacity: 0.4; cursor: not-allowed; }
  input:focus, textarea:focus, select:focus { border-color: rgba(99,102,241,0.5) !important; box-shadow: 0 0 0 2px rgba(99,102,241,0.1); }
`;
