// Journeys page
(function () {

const { useState: useStateJP } = React;

function JourneysPage() {
  const D = window.MAX_DATA;
  const { font, fg, muted, border, cardBg, STAGES, JOURNEYS } = D;
  const [expandedJourney, setExpandedJourney] = useStateJP(1);
  const [filterStatus, setFilterStatus] = useStateJP("all");
  const [expandedCat, setExpandedCat] = useStateJP(null);
  const [dateRange, setDateRange] = useStateJP("30d");
  const dateRangeLabels = { "7d": "Last 7 days", "30d": "Last 30 days", "90d": "Last 90 days", "6m": "Last 6 months" };

  const jStyles = {
    "in-progress": { bg: "#dbeafe", text: "#1e40af", label: "In Progress" },
    "completed": { bg: "#dcfce7", text: "#166534", label: "Completed" },
    "at-risk": { bg: "#fee2e2", text: "#991b1b", label: "At Risk" },
  };
  const filteredJourneys = JOURNEYS.filter(j => filterStatus === "all" || j.status === filterStatus);

  const categories = [
    { id: "demandgen", label: "Demand Generation", color: "#2563eb", icon: "Megaphone", aiPct: 68, benchmark: 85, totalActions: 842,
      actions: [
        { name: "Ad Campaign Creation", channels: [{label:"AI Generated",pct:72,color:"#2563eb"},{label:"Manual",pct:28,color:"#9ca3af"}], volume: "34 campaigns" },
        { name: "Social Media Posting", channels: [{label:"AI Generated",pct:95,color:"#2563eb"},{label:"Manual",pct:5,color:"#9ca3af"}], volume: "142 posts" },
        { name: "Existing Customer MP Campaigns", channels: [{label:"AI Generated",pct:60,color:"#2563eb"},{label:"Manual",pct:40,color:"#9ca3af"}], volume: "8 campaigns" },
        { name: "Existing Customer — Outbound SMS", channels: [{label:"AI Agent",pct:82,color:"#2563eb"},{label:"Human CSR",pct:18,color:"#9ca3af"}], volume: "1,247 sent" },
        { name: "Existing Customer — Outbound Calls", channels: [{label:"AI Agent",pct:45,color:"#2563eb"},{label:"Human CSR",pct:55,color:"#9ca3af"}], volume: "326 calls" },
        { name: "Capacity-Based Throttling", channels: [{label:"Max Automated",pct:100,color:"#2563eb"}], volume: "3 adjustments/wk" },
      ]},
    { id: "booking", label: "Job Booking", color: "#7c3aed", icon: "Phone", aiPct: 58, benchmark: 82, totalActions: 1420,
      actions: [
        { name: "Inbound Calls — New Jobs", channels: [{label:"AI Agent",pct:52,color:"#7c3aed"},{label:"Human CSR",pct:48,color:"#9ca3af"}], volume: "486/wk" },
        { name: "Outbound Calls — New Jobs", channels: [{label:"AI Agent",pct:68,color:"#7c3aed"},{label:"Human CSR",pct:32,color:"#9ca3af"}], volume: "124/wk" },
        { name: "Inbound SMS — New Jobs", channels: [{label:"AI Agent",pct:88,color:"#7c3aed"},{label:"Human CSR",pct:12,color:"#9ca3af"}], volume: "312/wk" },
        { name: "Outbound SMS — New Jobs", channels: [{label:"AI Agent",pct:92,color:"#7c3aed"},{label:"Human CSR",pct:8,color:"#9ca3af"}], volume: "198/wk" },
        { name: "Missed Call Handling", channels: [{label:"AI Agent",pct:78,color:"#7c3aed"},{label:"Human CSR",pct:22,color:"#9ca3af"}], volume: "47/wk" },
      ]},
    { id: "dispatch", label: "Dispatch & Prep", color: "#0891b2", icon: "Truck", aiPct: 74, benchmark: 90, totalActions: 2840,
      actions: [
        { name: "Reschedule Requests — Inbound", channels: [{label:"AI Agent",pct:62,color:"#0891b2"},{label:"Human CSR",pct:38,color:"#9ca3af"}], volume: "89/wk" },
        { name: "Reschedule Requests — Outbound", channels: [{label:"AI Agent",pct:70,color:"#0891b2"},{label:"Human CSR",pct:30,color:"#9ca3af"}], volume: "56/wk" },
        { name: "Reschedule Requests — SMS", channels: [{label:"AI Agent",pct:94,color:"#0891b2"},{label:"Human CSR",pct:6,color:"#9ca3af"}], volume: "134/wk" },
        { name: "Pre Job Data Enrichment", channels: [{label:"AI Agent",pct:85,color:"#0891b2"},{label:"Human CSR",pct:15,color:"#9ca3af"}], volume: "816/wk" },
        { name: "Appointment Confirmation", channels: [{label:"AI Agent",pct:90,color:"#0891b2"},{label:"Human Dispatcher",pct:10,color:"#9ca3af"}], volume: "816/wk" },
        { name: "Assign Best Technician", channels: [{label:"AI Agent",pct:78,color:"#0891b2"},{label:"Human Dispatcher",pct:22,color:"#9ca3af"}], volume: "816/wk" },
        { name: "Job Closeout Review", channels: [{label:"AI Agent",pct:70,color:"#0891b2"},{label:"Human Dispatcher",pct:30,color:"#9ca3af"}], volume: "724/wk" },
      ]},
    { id: "diagnosis", label: "Diagnosis", color: "#059669", icon: "Wrench", aiPct: 52, benchmark: 78, totalActions: 4896,
      actions: [
        { name: "Pre Job Brief", channels: [{label:"AI Agent",pct:100,color:"#059669"}], volume: "816/wk" },
        { name: "Equipment Nameplate Scan", channels: [{label:"Technician (AI-assisted)",pct:100,color:"#059669"}], volume: "342/mo" },
        { name: "Find Replacement Parts", channels: [{label:"Technician (AI-assisted)",pct:100,color:"#059669"}], volume: "178/mo" },
        { name: "AI Diagnostics + Troubleshooting", channels: [{label:"Technician (AI-assisted)",pct:100,color:"#059669"}], volume: "95/mo" },
        { name: "Fill Out Forms", channels: [{label:"AI Autofill",pct:60,color:"#059669"},{label:"Technician",pct:40,color:"#9ca3af"}], volume: "724/wk" },
      ]},
    { id: "quoting", label: "Quoting & Financing", color: "#059669", icon: "DollarSign", aiPct: 38, benchmark: 72, totalActions: 816,
      actions: [
        { name: "Create Estimate / Proposal", channels: [{label:"AI Generated",pct:35,color:"#059669"},{label:"Technician",pct:55,color:"#9ca3af"},{label:"None",pct:10,color:"#dc2626"}], volume: "724/wk" },
        { name: "Pricing", channels: [{label:"AI Dynamic Pricing",pct:25,color:"#059669"},{label:"Technician",pct:75,color:"#9ca3af"}], volume: "724/wk" },
        { name: "Pre-Screen for Financing", channels: [{label:"Yes",pct:42,color:"#059669"},{label:"No",pct:58,color:"#dc2626"}], volume: "724 jobs" },
        { name: "Present Financing", channels: [{label:"Yes",pct:38,color:"#059669"},{label:"No",pct:62,color:"#dc2626"}], volume: "304 jobs" },
      ]},
    { id: "satisfaction", label: "Customer Satisfaction", color: "#e11d48", icon: "Heart", aiPct: 72, benchmark: 88, totalActions: 724,
      actions: [
        { name: "Review Request", channels: [{label:"AI",pct:72,color:"#e11d48"},{label:"Human",pct:18,color:"#9ca3af"},{label:"None",pct:10,color:"#dc2626"}], volume: "724/wk" },
      ]},
    { id: "memberships", label: "Memberships", color: "#e11d48", icon: "Heart", aiPct: 45, benchmark: 76, totalActions: 340,
      actions: [
        { name: "Schedule Membership Visits", channels: [{label:"AI Agent",pct:65,color:"#e11d48"},{label:"Human",pct:35,color:"#9ca3af"}], volume: "92/mo" },
        { name: "Renew Memberships", channels: [{label:"AI Agent",pct:30,color:"#e11d48"},{label:"Human",pct:70,color:"#9ca3af"}], volume: "48/mo" },
        { name: "Sell Memberships", channels: [{label:"AI Agent",pct:25,color:"#e11d48"},{label:"Human",pct:75,color:"#9ca3af"}], volume: "34/mo" },
      ]},
    { id: "backoffice", label: "Finance & Operations", color: "#d97706", icon: "Clipboard", aiPct: 42, benchmark: 68, totalActions: 1680,
      actions: [
        { name: "Gross Pay Calculation", channels: [{label:"AI",pct:55,color:"#d97706"},{label:"Human",pct:45,color:"#9ca3af"}], volume: "bi-weekly" },
        { name: "Inventory Replenishment", channels: [{label:"AI",pct:40,color:"#d97706"},{label:"Human",pct:60,color:"#9ca3af"}], volume: "34/mo" },
        { name: "Invoice Issue Detection", channels: [{label:"AI Agent",pct:50,color:"#d97706"},{label:"Human",pct:50,color:"#9ca3af"}], volume: "124/mo" },
        { name: "Unpaid Balance Collection", channels: [{label:"AI Agent",pct:30,color:"#d97706"},{label:"Human",pct:70,color:"#9ca3af"}], volume: "42/mo" },
        { name: "Payment Collection", channels: [{label:"AI Agent",pct:65,color:"#d97706"},{label:"Human",pct:35,color:"#9ca3af"}], volume: "782/mo" },
      ]},
  ];

  const totalActions = categories.reduce((s, c) => s + c.totalActions, 0);
  const totalAI = categories.reduce((s, c) => s + Math.round(c.totalActions * c.aiPct / 100), 0);
  const overallPct = Math.round((totalAI / totalActions) * 100);

  return (
    <div style={{ padding: "24px 28px", maxWidth: 1300, margin: "0 auto" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 20 }}>
        <div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: fg, fontFamily: font, margin: 0 }}>Journeys</h1>
          <p style={{ fontSize: 13, color: muted, fontFamily: font, marginTop: 2 }}>Track the AI-powered customer journey from first touch to retention</p>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 4, background: "white", border: `1px solid ${border}`, borderRadius: 8, padding: 4 }}>
          {Object.entries(dateRangeLabels).map(([key, label]) => (
            <button key={key} onClick={() => setDateRange(key)} style={{ padding: "5px 12px", borderRadius: 6, border: "none", cursor: "pointer", fontSize: 12, fontWeight: dateRange === key ? 700 : 500, fontFamily: font, background: dateRange === key ? "#2563eb" : "transparent", color: dateRange === key ? "white" : muted, transition: "all 0.15s" }}>
              {label}
            </button>
          ))}
        </div>
      </div>

      {/* Revenue Pipeline Sankey */}
      <window.RevenueSankey />

      {/* Automation Coverage */}
      <div style={{ background: cardBg, borderRadius: 10, border: `1px solid ${border}`, overflow: "hidden", marginBottom: 20 }}>
        <div style={{ padding: "16px 20px", borderBottom: `1px solid ${border}`, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ background: "#eff6ff", borderRadius: 8, padding: 8 }}><window.Icon name="Zap" size={18} color="#2563eb" /></div>
            <div>
              <h2 style={{ fontSize: 15, fontWeight: 700, color: fg, fontFamily: font, margin: 0 }}>Automation Coverage</h2>
              <p style={{ fontSize: 11, color: muted, fontFamily: font, marginTop: 2 }}>AI vs. Human across every action in your business — {dateRangeLabels[dateRange].toLowerCase()}</p>
            </div>
          </div>
          <div style={{ textAlign: "right" }}>
            <div style={{ fontSize: 28, fontWeight: 800, color: "#2563eb", fontFamily: font }}>{overallPct}%</div>
            <div style={{ fontSize: 10, color: muted, fontFamily: font }}>AI-powered overall</div>
          </div>
        </div>
        {categories.map(cat => {
          const isExpanded = expandedCat === cat.id;
          return (
            <div key={cat.id}>
              <button onClick={() => setExpandedCat(isExpanded ? null : cat.id)} style={{ width: "100%", display: "flex", alignItems: "center", gap: 16, padding: "14px 20px", background: isExpanded ? "#f8fafc" : "transparent", border: "none", borderBottom: `1px solid ${border}`, cursor: "pointer", textAlign: "left" }}>
                <div style={{ width: 32, height: 32, borderRadius: 8, background: `${cat.color}12`, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                  <window.Icon name={cat.icon} size={16} color={cat.color} strokeWidth={2} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                    <span style={{ fontSize: 14, fontWeight: 700, color: fg, fontFamily: font }}>{cat.label}</span>
                    <span style={{ fontSize: 11, color: muted, fontFamily: font }}>{cat.actions.length} action types</span>
                    <span style={{ fontSize: 11, color: muted, fontFamily: font, marginLeft: "auto" }}>
                      <strong style={{ color: cat.color }}>{Math.round(cat.totalActions * cat.aiPct / 100).toLocaleString()}</strong> actions taken by AI agents
                    </span>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <div style={{ flex: 1, height: 8, borderRadius: 4, background: "#f0f0f0", position: "relative" }}>
                      <div style={{ width: `${cat.aiPct}%`, height: "100%", borderRadius: 4, background: cat.color, opacity: 0.7, transition: "width 0.3s" }} />
                      <div style={{ position: "absolute", top: -2, left: `${cat.benchmark}%`, transform: "translateX(-50%)", width: 2, height: 12, background: "#374151", borderRadius: 1, opacity: 0.4 }} />
                    </div>
                    <span style={{ fontSize: 13, fontWeight: 800, color: cat.color, fontFamily: font, flexShrink: 0 }}>{cat.aiPct}%</span>
                    <span style={{ fontSize: 11, color: muted, fontFamily: font, flexShrink: 0 }}>AI-handled</span>
                    <span style={{ fontSize: 11, fontWeight: 700, fontFamily: font, flexShrink: 0, color: cat.aiPct >= cat.benchmark ? "#16a34a" : (cat.benchmark - cat.aiPct) <= 15 ? "#f59e0b" : "#ef4444" }}>
                      {cat.aiPct >= cat.benchmark ? `✓ At target` : `-${cat.benchmark - cat.aiPct} pts vs top ${cat.benchmark}%`}
                    </span>
                  </div>
                </div>
                <window.Icon name={isExpanded ? "ChevronUp" : "ChevronDown"} size={15} color="#9ca3af" style={{ flexShrink: 0 }} />
              </button>
              {isExpanded && (
                <div style={{ background: "#f8fafc", borderBottom: `1px solid ${border}` }}>
                  {cat.actions.map((action, ai) => (
                    <div key={ai} style={{ display: "flex", alignItems: "center", gap: 16, padding: "10px 20px 10px 68px", borderBottom: ai < cat.actions.length - 1 ? `1px solid ${border}` : "none" }}>
                      <span style={{ fontSize: 12, fontWeight: 600, color: fg, fontFamily: font, width: 240, flexShrink: 0 }}>{action.name}</span>
                      <div style={{ flex: 1, display: "flex", height: 22, borderRadius: 4, overflow: "hidden" }}>
                        {action.channels.map((ch, ci) => (
                          <div key={ci} style={{ width: `${ch.pct}%`, background: ch.color, opacity: ch.color === "#dc2626" ? 0.3 : ch.color === "#9ca3af" ? 0.25 : 0.65, display: "flex", alignItems: "center", justifyContent: "center" }}>
                            {ch.pct >= 18 && <span style={{ fontSize: 10, fontWeight: 700, color: ch.color === "#9ca3af" ? "#4b5563" : "white", fontFamily: font, whiteSpace: "nowrap" }}>{ch.label} {ch.pct}%</span>}
                          </div>
                        ))}
                      </div>
                      <div style={{ display: "flex", gap: 8, flexShrink: 0 }}>
                        {action.channels.filter(ch => ch.pct < 18).map((ch, ci) => (
                          <span key={ci} style={{ fontSize: 10, color: muted, fontFamily: font }}>{ch.label} {ch.pct}%</span>
                        ))}
                      </div>
                      <span style={{ fontSize: 11, color: muted, fontFamily: font, flexShrink: 0, minWidth: 90, textAlign: "right" }}>{action.volume}</span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Customer Journeys */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <span style={{ fontSize: 14, fontWeight: 700, color: fg, fontFamily: font }}>Customer Journeys</span>
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6, background: cardBg, border: "1px solid #d1d5db", borderRadius: 8, padding: "5px 10px", width: 200 }}><window.Icon name="Search" size={13} color="#9ca3af" /><input placeholder="Search customers..." style={{ border: "none", outline: "none", fontSize: 12, fontFamily: font, color: fg, width: "100%", background: "transparent" }} /></div>
          {["all", "in-progress", "at-risk", "completed"].map(s => (
            <button key={s} onClick={() => setFilterStatus(s)} style={{ fontSize: 11, fontWeight: filterStatus === s ? 700 : 500, color: filterStatus === s ? fg : muted, background: filterStatus === s ? cardBg : "transparent", border: filterStatus === s ? "1px solid #d1d5db" : "1px solid transparent", borderRadius: 8, padding: "5px 12px", cursor: "pointer", fontFamily: font }}>{s === "all" ? "All" : jStyles[s]?.label || s}</button>
          ))}
        </div>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
        {filteredJourneys.map(journey => {
          const isExp = expandedJourney === journey.id;
          const js = jStyles[journey.status];
          const stageData = STAGES.find(s => s.id === journey.stage);
          return (
            <div key={journey.id} style={{ background: cardBg, borderRadius: 8, border: `1px solid ${border}`, overflow: "hidden" }}>
              <button onClick={() => setExpandedJourney(isExp ? null : journey.id)} style={{ width: "100%", display: "grid", gridTemplateColumns: "1fr auto auto auto auto", alignItems: "center", gap: 14, padding: "12px 16px", background: "none", border: "none", cursor: "pointer", textAlign: "left" }}>
                <div>
                  <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                    <window.Icon name="User" size={13} color={muted} />
                    <span style={{ fontSize: 13, fontWeight: 700, color: fg, fontFamily: font }}>{journey.customer}</span>
                  </div>
                  <div style={{ fontSize: 11, color: muted, fontFamily: font, marginTop: 2, marginLeft: 19 }}>{journey.job}</div>
                </div>
                <span style={{ fontSize: 13, fontWeight: 700, color: fg, fontFamily: font }}>{journey.value}</span>
                <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
                  <window.Icon name={stageData?.icon || "Wrench"} size={12} color={stageData?.color} />
                  <span style={{ fontSize: 10, color: muted, fontFamily: font }}>{stageData?.label}</span>
                </div>
                <span style={{ fontSize: 10, fontWeight: 600, color: js.text, background: js.bg, padding: "2px 8px", borderRadius: 99, fontFamily: font }}>{js.label}</span>
                <window.Icon name={isExp ? "ChevronUp" : "ChevronDown"} size={14} color="#9ca3af" />
              </button>
              {isExp && (
                <div style={{ borderTop: `1px solid ${border}`, padding: "14px 16px 14px 36px" }}>
                  <div style={{ fontSize: 10, fontWeight: 600, color: "#9ca3af", fontFamily: font, marginBottom: 10, textTransform: "uppercase", letterSpacing: 0.5 }}>{journey.touchpoints.length} AI Touchpoints</div>
                  <div style={{ position: "relative" }}>
                    <div style={{ position: "absolute", left: 12, top: 0, bottom: 0, width: 1.5, background: border }} />
                    {journey.touchpoints.map((tp, i) => (
                      <div key={i} style={{ display: "flex", gap: 12, marginBottom: i < journey.touchpoints.length - 1 ? 14 : 0, position: "relative" }}>
                        <div style={{ width: 26, height: 26, borderRadius: 99, background: cardBg, border: "1.5px solid #d1d5db", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, zIndex: 1 }}>
                          <window.Icon name={tp.icon} size={12} color={muted} />
                        </div>
                        <div style={{ flex: 1, paddingTop: 1 }}>
                          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                            <span style={{ fontSize: 12, fontWeight: 600, color: fg, fontFamily: font }}>{tp.label}</span>
                            <span style={{ fontSize: 10, color: "#9ca3af", fontFamily: font }}>{tp.time}</span>
                          </div>
                          <div style={{ fontSize: 11, color: muted, fontFamily: font, marginTop: 1 }}>{tp.detail}</div>
                          <span style={{ fontSize: 9, color: "#2563eb", background: "#eff6ff", padding: "1px 7px", borderRadius: 4, fontFamily: font, fontWeight: 600, marginTop: 3, display: "inline-block" }}>{tp.automation}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.JourneysPage = JourneysPage;
})();
