import { useState, useEffect, useRef, useCallback } from "react";
import {
  LineChart, Line, AreaChart, Area, BarChart, Bar, XAxis, YAxis,
  CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell
} from "recharts";

/* ═══════════════════════════════════════════
   DATA
   ═══════════════════════════════════════════ */

const revenueData = [
  { month: "Sep", revenue: 18400, orders: 142, lastYear: 15200 },
  { month: "Oct", revenue: 22100, orders: 168, lastYear: 17800 },
  { month: "Nov", revenue: 31500, orders: 243, lastYear: 24600 },
  { month: "Dec", revenue: 38200, orders: 312, lastYear: 29100 },
  { month: "Jan", revenue: 24800, orders: 189, lastYear: 20400 },
  { month: "Feb", revenue: 27600, orders: 205, lastYear: 22800 },
];

const dailyRevenue = [
  { day: "Mon", amount: 4280 }, { day: "Tue", amount: 3890 },
  { day: "Wed", amount: 5120 }, { day: "Thu", amount: 4650 },
  { day: "Fri", amount: 6340 }, { day: "Sat", amount: 7210 },
  { day: "Sun", amount: 5890 },
];

const topProducts = [
  { id: "P001", name: "Premium Wireless Headphones", sku: "WH-PRO-100", sold: 284, revenue: 22720, trend: +12, price: 79.99, stock: 142, img: "\u{1F3A7}", cat: "Electronics", rating: 4.8, reviews: 126 },
  { id: "P002", name: "Organic Face Serum 30ml", sku: "BT-SRM-030", sold: 196, revenue: 15680, trend: +8, price: 79.99, stock: 88, img: "\u2728", cat: "Beauty", rating: 4.9, reviews: 94 },
  { id: "P003", name: "Bamboo Desk Organizer", sku: "HM-DSK-001", sold: 167, revenue: 8350, trend: -3, price: 49.99, stock: 210, img: "\u{1FAB5}", cat: "Home", rating: 4.5, reviews: 67 },
  { id: "P004", name: "Smart LED Strip Kit", sku: "EL-LED-500", sold: 143, revenue: 10010, trend: +22, price: 69.99, stock: 56, img: "\u{1F4A1}", cat: "Electronics", rating: 4.7, reviews: 203 },
  { id: "P005", name: "Artisan Coffee Blend 500g", sku: "FD-COF-500", sold: 312, revenue: 7800, trend: +5, price: 24.99, stock: 334, img: "\u2615", cat: "Food & Drink", rating: 4.6, reviews: 312 },
  { id: "P006", name: "Merino Wool Beanie", sku: "AP-BNE-001", sold: 98, revenue: 3430, trend: +15, price: 34.99, stock: 180, img: "\u{1F9E2}", cat: "Apparel", rating: 4.4, reviews: 45 },
  { id: "P007", name: "Ceramic Pour-Over Set", sku: "HM-POR-002", sold: 76, revenue: 4560, trend: -1, price: 59.99, stock: 64, img: "\u{1FAD6}", cat: "Home", rating: 4.8, reviews: 89 },
  { id: "P008", name: "Bluetooth Speaker Mini", sku: "EL-SPK-MIN", sold: 189, revenue: 9450, trend: +18, price: 49.99, stock: 102, img: "\u{1F50A}", cat: "Electronics", rating: 4.3, reviews: 156 },
];

const categoryData = [
  { name: "Electronics", value: 38, color: "var(--gold)" },
  { name: "Beauty", value: 24, color: "var(--blue)" },
  { name: "Home", value: 18, color: "var(--red)" },
  { name: "Food & Drink", value: 12, color: "var(--green)" },
  { name: "Apparel", value: 8, color: "#B472E8" },
];

const allOrders = [
  { id: "#WC-4821", customer: "Sarah Chen", custId: "C001", email: "sarah.chen@email.com", items: 3, products: ["Premium Wireless Headphones", "Organic Face Serum 30ml", "Artisan Coffee Blend 500g"], total: 247.50, status: "completed", time: "12 min ago", date: "Feb 28, 2026", method: "Credit Card", shipping: "Express" },
  { id: "#WC-4820", customer: "Marcus Johnson", custId: "C002", email: "m.johnson@mail.com", items: 1, products: ["Smart LED Strip Kit"], total: 89.99, status: "processing", time: "28 min ago", date: "Feb 28, 2026", method: "PayPal", shipping: "Standard" },
  { id: "#WC-4819", customer: "Yuki Tanaka", custId: "C003", email: "yuki.t@inbox.jp", items: 5, products: ["Bamboo Desk Organizer", "Ceramic Pour-Over Set", "Artisan Coffee Blend 500g", "Merino Wool Beanie", "Bluetooth Speaker Mini"], total: 412.00, status: "completed", time: "1 hr ago", date: "Feb 28, 2026", method: "Apple Pay", shipping: "Express" },
  { id: "#WC-4818", customer: "Priya Sharma", custId: "C004", email: "priya.s@company.in", items: 2, products: ["Organic Face Serum 30ml", "Merino Wool Beanie"], total: 156.80, status: "on-hold", time: "2 hr ago", date: "Feb 28, 2026", method: "Credit Card", shipping: "Standard" },
  { id: "#WC-4817", customer: "Leo Martinez", custId: "C005", email: "leo.m@correo.es", items: 1, products: ["Artisan Coffee Blend 500g"], total: 34.99, status: "completed", time: "3 hr ago", date: "Feb 28, 2026", method: "Credit Card", shipping: "Standard" },
  { id: "#WC-4816", customer: "Emma Wilson", custId: "C006", email: "emma.w@outlook.com", items: 4, products: ["Premium Wireless Headphones", "Smart LED Strip Kit", "Bluetooth Speaker Mini", "Artisan Coffee Blend 500g"], total: 289.60, status: "processing", time: "4 hr ago", date: "Feb 28, 2026", method: "Stripe", shipping: "Express" },
  { id: "#WC-4815", customer: "James Okafor", custId: "C007", email: "j.okafor@gmail.com", items: 2, products: ["Bamboo Desk Organizer", "Ceramic Pour-Over Set"], total: 109.98, status: "completed", time: "5 hr ago", date: "Feb 27, 2026", method: "PayPal", shipping: "Standard" },
  { id: "#WC-4814", customer: "Sarah Chen", custId: "C001", email: "sarah.chen@email.com", items: 1, products: ["Merino Wool Beanie"], total: 34.99, status: "completed", time: "8 hr ago", date: "Feb 27, 2026", method: "Credit Card", shipping: "Standard" },
  { id: "#WC-4813", customer: "Aisha Patel", custId: "C008", email: "aisha.p@mail.co.uk", items: 3, products: ["Organic Face Serum 30ml", "Artisan Coffee Blend 500g", "Ceramic Pour-Over Set"], total: 164.97, status: "refunded", time: "12 hr ago", date: "Feb 27, 2026", method: "Credit Card", shipping: "Express" },
  { id: "#WC-4812", customer: "Tom Andersen", custId: "C009", email: "tom.a@norsk.no", items: 2, products: ["Bluetooth Speaker Mini", "Smart LED Strip Kit"], total: 119.98, status: "completed", time: "1 day ago", date: "Feb 27, 2026", method: "Apple Pay", shipping: "Standard" },
];

const allCustomers = [
  { id: "C001", name: "Sarah Chen", email: "sarah.chen@email.com", orders: 12, spent: 1847.40, joined: "Mar 2025", lastOrder: "12 min ago", city: "San Francisco", avatar: "SC", tier: "Gold" },
  { id: "C002", name: "Marcus Johnson", email: "m.johnson@mail.com", orders: 5, spent: 634.50, joined: "Jul 2025", lastOrder: "28 min ago", city: "Chicago", avatar: "MJ", tier: "Silver" },
  { id: "C003", name: "Yuki Tanaka", email: "yuki.t@inbox.jp", orders: 18, spent: 3210.80, joined: "Jan 2025", lastOrder: "1 hr ago", city: "Tokyo", avatar: "YT", tier: "Platinum" },
  { id: "C004", name: "Priya Sharma", email: "priya.s@company.in", orders: 8, spent: 1120.00, joined: "May 2025", lastOrder: "2 hr ago", city: "Mumbai", avatar: "PS", tier: "Gold" },
  { id: "C005", name: "Leo Martinez", email: "leo.m@correo.es", orders: 3, spent: 224.97, joined: "Nov 2025", lastOrder: "3 hr ago", city: "Barcelona", avatar: "LM", tier: "Bronze" },
  { id: "C006", name: "Emma Wilson", email: "emma.w@outlook.com", orders: 15, spent: 2780.20, joined: "Feb 2025", lastOrder: "4 hr ago", city: "London", avatar: "EW", tier: "Platinum" },
  { id: "C007", name: "James Okafor", email: "j.okafor@gmail.com", orders: 6, spent: 789.50, joined: "Aug 2025", lastOrder: "5 hr ago", city: "Lagos", avatar: "JO", tier: "Silver" },
  { id: "C008", name: "Aisha Patel", email: "aisha.p@mail.co.uk", orders: 9, spent: 1456.30, joined: "Apr 2025", lastOrder: "12 hr ago", city: "Birmingham", avatar: "AP", tier: "Gold" },
  { id: "C009", name: "Tom Andersen", email: "tom.a@norsk.no", orders: 4, spent: 479.92, joined: "Sep 2025", lastOrder: "1 day ago", city: "Oslo", avatar: "TA", tier: "Silver" },
  { id: "C010", name: "Maria Rossi", email: "m.rossi@posta.it", orders: 22, spent: 4102.60, joined: "Dec 2024", lastOrder: "2 days ago", city: "Milan", avatar: "MR", tier: "Platinum" },
];

const customerGrowth = [
  { month: "Sep", new: 86, returning: 142 }, { month: "Oct", new: 104, returning: 156 },
  { month: "Nov", new: 148, returning: 198 }, { month: "Dec", new: 192, returning: 234 },
  { month: "Jan", new: 112, returning: 189 }, { month: "Feb", new: 134, returning: 205 },
];

const productSalesHistory = [
  { week: "W1", units: 42 }, { week: "W2", units: 58 }, { week: "W3", units: 51 },
  { week: "W4", units: 67 }, { week: "W5", units: 73 }, { week: "W6", units: 62 },
  { week: "W7", units: 84 }, { week: "W8", units: 71 },
];

const customerSpendHistory = [
  { month: "Sep", amount: 124 }, { month: "Oct", amount: 210 },
  { month: "Nov", amount: 189 }, { month: "Dec", amount: 342 },
  { month: "Jan", amount: 267 }, { month: "Feb", amount: 248 },
];

const CHART_COLORS = ["#E8C872", "#72B4E8", "#72E8A8", "#E87272", "#B472E8", "#E8A872", "#72E8D8", "#D872E8"];

/* ═══════════════════════════════════════════
   SHARED COMPONENTS
   ═══════════════════════════════════════════ */

const AnimatedNumber = ({ value, prefix = "", suffix = "", decimals = 0 }) => {
  const [display, setDisplay] = useState(0);
  useEffect(() => {
    const dur = 1000, start = performance.now();
    const step = (now) => { const p = Math.min((now - start) / dur, 1); setDisplay(value * (1 - Math.pow(1 - p, 3))); if (p < 1) requestAnimationFrame(step); };
    requestAnimationFrame(step);
  }, [value]);
  return <span>{prefix}{decimals > 0 ? display.toFixed(decimals) : Math.round(display).toLocaleString()}{suffix}</span>;
};

const StatusBadge = ({ status }) => {
  const c = { completed: { bg: "rgba(114,232,168,0.12)", color: "var(--green)", label: "Completed" }, processing: { bg: "rgba(114,180,232,0.12)", color: "var(--blue)", label: "Processing" }, "on-hold": { bg: "rgba(232,200,114,0.12)", color: "var(--gold)", label: "On Hold" }, refunded: { bg: "rgba(232,114,114,0.12)", color: "var(--red)", label: "Refunded" } }[status] || { bg: "rgba(255,255,255,0.06)", color: "#999", label: status };
  return <span style={{ padding: "4px 10px", borderRadius: "6px", fontSize: "11px", fontWeight: 600, background: c.bg, color: c.color, letterSpacing: "0.02em", textTransform: "uppercase" }}>{c.label}</span>;
};

const TierBadge = ({ tier }) => {
  const c = { Platinum: "#72B4E8", Gold: "#E8C872", Silver: "#A0A4B0", Bronze: "#C08060" }[tier] || "#888";
  return <span style={{ padding: "3px 9px", borderRadius: "5px", fontSize: "10px", fontWeight: 700, background: `${c}18`, color: c, letterSpacing: "0.06em", textTransform: "uppercase" }}>{tier}</span>;
};

const CustomTooltip = ({ active, payload, label }) => {
  if (!active || !payload?.length) return null;
  return (
    <div style={{ background: "var(--tooltip-bg)", border: "1px solid var(--border)", borderRadius: "10px", padding: "12px 16px", boxShadow: "0 8px 32px rgba(0,0,0,0.25)" }}>
      <p style={{ color: "var(--text-tertiary)", fontSize: "11px", margin: "0 0 6px", fontWeight: 600, letterSpacing: "0.05em", textTransform: "uppercase" }}>{label}</p>
      {payload.map((p, i) => (
        <p key={i} style={{ color: p.color, fontSize: "13px", margin: "2px 0", fontWeight: 500 }}>
          {p.name}: {typeof p.value === "number" && p.value > 100 ? `\u00A3${p.value.toLocaleString()}` : p.value}
        </p>
      ))}
    </div>
  );
};

const BackButton = ({ onClick, label = "Back" }) => (
  <button onClick={onClick} style={{ display: "inline-flex", alignItems: "center", gap: "6px", background: "none", border: "none", color: "var(--text-tertiary)", fontSize: "13px", fontWeight: 500, cursor: "pointer", padding: "6px 0", marginBottom: "16px", transition: "color 0.2s", fontFamily: "inherit" }}
    onMouseEnter={e => e.target.style.color = "var(--gold)"} onMouseLeave={e => e.target.style.color = "var(--text-tertiary)"}>
    \u2190 {label}
  </button>
);

const DetailRow = ({ label, value, accent }) => (
  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "12px 0", borderBottom: "1px solid var(--border)" }}>
    <span style={{ fontSize: "13px", color: "var(--text-tertiary)", fontWeight: 500 }}>{label}</span>
    <span style={{ fontSize: "13px", color: accent || "var(--text-primary)", fontWeight: 600 }}>{value}</span>
  </div>
);

const SectionTitle = ({ title, sub }) => (
  <div style={{ marginBottom: "20px" }}>
    <h2 style={{ fontFamily: "'Sora', sans-serif", fontSize: "24px", fontWeight: 700, color: "var(--text-primary)", letterSpacing: "-0.02em" }}>{title}</h2>
    {sub && <p style={{ fontSize: "13px", color: "var(--text-muted)", marginTop: "4px" }}>{sub}</p>}
  </div>
);

const Clickable = ({ children, onClick, style = {} }) => (
  <span onClick={onClick} style={{ cursor: "pointer", transition: "color 0.15s", ...style }}
    onMouseEnter={e => { e.currentTarget.style.color = "#E8C872"; e.currentTarget.style.textDecoration = "underline"; }}
    onMouseLeave={e => { e.currentTarget.style.color = style.color || "#fff"; e.currentTarget.style.textDecoration = "none"; }}>
    {children}
  </span>
);

/* ═══════════════════════════════════════════
   OVERVIEW PAGE
   ═══════════════════════════════════════════ */

const OverviewPage = ({ navigate }) => {
  const kpis = [
    { label: "Total Revenue", value: 162600, prefix: "\u00A3", change: +18.4, icon: "\u{1F4B0}", sub: "vs \u00A3137,300 last period" },
    { label: "Orders", value: 1259, change: +12.1, icon: "\u{1F4E6}", sub: "Avg. \u00A3129.15 per order" },
    { label: "Customers", value: 876, change: +24.6, icon: "\u{1F465}", sub: "134 new this month" },
    { label: "Conversion Rate", value: 3.8, suffix: "%", change: +0.6, icon: "\u{1F3AF}", sub: "From 11,240 visitors" },
  ];
  return (
    <>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "16px", marginBottom: "24px" }}>
        {kpis.map((kpi, i) => (
          <div key={i} className="card" style={{ padding: "24px", animation: `fadeUp 0.6s ease ${i * 0.08}s both`, cursor: i === 1 || i === 2 ? "pointer" : "default" }}
            onClick={() => { if (i === 1) navigate("orders"); if (i === 2) navigate("customers"); }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: "14px" }}>
              <span style={{ fontSize: "12px", fontWeight: 600, color: "var(--text-tertiary)", letterSpacing: "0.06em", textTransform: "uppercase" }}>{kpi.label}</span>
              <span style={{ fontSize: "20px" }}>{kpi.icon}</span>
            </div>
            <div style={{ fontSize: "32px", fontWeight: 700, color: "var(--text-primary)", letterSpacing: "-0.02em", lineHeight: 1 }}>
              <AnimatedNumber value={kpi.value} prefix={kpi.prefix || ""} suffix={kpi.suffix || ""} decimals={kpi.suffix === "%" ? 1 : 0} />
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: "8px", marginTop: "10px" }}>
              <span style={{ fontSize: "12px", fontWeight: 600, color: kpi.change > 0 ? "#72E8A8" : "#E87272" }}>{kpi.change > 0 ? "\u2191" : "\u2193"} {Math.abs(kpi.change)}%</span>
              <span style={{ fontSize: "11px", color: "var(--text-muted)" }}>{kpi.sub}</span>
            </div>
          </div>
        ))}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 380px", gap: "16px", marginBottom: "16px" }}>
        <div className="card" style={{ padding: "24px", animation: "fadeUp 0.6s ease 0.35s both" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "24px" }}>
            <div><h3 style={{ fontSize: "15px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "4px" }}>Revenue Overview</h3><p style={{ fontSize: "12px", color: "var(--text-muted)" }}>Monthly revenue vs previous year</p></div>
            <div style={{ display: "flex", gap: "16px" }}>{[["#E8C872", "This Year"], ["rgba(255,255,255,0.15)", "Last Year"]].map(([c, l]) => (<div key={l} style={{ display: "flex", alignItems: "center", gap: "6px" }}><div style={{ width: 10, height: 3, borderRadius: 2, background: c }} /><span style={{ fontSize: "11px", color: "var(--text-tertiary)" }}>{l}</span></div>))}</div>
          </div>
          <ResponsiveContainer width="100%" height={240}>
            <AreaChart data={revenueData} margin={{ top: 5, right: 10, left: -10, bottom: 0 }}>
              <defs><linearGradient id="revG" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="#E8C872" stopOpacity={0.2} /><stop offset="100%" stopColor="#E8C872" stopOpacity={0} /></linearGradient></defs>
              <CartesianGrid strokeDasharray="3 3" stroke="var(--chart-grid)" />
              <XAxis dataKey="month" tick={{ fontSize: 11, fill: "var(--chart-axis)" }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fontSize: 11, fill: "var(--chart-axis)" }} axisLine={false} tickLine={false} tickFormatter={v => `\u00A3${(v / 1000).toFixed(0)}k`} />
              <Tooltip content={<CustomTooltip />} />
              <Area type="monotone" dataKey="lastYear" stroke="var(--text-faint)" strokeWidth={2} fill="transparent" name="Last Year" dot={false} />
              <Area type="monotone" dataKey="revenue" stroke="#E8C872" strokeWidth={2.5} fill="url(#revG)" name="Revenue" dot={{ r: 3, fill: "#E8C872", strokeWidth: 0 }} activeDot={{ r: 5, fill: "#E8C872", stroke: "#0F1117", strokeWidth: 2 }} />
            </AreaChart>
          </ResponsiveContainer>
        </div>
        <div className="card" style={{ padding: "24px", animation: "fadeUp 0.6s ease 0.4s both" }}>
          <h3 style={{ fontSize: "15px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "4px" }}>Sales by Category</h3>
          <p style={{ fontSize: "12px", color: "var(--text-muted)", marginBottom: "16px" }}>Revenue distribution</p>
          <div style={{ display: "flex", justifyContent: "center" }}>
            <ResponsiveContainer width={200} height={200}><PieChart><Pie data={categoryData} cx="50%" cy="50%" innerRadius={60} outerRadius={85} paddingAngle={3} dataKey="value" stroke="none">{categoryData.map((e, i) => <Cell key={i} fill={e.color} />)}</Pie></PieChart></ResponsiveContainer>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: "10px", marginTop: "8px" }}>
            {categoryData.map((cat, i) => (<div key={i} style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}><div style={{ display: "flex", alignItems: "center", gap: "10px" }}><div style={{ width: 8, height: 8, borderRadius: "3px", background: cat.color }} /><Clickable onClick={() => navigate("products")} style={{ fontSize: "13px", color: "var(--text-secondary)" }}>{cat.name}</Clickable></div><span style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-secondary)" }}>{cat.value}%</span></div>))}
          </div>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px", marginBottom: "16px" }}>
        <div className="card" style={{ padding: "24px", animation: "fadeUp 0.6s ease 0.45s both" }}>
          <h3 style={{ fontSize: "15px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "4px" }}>This Week's Revenue</h3>
          <p style={{ fontSize: "12px", color: "var(--text-muted)", marginBottom: "24px" }}>Daily breakdown \u2014 \u00A337,380 total</p>
          <ResponsiveContainer width="100%" height={200}>
            <BarChart data={dailyRevenue} margin={{ top: 0, right: 0, left: -10, bottom: 0 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="var(--chart-grid)" vertical={false} />
              <XAxis dataKey="day" tick={{ fontSize: 11, fill: "var(--chart-axis)" }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fontSize: 11, fill: "var(--chart-axis)" }} axisLine={false} tickLine={false} tickFormatter={v => `\u00A3${(v / 1000).toFixed(0)}k`} />
              <Tooltip content={<CustomTooltip />} />
              <Bar dataKey="amount" name="Revenue" radius={[6, 6, 0, 0]} maxBarSize={40}>{dailyRevenue.map((_, i) => <Cell key={i} fill={i === 5 ? "#E8C872" : "rgba(114,180,232,0.5)"} />)}</Bar>
            </BarChart>
          </ResponsiveContainer>
        </div>
        <div className="card" style={{ padding: "24px", animation: "fadeUp 0.6s ease 0.5s both" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "24px" }}>
            <div><h3 style={{ fontSize: "15px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "4px" }}>Customer Growth</h3><p style={{ fontSize: "12px", color: "var(--text-muted)" }}>New vs returning</p></div>
            <div style={{ display: "flex", gap: "16px" }}>{[["#72E8A8", "New"], ["#B472E8", "Returning"]].map(([c, l]) => (<div key={l} style={{ display: "flex", alignItems: "center", gap: "6px" }}><div style={{ width: 10, height: 3, borderRadius: 2, background: c }} /><span style={{ fontSize: "11px", color: "var(--text-tertiary)" }}>{l}</span></div>))}</div>
          </div>
          <ResponsiveContainer width="100%" height={200}>
            <AreaChart data={customerGrowth} margin={{ top: 5, right: 10, left: -10, bottom: 0 }}>
              <defs><linearGradient id="newG" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="#72E8A8" stopOpacity={0.15} /><stop offset="100%" stopColor="#72E8A8" stopOpacity={0} /></linearGradient><linearGradient id="retG" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="#B472E8" stopOpacity={0.15} /><stop offset="100%" stopColor="#B472E8" stopOpacity={0} /></linearGradient></defs>
              <CartesianGrid strokeDasharray="3 3" stroke="var(--chart-grid)" />
              <XAxis dataKey="month" tick={{ fontSize: 11, fill: "var(--chart-axis)" }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fontSize: 11, fill: "var(--chart-axis)" }} axisLine={false} tickLine={false} />
              <Tooltip content={<CustomTooltip />} />
              <Area type="monotone" dataKey="returning" stroke="#B472E8" strokeWidth={2} fill="url(#retG)" name="Returning" dot={false} />
              <Area type="monotone" dataKey="new" stroke="#72E8A8" strokeWidth={2} fill="url(#newG)" name="New" dot={false} />
            </AreaChart>
          </ResponsiveContainer>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px" }}>
        <div className="card" style={{ padding: "24px", animation: "fadeUp 0.6s ease 0.55s both" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "20px" }}><div><h3 style={{ fontSize: "15px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "4px" }}>Recent Orders</h3><p style={{ fontSize: "12px", color: "var(--text-muted)" }}>Latest transactions</p></div><button onClick={() => navigate("orders")} className="link-btn">View All \u2192</button></div>
          <div style={{ display: "grid", gridTemplateColumns: "80px 1fr 80px 90px 80px", padding: "0 0 10px", borderBottom: "1px solid var(--border)", fontSize: "10px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.08em", textTransform: "uppercase" }}><span>Order</span><span>Customer</span><span>Total</span><span>Status</span><span>Time</span></div>
          {allOrders.slice(0, 5).map((o, i) => (<div key={i} className="table-row" style={{ display: "grid", gridTemplateColumns: "80px 1fr 80px 90px 80px", padding: "12px 0", alignItems: "center", borderBottom: i < 4 ? "1px solid rgba(255,255,255,0.03)" : "none" }}><Clickable onClick={() => navigate("order-detail", o.id)} style={{ fontSize: "12px", fontWeight: 600, color: "var(--gold)" }}>{o.id}</Clickable><Clickable onClick={() => navigate("customer-detail", o.custId)} style={{ fontSize: "13px", color: "var(--text-secondary)" }}>{o.customer}</Clickable><span style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)" }}>{`\u00A3${o.total.toFixed(2)}`}</span><StatusBadge status={o.status} /><span style={{ fontSize: "11px", color: "var(--text-muted)" }}>{o.time}</span></div>))}
        </div>
        <div className="card" style={{ padding: "24px", animation: "fadeUp 0.6s ease 0.6s both" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "20px" }}><div><h3 style={{ fontSize: "15px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "4px" }}>Top Products</h3><p style={{ fontSize: "12px", color: "var(--text-muted)" }}>Best performers</p></div><button onClick={() => navigate("products")} className="link-btn">View All \u2192</button></div>
          <div style={{ display: "grid", gridTemplateColumns: "28px 1fr 60px 85px 60px", padding: "0 0 10px", borderBottom: "1px solid var(--border)", fontSize: "10px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.08em", textTransform: "uppercase" }}><span>#</span><span>Product</span><span>Sold</span><span>Revenue</span><span>Trend</span></div>
          {topProducts.slice(0, 5).map((p, i) => (<div key={i} className="table-row" style={{ display: "grid", gridTemplateColumns: "28px 1fr 60px 85px 60px", padding: "14px 0", alignItems: "center", borderBottom: i < 4 ? "1px solid rgba(255,255,255,0.03)" : "none" }}><span style={{ fontSize: "12px", fontWeight: 700, color: i === 0 ? "#E8C872" : i === 1 ? "rgba(255,255,255,0.5)" : i === 2 ? "#C07040" : "rgba(255,255,255,0.2)" }}>{i + 1}</span><Clickable onClick={() => navigate("product-detail", p.id)} style={{ fontSize: "13px", color: "var(--text-secondary)", fontWeight: 500 }}>{p.name}</Clickable><span style={{ fontSize: "13px", color: "var(--text-tertiary)" }}>{p.sold}</span><span style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)" }}>{`\u00A3${p.revenue.toLocaleString()}`}</span><span style={{ fontSize: "12px", fontWeight: 600, color: p.trend > 0 ? "#72E8A8" : "#E87272" }}>{p.trend > 0 ? "\u2191" : "\u2193"}{Math.abs(p.trend)}%</span></div>))}
        </div>
      </div>
    </>
  );
};

/* ═══════════════════════════════════════════
   ORDERS / PRODUCTS / CUSTOMERS PAGES
   (Condensed from previous version)
   ═══════════════════════════════════════════ */

const OrdersPage = ({ navigate }) => {
  const [filter, setFilter] = useState("all");
  const filtered = filter === "all" ? allOrders : allOrders.filter(o => o.status === filter);
  const counts = { all: allOrders.length, completed: allOrders.filter(o => o.status === "completed").length, processing: allOrders.filter(o => o.status === "processing").length, "on-hold": allOrders.filter(o => o.status === "on-hold").length, refunded: allOrders.filter(o => o.status === "refunded").length };
  return (
    <div style={{ animation: "fadeUp 0.5s ease" }}>
      <SectionTitle title="Orders" sub={`${allOrders.length} total orders \u2014 \u00A3${allOrders.reduce((s, o) => s + o.total, 0).toLocaleString(undefined, { minimumFractionDigits: 2 })} revenue`} />
      <div style={{ display: "flex", gap: "6px", marginBottom: "20px", flexWrap: "wrap" }}>
        {["all", "completed", "processing", "on-hold", "refunded"].map(f => (<button key={f} onClick={() => setFilter(f)} className={`date-btn ${filter === f ? "active" : ""}`} style={{ textTransform: "capitalize" }}>{f === "all" ? "All" : f.replace("-", " ")} ({counts[f] || 0})</button>))}
      </div>
      <div className="card" style={{ padding: "0", overflow: "hidden" }}>
        <div style={{ display: "grid", gridTemplateColumns: "90px 1fr 140px 80px 100px 100px 90px", padding: "14px 24px", borderBottom: "1px solid var(--border)", fontSize: "10px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.08em", textTransform: "uppercase" }}><span>Order</span><span>Customer</span><span>Email</span><span>Items</span><span>Total</span><span>Status</span><span>Date</span></div>
        {filtered.map((o, i) => (<div key={i} className="table-row" style={{ display: "grid", gridTemplateColumns: "90px 1fr 140px 80px 100px 100px 90px", padding: "14px 24px", alignItems: "center", borderBottom: "1px solid var(--border)" }}><Clickable onClick={() => navigate("order-detail", o.id)} style={{ fontSize: "13px", fontWeight: 600, color: "var(--gold)" }}>{o.id}</Clickable><Clickable onClick={() => navigate("customer-detail", o.custId)} style={{ fontSize: "13px", color: "var(--text-secondary)" }}>{o.customer}</Clickable><span style={{ fontSize: "12px", color: "var(--text-muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{o.email}</span><span style={{ fontSize: "13px", color: "var(--text-tertiary)", textAlign: "center" }}>{o.items}</span><span style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)" }}>{`\u00A3${o.total.toFixed(2)}`}</span><StatusBadge status={o.status} /><span style={{ fontSize: "11px", color: "var(--text-muted)" }}>{o.date}</span></div>))}
      </div>
    </div>
  );
};

const OrderDetailPage = ({ navigate, detailId }) => {
  const order = allOrders.find(o => o.id === detailId);
  if (!order) return <div style={{ color: "var(--text-primary)" }}>Order not found</div>;
  return (
    <div style={{ animation: "fadeUp 0.5s ease" }}>
      <BackButton onClick={() => navigate("orders")} label="All Orders" />
      <div style={{ display: "flex", alignItems: "center", gap: "16px", marginBottom: "28px" }}><h2 style={{ fontFamily: "'Sora', sans-serif", fontSize: "28px", fontWeight: 700, color: "var(--text-primary)" }}>{order.id}</h2><StatusBadge status={order.status} /></div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "16px" }}>
        <div className="card" style={{ padding: "24px" }}><h4 style={{ fontSize: "12px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: "16px" }}>Order Details</h4><DetailRow label="Date" value={order.date} /><DetailRow label="Payment" value={order.method} /><DetailRow label="Shipping" value={order.shipping} /><DetailRow label="Total" value={`\u00A3${order.total.toFixed(2)}`} accent="#E8C872" /></div>
        <div className="card" style={{ padding: "24px" }}><h4 style={{ fontSize: "12px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: "16px" }}>Customer</h4><div style={{ display: "flex", alignItems: "center", gap: "12px", marginBottom: "16px" }}><div style={{ width: 44, height: 44, borderRadius: "12px", background: "linear-gradient(135deg, rgba(232,200,114,0.2), rgba(114,180,232,0.2))", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "14px", fontWeight: 700, color: "var(--gold)" }}>{order.customer.split(" ").map(n => n[0]).join("")}</div><div><Clickable onClick={() => navigate("customer-detail", order.custId)} style={{ fontSize: "15px", fontWeight: 600, color: "var(--text-primary)" }}>{order.customer}</Clickable><p style={{ fontSize: "12px", color: "var(--text-muted)", marginTop: "2px" }}>{order.email}</p></div></div></div>
        <div className="card" style={{ padding: "24px" }}><h4 style={{ fontSize: "12px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: "16px" }}>Items ({order.items})</h4>{order.products.map((pName, i) => { const prod = topProducts.find(tp => tp.name === pName); return (<div key={i} style={{ display: "flex", alignItems: "center", gap: "10px", padding: "10px 0", borderBottom: i < order.products.length - 1 ? "1px solid rgba(255,255,255,0.04)" : "none" }}><span style={{ fontSize: "18px" }}>{prod?.img || "\u{1F4E6}"}</span><Clickable onClick={() => prod && navigate("product-detail", prod.id)} style={{ fontSize: "13px", color: "var(--text-secondary)", fontWeight: 500 }}>{pName}</Clickable></div>); })}</div>
      </div>
    </div>
  );
};

const ProductsPage = ({ navigate }) => (
  <div style={{ animation: "fadeUp 0.5s ease" }}>
    <SectionTitle title="Products" sub={`${topProducts.length} products \u2014 \u00A3${topProducts.reduce((s, p) => s + p.revenue, 0).toLocaleString()} total revenue`} />
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "16px" }}>
      {topProducts.map((p, i) => (<div key={i} className="card" style={{ padding: "24px", cursor: "pointer", animation: `fadeUp 0.5s ease ${i * 0.06}s both` }} onClick={() => navigate("product-detail", p.id)}><div style={{ fontSize: "36px", marginBottom: "14px" }}>{p.img}</div><h4 style={{ fontSize: "14px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "4px", lineHeight: 1.3 }}>{p.name}</h4><p style={{ fontSize: "11px", color: "var(--text-muted)", marginBottom: "14px" }}>{p.cat} \u00B7 {p.sku}</p><div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}><span style={{ fontSize: "20px", fontWeight: 700, color: "var(--gold)" }}>{`\u00A3${p.price}`}</span><span style={{ fontSize: "12px", fontWeight: 600, color: p.trend > 0 ? "#72E8A8" : "#E87272" }}>{p.trend > 0 ? "\u2191" : "\u2193"}{Math.abs(p.trend)}%</span></div><div style={{ display: "flex", justifyContent: "space-between", marginTop: "12px", paddingTop: "12px", borderTop: "1px solid rgba(255,255,255,0.05)" }}><div><p style={{ fontSize: "10px", color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Sold</p><p style={{ fontSize: "14px", fontWeight: 600, color: "var(--text-primary)" }}>{p.sold}</p></div><div><p style={{ fontSize: "10px", color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Stock</p><p style={{ fontSize: "14px", fontWeight: 600, color: p.stock < 70 ? "#E87272" : "#fff" }}>{p.stock}</p></div><div><p style={{ fontSize: "10px", color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Rating</p><p style={{ fontSize: "14px", fontWeight: 600, color: "var(--text-primary)" }}>\u2B50 {p.rating}</p></div></div></div>))}
    </div>
  </div>
);

const ProductDetailPage = ({ navigate, detailId }) => {
  const product = topProducts.find(p => p.id === detailId);
  if (!product) return <div style={{ color: "var(--text-primary)" }}>Product not found</div>;
  const relatedOrders = allOrders.filter(o => o.products.includes(product.name));
  return (
    <div style={{ animation: "fadeUp 0.5s ease" }}>
      <BackButton onClick={() => navigate("products")} label="All Products" />
      <div style={{ display: "flex", alignItems: "center", gap: "20px", marginBottom: "28px" }}><div style={{ width: 64, height: 64, borderRadius: "16px", background: "linear-gradient(135deg, rgba(232,200,114,0.15), rgba(114,180,232,0.1))", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "32px" }}>{product.img}</div><div><h2 style={{ fontFamily: "'Sora', sans-serif", fontSize: "26px", fontWeight: 700, color: "var(--text-primary)" }}>{product.name}</h2><p style={{ fontSize: "13px", color: "var(--text-muted)", marginTop: "4px" }}>{product.cat} \u00B7 SKU: {product.sku}</p></div></div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "16px", marginBottom: "16px" }}>
        {[{ label: "Price", value: `\u00A3${product.price}`, icon: "\u{1F4B7}" }, { label: "Units Sold", value: product.sold, icon: "\u{1F4CA}" }, { label: "Revenue", value: `\u00A3${product.revenue.toLocaleString()}`, icon: "\u{1F4B0}" }, { label: "In Stock", value: product.stock, icon: "\u{1F4E6}" }].map((s, i) => (<div key={i} className="card" style={{ padding: "20px" }}><div style={{ display: "flex", justifyContent: "space-between", marginBottom: "8px" }}><span style={{ fontSize: "11px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.06em", textTransform: "uppercase" }}>{s.label}</span><span style={{ fontSize: "16px" }}>{s.icon}</span></div><span style={{ fontSize: "24px", fontWeight: 700, color: "var(--text-primary)" }}>{s.value}</span></div>))}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px", marginBottom: "16px" }}>
        <div className="card" style={{ padding: "24px" }}>
          <h4 style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "20px" }}>Sales Trend (8 Weeks)</h4>
          <ResponsiveContainer width="100%" height={200}><AreaChart data={productSalesHistory} margin={{ top: 5, right: 10, left: -10, bottom: 0 }}><defs><linearGradient id="pSG" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="#E8C872" stopOpacity={0.2} /><stop offset="100%" stopColor="#E8C872" stopOpacity={0} /></linearGradient></defs><CartesianGrid strokeDasharray="3 3" stroke="var(--chart-grid)" /><XAxis dataKey="week" tick={{ fontSize: 11, fill: "var(--chart-axis)" }} axisLine={false} tickLine={false} /><YAxis tick={{ fontSize: 11, fill: "var(--chart-axis)" }} axisLine={false} tickLine={false} /><Tooltip content={<CustomTooltip />} /><Area type="monotone" dataKey="units" stroke="#E8C872" strokeWidth={2} fill="url(#pSG)" name="Units Sold" dot={{ r: 3, fill: "#E8C872", strokeWidth: 0 }} /></AreaChart></ResponsiveContainer>
        </div>
        <div className="card" style={{ padding: "24px" }}><h4 style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "16px" }}>Product Details</h4><DetailRow label="Category" value={product.cat} /><DetailRow label="SKU" value={product.sku} /><DetailRow label="Rating" value={`\u2B50 ${product.rating} (${product.reviews} reviews)`} /><DetailRow label="Trend" value={`${product.trend > 0 ? "\u2191" : "\u2193"} ${Math.abs(product.trend)}%`} accent={product.trend > 0 ? "#72E8A8" : "#E87272"} /><DetailRow label="Stock" value={product.stock < 70 ? "Low Stock" : "In Stock"} accent={product.stock < 70 ? "#E87272" : "#72E8A8"} /></div>
      </div>
      {relatedOrders.length > 0 && <div className="card" style={{ padding: "24px" }}><h4 style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "16px" }}>Related Orders ({relatedOrders.length})</h4>{relatedOrders.map((o, i) => (<div key={i} className="table-row" style={{ display: "flex", alignItems: "center", gap: "20px", padding: "10px 0", borderBottom: "1px solid var(--border)" }}><Clickable onClick={() => navigate("order-detail", o.id)} style={{ fontSize: "13px", fontWeight: 600, color: "var(--gold)", width: 80 }}>{o.id}</Clickable><Clickable onClick={() => navigate("customer-detail", o.custId)} style={{ fontSize: "13px", color: "var(--text-secondary)", flex: 1 }}>{o.customer}</Clickable><span style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)", width: 80 }}>{`\u00A3${o.total.toFixed(2)}`}</span><StatusBadge status={o.status} /></div>))}</div>}
    </div>
  );
};

const CustomersPage = ({ navigate }) => {
  const [sort, setSort] = useState("spent");
  const sorted = [...allCustomers].sort((a, b) => sort === "spent" ? b.spent - a.spent : sort === "orders" ? b.orders - a.orders : a.name.localeCompare(b.name));
  return (
    <div style={{ animation: "fadeUp 0.5s ease" }}>
      <SectionTitle title="Customers" sub={`${allCustomers.length} customers \u2014 \u00A3${allCustomers.reduce((s, c) => s + c.spent, 0).toLocaleString(undefined, { minimumFractionDigits: 2 })} lifetime value`} />
      <div style={{ display: "flex", gap: "6px", marginBottom: "20px" }}>{[["spent", "Top Spenders"], ["orders", "Most Orders"], ["name", "Alphabetical"]].map(([v, l]) => (<button key={v} onClick={() => setSort(v)} className={`date-btn ${sort === v ? "active" : ""}`}>{l}</button>))}</div>
      <div className="card" style={{ padding: "0", overflow: "hidden" }}>
        {sorted.map((c, i) => (<div key={i} className="table-row" onClick={() => navigate("customer-detail", c.id)} style={{ display: "grid", gridTemplateColumns: "50px 1fr 160px 80px 100px 80px 100px", padding: "14px 24px", alignItems: "center", borderBottom: "1px solid var(--border)", cursor: "pointer" }}><div style={{ width: 36, height: 36, borderRadius: "10px", background: `linear-gradient(135deg, ${c.tier === "Platinum" ? "rgba(114,180,232,0.2)" : c.tier === "Gold" ? "rgba(232,200,114,0.2)" : "rgba(255,255,255,0.06)"}, rgba(255,255,255,0.03))`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: "12px", fontWeight: 700, color: c.tier === "Platinum" ? "#72B4E8" : c.tier === "Gold" ? "#E8C872" : "rgba(255,255,255,0.5)" }}>{c.avatar}</div><div><span style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)" }}>{c.name}</span><p style={{ fontSize: "11px", color: "var(--text-muted)", marginTop: "1px" }}>{c.city}</p></div><span style={{ fontSize: "12px", color: "var(--text-muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.email}</span><span style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)", textAlign: "center" }}>{c.orders}</span><span style={{ fontSize: "13px", fontWeight: 600, color: "var(--gold)" }}>{`\u00A3${c.spent.toLocaleString(undefined, { minimumFractionDigits: 2 })}`}</span><TierBadge tier={c.tier} /><span style={{ fontSize: "11px", color: "var(--text-muted)" }}>{c.lastOrder}</span></div>))}
      </div>
    </div>
  );
};

const CustomerDetailPage = ({ navigate, detailId }) => {
  const customer = allCustomers.find(c => c.id === detailId);
  if (!customer) return <div style={{ color: "var(--text-primary)" }}>Customer not found</div>;
  const custOrders = allOrders.filter(o => o.custId === detailId);
  return (
    <div style={{ animation: "fadeUp 0.5s ease" }}>
      <BackButton onClick={() => navigate("customers")} label="All Customers" />
      <div style={{ display: "flex", alignItems: "center", gap: "20px", marginBottom: "28px" }}><div style={{ width: 64, height: 64, borderRadius: "16px", background: `linear-gradient(135deg, ${customer.tier === "Platinum" ? "rgba(114,180,232,0.25)" : "rgba(232,200,114,0.2)"}, rgba(255,255,255,0.03))`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: "22px", fontWeight: 700, color: customer.tier === "Platinum" ? "#72B4E8" : "#E8C872" }}>{customer.avatar}</div><div><div style={{ display: "flex", alignItems: "center", gap: "12px" }}><h2 style={{ fontFamily: "'Sora', sans-serif", fontSize: "26px", fontWeight: 700, color: "var(--text-primary)" }}>{customer.name}</h2><TierBadge tier={customer.tier} /></div><p style={{ fontSize: "13px", color: "var(--text-muted)", marginTop: "4px" }}>{customer.email} \u00B7 {customer.city}</p></div></div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "16px", marginBottom: "16px" }}>
        {[{ label: "Total Spent", value: `\u00A3${customer.spent.toLocaleString(undefined, { minimumFractionDigits: 2 })}`, icon: "\u{1F4B0}" }, { label: "Orders", value: customer.orders, icon: "\u{1F4E6}" }, { label: "Avg. Order", value: `\u00A3${(customer.spent / customer.orders).toFixed(2)}`, icon: "\u{1F4CA}" }, { label: "Member Since", value: customer.joined, icon: "\u{1F4C5}" }].map((s, i) => (<div key={i} className="card" style={{ padding: "20px" }}><div style={{ display: "flex", justifyContent: "space-between", marginBottom: "8px" }}><span style={{ fontSize: "11px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.06em", textTransform: "uppercase" }}>{s.label}</span><span style={{ fontSize: "16px" }}>{s.icon}</span></div><span style={{ fontSize: "24px", fontWeight: 700, color: "var(--text-primary)" }}>{s.value}</span></div>))}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px", marginBottom: "16px" }}>
        <div className="card" style={{ padding: "24px" }}><h4 style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "20px" }}>Spending History</h4><ResponsiveContainer width="100%" height={200}><BarChart data={customerSpendHistory} margin={{ top: 0, right: 0, left: -10, bottom: 0 }}><CartesianGrid strokeDasharray="3 3" stroke="var(--chart-grid)" vertical={false} /><XAxis dataKey="month" tick={{ fontSize: 11, fill: "var(--chart-axis)" }} axisLine={false} tickLine={false} /><YAxis tick={{ fontSize: 11, fill: "var(--chart-axis)" }} axisLine={false} tickLine={false} tickFormatter={v => `\u00A3${v}`} /><Tooltip content={<CustomTooltip />} /><Bar dataKey="amount" name="Spent" radius={[6, 6, 0, 0]} fill="rgba(232,200,114,0.5)" maxBarSize={36} /></BarChart></ResponsiveContainer></div>
        <div className="card" style={{ padding: "24px" }}><h4 style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "16px" }}>Profile</h4><DetailRow label="ID" value={customer.id} /><DetailRow label="Email" value={customer.email} /><DetailRow label="Location" value={customer.city} /><DetailRow label="Tier" value={customer.tier} accent={customer.tier === "Platinum" ? "#72B4E8" : customer.tier === "Gold" ? "#E8C872" : "#A0A4B0"} /><DetailRow label="Last Order" value={customer.lastOrder} /></div>
      </div>
      {custOrders.length > 0 && <div className="card" style={{ padding: "24px" }}><h4 style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "16px" }}>Order History ({custOrders.length})</h4>{custOrders.map((o, i) => (<div key={i} className="table-row" style={{ display: "flex", alignItems: "center", gap: "20px", padding: "10px 0", borderBottom: "1px solid var(--border)" }}><Clickable onClick={() => navigate("order-detail", o.id)} style={{ fontSize: "13px", fontWeight: 600, color: "var(--gold)", width: 80 }}>{o.id}</Clickable><span style={{ fontSize: "12px", color: "var(--text-tertiary)", flex: 1 }}>{o.products.join(", ")}</span><span style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)", width: 80 }}>{`\u00A3${o.total.toFixed(2)}`}</span><StatusBadge status={o.status} /></div>))}</div>}
    </div>
  );
};

/* ═══════════════════════════════════════════
   CUSTOM DASHBOARD BUILDER
   ═══════════════════════════════════════════ */

const WIDGET_TYPES = [
  { id: "line_chart", label: "Line Chart", icon: "\u{1F4C8}" },
  { id: "bar_chart", label: "Bar Chart", icon: "\u{1F4CA}" },
  { id: "area_chart", label: "Area Chart", icon: "\u{1F30A}" },
  { id: "donut_chart", label: "Donut Chart", icon: "\u{1F369}" },
  { id: "kpi_card", label: "KPI Card", icon: "\u{1F3AF}" },
  { id: "table", label: "Table", icon: "\u{1F4CB}" },
  { id: "comparison", label: "Comparison", icon: "\u2696\uFE0F" },
];

const PRESET_TEMPLATES = [
  {
    name: "Sales Overview", icon: "\u{1F4B0}", desc: "Revenue, orders by status, top products, daily revenue",
    widgets: [
      { type: "area_chart", prompt: "Monthly revenue for the last 6 months", size: "large" },
      { type: "donut_chart", prompt: "Orders by status this month", size: "medium" },
      { type: "bar_chart", prompt: "Top 5 products by revenue", size: "medium" },
      { type: "bar_chart", prompt: "Daily revenue this week", size: "large" },
    ]
  },
  {
    name: "Customer Insights", icon: "\u{1F465}", desc: "Growth trends, top spenders, tier breakdown",
    widgets: [
      { type: "area_chart", prompt: "New vs returning customers per month", size: "large" },
      { type: "table", prompt: "Top 5 customers by total spend", size: "medium" },
      { type: "donut_chart", prompt: "Customers by tier", size: "medium" },
      { type: "kpi_card", prompt: "Total customers this month", size: "small" },
      { type: "kpi_card", prompt: "Average customer lifetime value", size: "small" },
    ]
  },
  {
    name: "Product Performance", icon: "\u{1F4E6}", desc: "Sales trends, low stock alerts, category breakdown",
    widgets: [
      { type: "bar_chart", prompt: "Top 8 products by units sold", size: "large" },
      { type: "table", prompt: "Products with stock below 100", size: "medium" },
      { type: "donut_chart", prompt: "Revenue by product category", size: "medium" },
      { type: "line_chart", prompt: "Weekly product sales trend", size: "large" },
    ]
  },
  {
    name: "Quick KPIs", icon: "\u26A1", desc: "Six key metrics at a glance",
    widgets: [
      { type: "kpi_card", prompt: "Total revenue this month", size: "small" },
      { type: "kpi_card", prompt: "Total orders this month", size: "small" },
      { type: "kpi_card", prompt: "Total customers", size: "small" },
      { type: "kpi_card", prompt: "Average order value", size: "small" },
      { type: "kpi_card", prompt: "Refund rate this month", size: "small" },
      { type: "kpi_card", prompt: "Conversion rate", size: "small" },
    ]
  },
];

// Simulates AI-generated widget data based on prompt keywords
const generateWidgetData = (prompt, type) => {
  const p = prompt.toLowerCase();
  if (type === "kpi_card") {
    if (p.includes("revenue")) return { title: "Total Revenue", value: "\u00A327,600", change: "+18.4%", positive: true };
    if (p.includes("order") && p.includes("value")) return { title: "Avg. Order Value", value: "\u00A3129.15", change: "+4.2%", positive: true };
    if (p.includes("order")) return { title: "Total Orders", value: "205", change: "+12.1%", positive: true };
    if (p.includes("customer") && p.includes("lifetime")) return { title: "Avg. Lifetime Value", value: "\u00A31,664", change: "+8.7%", positive: true };
    if (p.includes("customer")) return { title: "Total Customers", value: "876", change: "+24.6%", positive: true };
    if (p.includes("refund")) return { title: "Refund Rate", value: "2.3%", change: "-0.4%", positive: true };
    if (p.includes("conversion")) return { title: "Conversion Rate", value: "3.8%", change: "+0.6%", positive: true };
    return { title: prompt, value: "1,247", change: "+5.2%", positive: true };
  }
  if (type === "table") {
    if (p.includes("customer")) return { title: p.includes("top") ? "Top Customers by Spend" : "Customers", headers: ["Name", "Spent", "Orders"], rows: allCustomers.slice(0, 5).map(c => [c.name, `\u00A3${c.spent.toLocaleString()}`, c.orders]) };
    if (p.includes("stock") || p.includes("low")) return { title: "Low Stock Products", headers: ["Product", "Stock", "Category"], rows: topProducts.filter(pr => pr.stock < 120).map(pr => [pr.name, pr.stock, pr.cat]) };
    return { title: "Top Products", headers: ["Product", "Revenue", "Sold"], rows: topProducts.slice(0, 5).map(pr => [pr.name, `\u00A3${pr.revenue.toLocaleString()}`, pr.sold]) };
  }
  if (type === "donut_chart") {
    if (p.includes("status")) return { title: "Orders by Status", data: [{ name: "Completed", value: 65 }, { name: "Processing", value: 20 }, { name: "On Hold", value: 10 }, { name: "Refunded", value: 5 }] };
    if (p.includes("tier")) return { title: "Customers by Tier", data: [{ name: "Platinum", value: 15 }, { name: "Gold", value: 30 }, { name: "Silver", value: 35 }, { name: "Bronze", value: 20 }] };
    if (p.includes("category") || p.includes("categor")) return { title: "Revenue by Category", data: categoryData.map(c => ({ name: c.name, value: c.value })) };
    return { title: prompt, data: [{ name: "Segment A", value: 40 }, { name: "Segment B", value: 35 }, { name: "Segment C", value: 25 }] };
  }
  // Line, area, bar charts
  if (p.includes("daily") || p.includes("week")) return { title: p.includes("revenue") ? "Daily Revenue" : "Daily Activity", data: dailyRevenue.map(d => ({ label: d.day, value: d.amount })), yFormat: "currency" };
  if (p.includes("new") && p.includes("return")) return { title: "New vs Returning Customers", data: customerGrowth.map(d => ({ label: d.month, value: d.new, value2: d.returning })), series: ["New", "Returning"], yFormat: "number" };
  if (p.includes("product") && (p.includes("top") || p.includes("unit"))) return { title: p.includes("revenue") ? "Top Products by Revenue" : "Top Products by Units Sold", data: topProducts.slice(0, p.includes("8") ? 8 : 5).map(pr => ({ label: pr.name.split(" ").slice(0, 2).join(" "), value: p.includes("revenue") ? pr.revenue : pr.sold })), yFormat: p.includes("revenue") ? "currency" : "number" };
  if (p.includes("weekly") || p.includes("trend")) return { title: "Weekly Sales Trend", data: productSalesHistory.map(d => ({ label: d.week, value: d.units })), yFormat: "number" };
  return { title: prompt, data: revenueData.map(d => ({ label: d.month, value: d.revenue })), yFormat: "currency" };
};

const WidgetRenderer = ({ widget }) => {
  const data = widget.data;
  if (!data) return null;

  const chartMargin = { top: 5, right: 10, left: -10, bottom: 0 };
  const axisProps = { tick: { fontSize: 11, fill: "var(--chart-axis)" }, axisLine: false, tickLine: false };
  const yFmt = data.yFormat === "currency" ? v => `\u00A3${(v >= 1000 ? (v / 1000).toFixed(0) + "k" : v)}` : undefined;

  if (widget.type === "kpi_card") {
    return (
      <div style={{ display: "flex", flexDirection: "column", justifyContent: "center", height: "100%", padding: "8px 0" }}>
        <span style={{ fontSize: "36px", fontWeight: 700, color: "var(--text-primary)", letterSpacing: "-0.02em", lineHeight: 1 }}>{data.value}</span>
        <span style={{ fontSize: "13px", fontWeight: 600, color: data.positive ? "#72E8A8" : "#E87272", marginTop: "8px" }}>{data.change}</span>
      </div>
    );
  }

  if (widget.type === "table") {
    return (
      <div style={{ overflowX: "auto" }}>
        <div style={{ display: "grid", gridTemplateColumns: `repeat(${data.headers.length}, 1fr)`, padding: "0 0 8px", borderBottom: "1px solid var(--border)", fontSize: "10px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.06em", textTransform: "uppercase" }}>
          {data.headers.map((h, i) => <span key={i}>{h}</span>)}
        </div>
        {data.rows.map((row, ri) => (
          <div key={ri} style={{ display: "grid", gridTemplateColumns: `repeat(${data.headers.length}, 1fr)`, padding: "10px 0", borderBottom: "1px solid var(--border)", fontSize: "13px" }}>
            {row.map((cell, ci) => <span key={ci} style={{ color: ci === 0 ? "var(--text-secondary)" : "var(--text-tertiary)", fontWeight: ci === 0 ? 500 : 400 }}>{cell}</span>)}
          </div>
        ))}
      </div>
    );
  }

  if (widget.type === "donut_chart") {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: "20px" }}>
        <ResponsiveContainer width={140} height={140}><PieChart><Pie data={data.data} cx="50%" cy="50%" innerRadius={42} outerRadius={62} paddingAngle={3} dataKey="value" stroke="none">{data.data.map((_, i) => <Cell key={i} fill={CHART_COLORS[i % CHART_COLORS.length]} />)}</Pie></PieChart></ResponsiveContainer>
        <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
          {data.data.map((d, i) => (<div key={i} style={{ display: "flex", alignItems: "center", gap: "8px" }}><div style={{ width: 8, height: 8, borderRadius: 3, background: CHART_COLORS[i % CHART_COLORS.length] }} /><span style={{ fontSize: "12px", color: "var(--text-secondary)" }}>{d.name}</span><span style={{ fontSize: "12px", fontWeight: 600, color: "var(--text-secondary)" }}>{d.value}%</span></div>))}
        </div>
      </div>
    );
  }

  const ChartComp = widget.type === "bar_chart" ? BarChart : widget.type === "area_chart" ? AreaChart : LineChart;
  const DataComp = widget.type === "bar_chart" ? Bar : widget.type === "area_chart" ? Area : Line;

  if (data.series && data.series.length === 2) {
    return (
      <ResponsiveContainer width="100%" height={200}>
        <AreaChart data={data.data} margin={chartMargin}>
          <CartesianGrid strokeDasharray="3 3" stroke="var(--chart-grid)" />
          <XAxis dataKey="label" {...axisProps} /><YAxis {...axisProps} tickFormatter={yFmt} />
          <Tooltip content={<CustomTooltip />} />
          <Area type="monotone" dataKey="value" stroke="#72E8A8" strokeWidth={2} fill="rgba(114,232,168,0.1)" name={data.series[0]} />
          <Area type="monotone" dataKey="value2" stroke="#B472E8" strokeWidth={2} fill="rgba(180,114,232,0.1)" name={data.series[1]} />
        </AreaChart>
      </ResponsiveContainer>
    );
  }

  return (
    <ResponsiveContainer width="100%" height={200}>
      <ChartComp data={data.data} margin={chartMargin}>
        <CartesianGrid strokeDasharray="3 3" stroke="var(--chart-grid)" vertical={widget.type === "bar_chart" ? false : undefined} />
        <XAxis dataKey="label" {...axisProps} /><YAxis {...axisProps} tickFormatter={yFmt} />
        <Tooltip content={<CustomTooltip />} />
        {widget.type === "bar_chart" ? <Bar dataKey="value" name="Value" radius={[6, 6, 0, 0]} fill="#E8C872" maxBarSize={40} /> : widget.type === "area_chart" ? <Area type="monotone" dataKey="value" stroke="#E8C872" strokeWidth={2} fill="rgba(232,200,114,0.15)" name="Value" /> : <Line type="monotone" dataKey="value" stroke="#E8C872" strokeWidth={2.5} name="Value" dot={{ r: 3, fill: "#E8C872", strokeWidth: 0 }} />}
      </ChartComp>
    </ResponsiveContainer>
  );
};

const AddWidgetModal = ({ onClose, onAdd }) => {
  const [prompt, setPrompt] = useState("");
  const [type, setType] = useState("area_chart");
  const [loading, setLoading] = useState(false);

  const handleAdd = async () => {
    if (!prompt.trim()) return;
    setLoading(true);
    // Simulate AI processing delay
    await new Promise(r => setTimeout(r, 1200));
    const data = generateWidgetData(prompt, type);
    onAdd({ id: `w_${Date.now()}`, type, prompt: prompt.trim(), title: data.title || prompt.trim(), data, size: type === "kpi_card" ? "small" : "medium", created: new Date().toISOString() });
    setLoading(false);
  };

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 2000, display: "flex", alignItems: "center", justifyContent: "center", background: "var(--modal-overlay)", backdropFilter: "blur(8px)", animation: "fadeUp 0.2s ease" }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{ width: 520, background: "var(--modal-bg)", border: "1px solid var(--input-border)", borderRadius: "20px", padding: "32px", boxShadow: "0 32px 80px rgba(0,0,0,0.5)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "24px" }}>
          <h3 style={{ fontFamily: "'Sora', sans-serif", fontSize: "20px", fontWeight: 700, color: "var(--text-primary)" }}>Add Widget</h3>
          <button onClick={onClose} style={{ background: "none", border: "none", color: "var(--text-tertiary)", fontSize: "18px", cursor: "pointer", fontFamily: "inherit" }}>\u2715</button>
        </div>

        <label style={{ fontSize: "11px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.06em", textTransform: "uppercase", display: "block", marginBottom: "8px" }}>Widget Type</label>
        <div style={{ display: "flex", flexWrap: "wrap", gap: "8px", marginBottom: "24px" }}>
          {WIDGET_TYPES.map(wt => (
            <button key={wt.id} onClick={() => setType(wt.id)} style={{
              padding: "8px 14px", borderRadius: "8px", fontSize: "12px", fontWeight: 600,
              background: type === wt.id ? "rgba(232,200,114,0.1)" : "rgba(255,255,255,0.03)",
              border: `1px solid ${type === wt.id ? "rgba(232,200,114,0.3)" : "rgba(255,255,255,0.06)"}`,
              color: type === wt.id ? "var(--gold)" : "var(--text-tertiary)",
              cursor: "pointer", fontFamily: "inherit", transition: "all 0.2s",
              display: "flex", alignItems: "center", gap: "6px",
            }}>{wt.icon} {wt.label}</button>
          ))}
        </div>

        <label style={{ fontSize: "11px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.06em", textTransform: "uppercase", display: "block", marginBottom: "8px" }}>What do you want to see?</label>
        <textarea
          value={prompt} onChange={e => setPrompt(e.target.value)}
          onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleAdd(); } }}
          placeholder='e.g. "Monthly revenue for the last 12 months" or "Top 10 products by units sold"'
          rows={3}
          style={{
            width: "100%", background: "var(--input-bg)", border: "1px solid var(--input-border)",
            borderRadius: "12px", padding: "14px 16px", color: "var(--text-primary)", fontSize: "14px",
            fontFamily: "inherit", resize: "none", outline: "none", lineHeight: 1.5,
            marginBottom: "8px",
          }}
        />
        <div style={{ display: "flex", flexWrap: "wrap", gap: "6px", marginBottom: "24px" }}>
          {["Monthly revenue last 6 months", "Top 5 products by units sold", "Orders by status", "Daily revenue this week"].map(s => (
            <button key={s} onClick={() => setPrompt(s)} style={{
              padding: "5px 10px", borderRadius: "6px", fontSize: "11px",
              background: "var(--bg-surface)", border: "1px solid var(--border)",
              color: "var(--text-tertiary)", cursor: "pointer", fontFamily: "inherit",
              transition: "all 0.2s",
            }}
              onMouseEnter={e => { e.target.style.borderColor = "rgba(232,200,114,0.2)"; e.target.style.color = "#E8C872"; }}
              onMouseLeave={e => { e.target.style.borderColor = "var(--border)"; e.target.style.color = "var(--text-tertiary)"; }}
            >{s}</button>
          ))}
        </div>

        <button onClick={handleAdd} disabled={!prompt.trim() || loading} style={{
          width: "100%", padding: "14px", borderRadius: "12px", border: "none",
          background: prompt.trim() && !loading ? "linear-gradient(135deg, #E8C872, #D4A843)" : "rgba(255,255,255,0.06)",
          color: prompt.trim() && !loading ? "#0F1117" : "var(--text-muted)",
          fontSize: "14px", fontWeight: 700, cursor: prompt.trim() && !loading ? "pointer" : "default",
          fontFamily: "inherit", transition: "all 0.2s",
          display: "flex", alignItems: "center", justifyContent: "center", gap: "8px",
        }}>
          {loading ? (<><div style={{ width: 16, height: 16, border: "2px solid rgba(0,0,0,0.2)", borderTopColor: "#0F1117", borderRadius: "50%", animation: "spin 0.6s linear infinite" }} /> Generating widget...</>) : "\u2728 Generate Widget"}
        </button>
      </div>
    </div>
  );
};

const MyDashboardPage = () => {
  const [widgets, setWidgets] = useState([]);
  const [editMode, setEditMode] = useState(false);
  const [showModal, setShowModal] = useState(false);

  const addWidget = (widget) => {
    setWidgets(prev => [...prev, widget]);
    setShowModal(false);
  };

  const removeWidget = (id) => setWidgets(prev => prev.filter(w => w.id !== id));

  const applyTemplate = (template) => {
    const newWidgets = template.widgets.map((tw, i) => {
      const data = generateWidgetData(tw.prompt, tw.type);
      return { id: `w_${Date.now()}_${i}`, type: tw.type, prompt: tw.prompt, title: data.title || tw.prompt, data, size: tw.size, created: new Date().toISOString() };
    });
    setWidgets(newWidgets);
  };

  const cycleSize = (id) => {
    setWidgets(prev => prev.map(w => {
      if (w.id !== id) return w;
      const sizes = w.type === "kpi_card" ? ["small", "medium"] : ["medium", "large"];
      const idx = sizes.indexOf(w.size);
      return { ...w, size: sizes[(idx + 1) % sizes.length] };
    }));
  };

  const refreshWidget = (id) => {
    setWidgets(prev => prev.map(w => {
      if (w.id !== id) return w;
      const data = generateWidgetData(w.prompt, w.type);
      return { ...w, data };
    }));
  };

  // Empty state
  if (widgets.length === 0) {
    return (
      <div style={{ animation: "fadeUp 0.5s ease" }}>
        <SectionTitle title="My Dashboard" sub="Build your own custom analytics view" />
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "60px 20px" }}>
          <div style={{ fontSize: "48px", marginBottom: "20px", opacity: 0.4 }}>{"\u2728"}</div>
          <h3 style={{ fontSize: "18px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "8px" }}>Build your own dashboard</h3>
          <p style={{ fontSize: "14px", color: "var(--text-muted)", marginBottom: "28px", textAlign: "center", maxWidth: 400 }}>Add widgets using text prompts. Describe what you want to see and the AI will create it for you.</p>
          <button onClick={() => setShowModal(true)} style={{
            padding: "14px 32px", borderRadius: "12px", border: "none",
            background: "linear-gradient(135deg, #E8C872, #D4A843)", color: "#0F1117",
            fontSize: "14px", fontWeight: 700, cursor: "pointer", fontFamily: "inherit",
            boxShadow: "0 8px 32px rgba(232,200,114,0.25)", transition: "all 0.2s",
            display: "flex", alignItems: "center", gap: "8px",
          }}>{"\u2795"} Add Your First Widget</button>

          <div style={{ marginTop: "48px", width: "100%" }}>
            <p style={{ fontSize: "12px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.06em", textTransform: "uppercase", textAlign: "center", marginBottom: "16px" }}>Or start with a template</p>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "12px" }}>
              {PRESET_TEMPLATES.map((t, i) => (
                <div key={i} className="card" onClick={() => applyTemplate(t)} style={{ padding: "20px", cursor: "pointer", textAlign: "center", animation: `fadeUp 0.5s ease ${i * 0.08}s both` }}>
                  <div style={{ fontSize: "28px", marginBottom: "10px" }}>{t.icon}</div>
                  <h4 style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "4px" }}>{t.name}</h4>
                  <p style={{ fontSize: "11px", color: "var(--text-muted)", lineHeight: 1.4 }}>{t.desc}</p>
                </div>
              ))}
            </div>
          </div>
        </div>
        {showModal && <AddWidgetModal onClose={() => setShowModal(false)} onAdd={addWidget} />}
      </div>
    );
  }

  // Dashboard with widgets
  const getColSpan = (size) => size === "small" ? 3 : size === "large" ? 12 : 6;

  return (
    <div style={{ animation: "fadeUp 0.5s ease" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "20px" }}>
        <SectionTitle title="My Dashboard" sub={`${widgets.length} widget${widgets.length !== 1 ? "s" : ""}`} />
        <div style={{ display: "flex", gap: "8px" }}>
          <button onClick={() => setEditMode(!editMode)} className={`date-btn ${editMode ? "active" : ""}`}>
            {editMode ? "\u2713 Done Editing" : "\u270E Edit Layout"}
          </button>
          <button onClick={() => setShowModal(true)} className="link-btn">{"\u2795"} Add Widget</button>
          <button onClick={() => { if (confirm("Reset dashboard and remove all widgets?")) setWidgets([]); }} style={{ padding: "6px 14px", borderRadius: "6px", fontSize: "12px", fontWeight: 600, cursor: "pointer", border: "1px solid rgba(232,114,114,0.2)", background: "transparent", color: "var(--red)", fontFamily: "inherit", transition: "all 0.2s" }}>{"\u{1F5D1}"} Reset</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(12, 1fr)", gap: "16px" }}>
        {widgets.map((w, i) => {
          const colSpan = getColSpan(w.size);
          const isKpi = w.type === "kpi_card";
          const isTable = w.type === "table";
          return (
            <div key={w.id} className="card" style={{
              gridColumn: `span ${colSpan}`,
              padding: "20px 24px",
              minHeight: isKpi ? 120 : isTable ? 200 : undefined,
              height: isKpi ? undefined : isTable ? undefined : 280,
              position: "relative",
              animation: `fadeUp 0.4s ease ${i * 0.05}s both`,
              border: editMode ? "1px dashed rgba(232,200,114,0.25)" : undefined,
            }}>
              {/* Widget header */}
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: isKpi ? "4px" : "16px" }}>
                <div>
                  <h4 style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "2px" }}>{w.title}</h4>
                  {!isKpi && <p style={{ fontSize: "11px", color: "var(--text-muted)", fontStyle: "italic" }}>{w.prompt}</p>}
                </div>
                <div style={{ display: "flex", gap: "4px", alignItems: "center" }}>
                  <button onClick={() => refreshWidget(w.id)} title="Refresh" style={{ background: "none", border: "none", color: "var(--text-muted)", cursor: "pointer", fontSize: "14px", padding: "4px", transition: "color 0.2s" }} onMouseEnter={e => e.target.style.color = "#E8C872"} onMouseLeave={e => e.target.style.color = "rgba(255,255,255,0.25)"}>{"\u{1F504}"}</button>
                  {editMode && (
                    <>
                      <button onClick={() => cycleSize(w.id)} title="Resize" style={{ background: "none", border: "none", color: "var(--text-muted)", cursor: "pointer", fontSize: "14px", padding: "4px", transition: "color 0.2s" }} onMouseEnter={e => e.target.style.color = "#72B4E8"} onMouseLeave={e => e.target.style.color = "rgba(255,255,255,0.25)"}>{"\u2922"}</button>
                      <button onClick={() => removeWidget(w.id)} title="Remove" style={{ background: "none", border: "none", color: "var(--text-muted)", cursor: "pointer", fontSize: "14px", padding: "4px", transition: "color 0.2s" }} onMouseEnter={e => e.target.style.color = "#E87272"} onMouseLeave={e => e.target.style.color = "rgba(255,255,255,0.25)"}>{"\u2715"}</button>
                    </>
                  )}
                </div>
              </div>
              {/* Widget content */}
              <div style={{ height: isKpi ? "auto" : isTable ? "auto" : 200 }}>
                <WidgetRenderer widget={w} />
              </div>
              {/* Size indicator in edit mode */}
              {editMode && <div style={{ position: "absolute", bottom: 6, right: 10, fontSize: "9px", color: "var(--text-faint)", letterSpacing: "0.06em", textTransform: "uppercase" }}>{w.size}</div>}
            </div>
          );
        })}
      </div>

      {showModal && <AddWidgetModal onClose={() => setShowModal(false)} onAdd={addWidget} />}
    </div>
  );
};

/* ═══════════════════════════════════════════
   REPORT BUILDER
   ═══════════════════════════════════════════ */

const REPORT_SECTION_PRESETS = [
  { prompt: "Top product sales this month", chartType: "bar_chart", icon: "\u{1F4E6}" },
  { prompt: "Monthly revenue for the last 6 months", chartType: "area_chart", icon: "\u{1F4B0}" },
  { prompt: "Customer acquisition this quarter", chartType: "area_chart", icon: "\u{1F465}" },
  { prompt: "Orders by status breakdown", chartType: "donut_chart", icon: "\u{1F4CB}" },
  { prompt: "Revenue by product category", chartType: "donut_chart", icon: "\u{1F4CA}" },
  { prompt: "Daily revenue this week", chartType: "bar_chart", icon: "\u{1F4C8}" },
  { prompt: "Top customers by lifetime spend", chartType: "bar_chart", icon: "\u{1F451}" },
  { prompt: "Low stock product alerts", chartType: "table", icon: "\u26A0\uFE0F" },
];

// Generates AI-style commentary text for a report section
const generateReportText = (prompt) => {
  const p = prompt.toLowerCase();

  if (p.includes("top product") || p.includes("best seller")) {
    return "Premium Wireless Headphones led the category this month with 284 units sold, generating \u00A322,720 in revenue \u2014 a 12% increase over the previous period. Artisan Coffee Blend maintained strong volume at 312 units, though at a lower price point contributing \u00A37,800. Organic Face Serum showed consistent growth at +8%, now the second highest revenue product at \u00A315,680.\n\nNotably, Smart LED Strip Kit saw the sharpest growth at +22%, suggesting strong seasonal demand or effective promotion. Consider increasing stock levels for this product ahead of the next campaign cycle. Bluetooth Speaker Mini also performed well with 189 units, though the 4.3 rating suggests some quality concerns worth investigating in customer reviews.";
  }
  if (p.includes("revenue") && (p.includes("month") || p.includes("6"))) {
    return "Revenue has shown a clear upward trajectory over the six-month period, peaking at \u00A338,200 in December \u2014 a 31% increase over the September baseline of \u00A318,400. The post-holiday dip in January (\u00A324,800) was less severe than last year's equivalent drop, indicating improved customer retention.\n\nFebruary recovered to \u00A327,600, tracking 21% ahead of the same period last year (\u00A322,800). Year-on-year growth has been consistently positive across all six months, averaging +18.4%. If this trajectory holds, the store is on pace to exceed \u00A3200,000 in total revenue by the end of the current fiscal year.";
  }
  if (p.includes("customer") && (p.includes("acqui") || p.includes("growth"))) {
    return "New customer acquisition peaked in December with 192 new accounts, driven by holiday shopping and likely supported by promotional activity. January saw the expected post-holiday decline to 112, but February rebounded to 134 \u2014 a healthy sign of organic growth returning.\n\nReturning customer numbers have grown steadily from 142 in September to 205 in February, indicating strong retention. The returning-to-new ratio improved from 1.65:1 to 1.53:1, meaning the store is acquiring proportionally more new customers while maintaining its existing base. Total active customers now stand at 876, a 24.6% increase over the previous period.";
  }
  if (p.includes("status") || p.includes("order") && p.includes("break")) {
    return "Order fulfilment is performing well, with 65% of orders reaching Completed status within the reporting period. Processing orders account for 20%, representing the current pipeline of active fulfilments that should convert within 24\u201348 hours.\n\nOn Hold orders at 10% merit attention \u2014 these typically indicate payment verification delays or stock availability issues. The refund rate of 5% is within acceptable industry benchmarks (average WooCommerce refund rate is 6\u20138%), though any increase should be investigated promptly. Reviewing the On Hold orders for common patterns could help reduce this queue and improve the customer experience.";
  }
  if (p.includes("category") || p.includes("categor")) {
    return "Electronics dominates the revenue mix at 38%, driven primarily by Premium Wireless Headphones, Smart LED Strip Kit, and Bluetooth Speaker Mini. This concentration presents both an opportunity (clear product-market fit) and a risk (over-reliance on a single category).\n\nBeauty products account for 24% of revenue with strong margins, while Home products at 18% show steady performance with lower return rates. Food & Drink (12%) maintains high repeat purchase rates despite lower per-unit revenue. Apparel at 8% represents the smallest segment but showed the strongest growth trend at +15%, suggesting an emerging opportunity worth investing in through expanded product lines.";
  }
  if (p.includes("daily") || p.includes("week")) {
    return "This week's revenue totalled \u00A337,380, with a clear peak on Saturday at \u00A37,210 \u2014 accounting for 19.3% of the weekly total. Friday was the second strongest day at \u00A36,340, confirming the typical end-of-week shopping pattern.\n\nTuesday recorded the lowest activity at \u00A33,890, presenting an opportunity for targeted mid-week promotions. The mid-week average (Mon\u2013Thu) of \u00A34,485 compared to the weekend average (Fri\u2013Sun) of \u00A36,480 suggests nearly 45% of revenue is concentrated in the final three days of the week. Consider scheduling email campaigns and social media pushes for Thursday evening to capture the Friday\u2013Saturday demand wave.";
  }
  if (p.includes("top customer") || p.includes("lifetime")) {
    return "Maria Rossi leads the customer base with \u00A34,102.60 in lifetime spend across 22 orders since December 2024, placing her firmly in the Platinum tier. Yuki Tanaka (\u00A33,210.80, 18 orders) and Emma Wilson (\u00A32,780.20, 15 orders) round out the top three.\n\nThe Platinum tier (customers spending over \u00A32,500) now comprises 15% of the customer base but generates approximately 42% of total revenue \u2014 a classic Pareto distribution. Gold tier customers (30%) contribute 33% of revenue. Investing in loyalty rewards or exclusive offers for the top two tiers could significantly improve retention rates and increase average order frequency, which currently sits at 1.4 orders per month for Platinum customers.";
  }
  if (p.includes("stock") || p.includes("low")) {
    return "Four products are currently flagged with stock levels below the 100-unit threshold. Smart LED Strip Kit is the most critical at 56 units remaining \u2014 given its +22% sales trend, current velocity suggests stockout within approximately 12 days without replenishment.\n\nCeramic Pour-Over Set (64 units) and Organic Face Serum (88 units) also require attention, though their lower daily sell-through rates provide a longer runway. Bluetooth Speaker Mini at 102 units is just above threshold but should be monitored given its strong sales volume of 189 units this period. Recommend placing reorders for all four products immediately, prioritising the LED Strip Kit for expedited shipping.";
  }
  return `Analysis of "${prompt}" shows positive trends across the reporting period. Key metrics indicate growth in the primary segments, with revenue tracking ahead of projections. Several areas of opportunity have been identified for the coming period, including optimising the product mix and improving customer retention through targeted campaigns.\n\nThe data suggests focusing investment on the highest-performing categories while monitoring emerging trends in secondary segments. Customer feedback and repeat purchase patterns indicate strong brand loyalty among the top tier, providing a solid foundation for expansion.`;
};

const AddSectionModal = ({ onClose, onAdd }) => {
  const [prompt, setPrompt] = useState("");
  const [chartType, setChartType] = useState("bar_chart");
  const [loading, setLoading] = useState(false);

  const chartTypes = [
    { id: "bar_chart", label: "Bar Chart", icon: "\u{1F4CA}" },
    { id: "area_chart", label: "Area Chart", icon: "\u{1F30A}" },
    { id: "line_chart", label: "Line Chart", icon: "\u{1F4C8}" },
    { id: "donut_chart", label: "Donut Chart", icon: "\u{1F369}" },
    { id: "table", label: "Table", icon: "\u{1F4CB}" },
    { id: "text_only", label: "Text Only", icon: "\u{1F4DD}" },
  ];

  const handleAdd = async () => {
    if (!prompt.trim()) return;
    setLoading(true);
    await new Promise(r => setTimeout(r, 1500));
    const text = generateReportText(prompt);
    const chartData = chartType !== "text_only" ? generateWidgetData(prompt, chartType) : null;
    onAdd({
      id: `rs_${Date.now()}`,
      prompt: prompt.trim(),
      title: chartData?.title || prompt.trim(),
      text,
      chartType: chartType === "text_only" ? null : chartType,
      chartData,
    });
    setLoading(false);
  };

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 2000, display: "flex", alignItems: "center", justifyContent: "center", background: "var(--modal-overlay)", backdropFilter: "blur(8px)", animation: "fadeUp 0.2s ease" }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{ width: 560, background: "var(--modal-bg)", border: "1px solid var(--input-border)", borderRadius: "20px", padding: "32px", boxShadow: "0 32px 80px rgba(0,0,0,0.5)", maxHeight: "90vh", overflowY: "auto" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "24px" }}>
          <h3 style={{ fontFamily: "'Sora', sans-serif", fontSize: "20px", fontWeight: 700, color: "var(--text-primary)" }}>Add Report Section</h3>
          <button onClick={onClose} style={{ background: "none", border: "none", color: "var(--text-tertiary)", fontSize: "18px", cursor: "pointer", fontFamily: "inherit" }}>{"\u2715"}</button>
        </div>

        <label style={{ fontSize: "11px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.06em", textTransform: "uppercase", display: "block", marginBottom: "8px" }}>What should this section cover?</label>
        <textarea
          value={prompt} onChange={e => setPrompt(e.target.value)}
          onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleAdd(); } }}
          placeholder='e.g. "Top product sales this month" or "Revenue by category breakdown"'
          rows={2}
          style={{ width: "100%", background: "var(--input-bg)", border: "1px solid var(--input-border)", borderRadius: "12px", padding: "14px 16px", color: "var(--text-primary)", fontSize: "14px", fontFamily: "inherit", resize: "none", outline: "none", lineHeight: 1.5, marginBottom: "12px" }}
        />

        <div style={{ display: "flex", flexWrap: "wrap", gap: "6px", marginBottom: "24px" }}>
          {REPORT_SECTION_PRESETS.map((s, i) => (
            <button key={i} onClick={() => { setPrompt(s.prompt); setChartType(s.chartType); }} style={{ padding: "6px 12px", borderRadius: "8px", fontSize: "11px", background: "var(--bg-surface)", border: "1px solid var(--border)", color: "var(--text-tertiary)", cursor: "pointer", fontFamily: "inherit", transition: "all 0.2s", display: "flex", alignItems: "center", gap: "4px" }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = "rgba(232,200,114,0.25)"; e.currentTarget.style.color = "#E8C872"; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--border)"; e.currentTarget.style.color = "var(--text-tertiary)"; }}
            ><span>{s.icon}</span> {s.prompt}</button>
          ))}
        </div>

        <label style={{ fontSize: "11px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.06em", textTransform: "uppercase", display: "block", marginBottom: "8px" }}>Visualisation Type</label>
        <div style={{ display: "flex", flexWrap: "wrap", gap: "8px", marginBottom: "28px" }}>
          {chartTypes.map(ct => (
            <button key={ct.id} onClick={() => setChartType(ct.id)} style={{
              padding: "8px 14px", borderRadius: "8px", fontSize: "12px", fontWeight: 600,
              background: chartType === ct.id ? "rgba(232,200,114,0.1)" : "rgba(255,255,255,0.03)",
              border: `1px solid ${chartType === ct.id ? "rgba(232,200,114,0.3)" : "rgba(255,255,255,0.06)"}`,
              color: chartType === ct.id ? "var(--gold)" : "var(--text-tertiary)",
              cursor: "pointer", fontFamily: "inherit", transition: "all 0.2s",
              display: "flex", alignItems: "center", gap: "6px",
            }}>{ct.icon} {ct.label}</button>
          ))}
        </div>

        <button onClick={handleAdd} disabled={!prompt.trim() || loading} style={{
          width: "100%", padding: "14px", borderRadius: "12px", border: "none",
          background: prompt.trim() && !loading ? "linear-gradient(135deg, #E8C872, #D4A843)" : "rgba(255,255,255,0.06)",
          color: prompt.trim() && !loading ? "#0F1117" : "var(--text-muted)",
          fontSize: "14px", fontWeight: 700, cursor: prompt.trim() && !loading ? "pointer" : "default",
          fontFamily: "inherit", transition: "all 0.2s",
          display: "flex", alignItems: "center", justifyContent: "center", gap: "8px",
        }}>
          {loading ? (<><div style={{ width: 16, height: 16, border: "2px solid rgba(0,0,0,0.2)", borderTopColor: "#0F1117", borderRadius: "50%", animation: "spin 0.6s linear infinite" }} /> Generating section...</>) : "\u{1F4DD} Add Section"}
        </button>
      </div>
    </div>
  );
};

const ReportSectionChart = ({ section }) => {
  if (!section.chartData || !section.chartType) return null;

  const w = { type: section.chartType, data: section.chartData };
  const chartMargin = { top: 5, right: 10, left: -10, bottom: 0 };
  const axisProps = { tick: { fontSize: 11, fill: "var(--chart-axis)" }, axisLine: false, tickLine: false };
  const yFmt = section.chartData.yFormat === "currency" ? v => `\u00A3${(v >= 1000 ? (v / 1000).toFixed(0) + "k" : v)}` : undefined;

  if (section.chartType === "table" && section.chartData.headers) {
    return (
      <div style={{ overflowX: "auto" }}>
        <div style={{ display: "grid", gridTemplateColumns: `repeat(${section.chartData.headers.length}, 1fr)`, padding: "0 0 8px", borderBottom: "1px solid var(--border)", fontSize: "10px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.06em", textTransform: "uppercase" }}>
          {section.chartData.headers.map((h, i) => <span key={i}>{h}</span>)}
        </div>
        {section.chartData.rows.map((row, ri) => (
          <div key={ri} style={{ display: "grid", gridTemplateColumns: `repeat(${section.chartData.headers.length}, 1fr)`, padding: "10px 0", borderBottom: "1px solid var(--border)", fontSize: "13px" }}>
            {row.map((cell, ci) => <span key={ci} style={{ color: ci === 0 ? "var(--text-secondary)" : "var(--text-tertiary)", fontWeight: ci === 0 ? 500 : 400 }}>{cell}</span>)}
          </div>
        ))}
      </div>
    );
  }

  if (section.chartType === "donut_chart" && section.chartData.data) {
    return (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: "32px" }}>
        <ResponsiveContainer width={180} height={180}><PieChart><Pie data={section.chartData.data} cx="50%" cy="50%" innerRadius={55} outerRadius={80} paddingAngle={3} dataKey="value" stroke="none">{section.chartData.data.map((_, i) => <Cell key={i} fill={CHART_COLORS[i % CHART_COLORS.length]} />)}</Pie></PieChart></ResponsiveContainer>
        <div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
          {section.chartData.data.map((d, i) => (<div key={i} style={{ display: "flex", alignItems: "center", gap: "10px" }}><div style={{ width: 10, height: 10, borderRadius: 3, background: CHART_COLORS[i % CHART_COLORS.length] }} /><span style={{ fontSize: "13px", color: "var(--text-secondary)" }}>{d.name}</span><span style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-secondary)" }}>{d.value}%</span></div>))}
        </div>
      </div>
    );
  }

  if (section.chartData.data) {
    const ChartComp = section.chartType === "bar_chart" ? BarChart : section.chartType === "area_chart" ? AreaChart : LineChart;
    const hasTwo = section.chartData.series && section.chartData.series.length === 2;

    if (hasTwo) {
      return (
        <ResponsiveContainer width="100%" height={220}>
          <AreaChart data={section.chartData.data} margin={chartMargin}>
            <CartesianGrid strokeDasharray="3 3" stroke="var(--chart-grid)" />
            <XAxis dataKey="label" {...axisProps} /><YAxis {...axisProps} tickFormatter={yFmt} />
            <Tooltip content={<CustomTooltip />} />
            <Area type="monotone" dataKey="value" stroke="#72E8A8" strokeWidth={2} fill="rgba(114,232,168,0.1)" name={section.chartData.series[0]} />
            <Area type="monotone" dataKey="value2" stroke="#B472E8" strokeWidth={2} fill="rgba(180,114,232,0.1)" name={section.chartData.series[1]} />
          </AreaChart>
        </ResponsiveContainer>
      );
    }

    return (
      <ResponsiveContainer width="100%" height={220}>
        <ChartComp data={section.chartData.data} margin={chartMargin}>
          <CartesianGrid strokeDasharray="3 3" stroke="var(--chart-grid)" vertical={section.chartType === "bar_chart" ? false : undefined} />
          <XAxis dataKey="label" {...axisProps} /><YAxis {...axisProps} tickFormatter={yFmt} />
          <Tooltip content={<CustomTooltip />} />
          {section.chartType === "bar_chart" ? <Bar dataKey="value" name="Value" radius={[6, 6, 0, 0]} fill="#E8C872" maxBarSize={44} /> : section.chartType === "area_chart" ? <Area type="monotone" dataKey="value" stroke="#E8C872" strokeWidth={2} fill="rgba(232,200,114,0.15)" name="Value" /> : <Line type="monotone" dataKey="value" stroke="#E8C872" strokeWidth={2.5} name="Value" dot={{ r: 3, fill: "#E8C872", strokeWidth: 0 }} />}
        </ChartComp>
      </ResponsiveContainer>
    );
  }
  return null;
};

const ReportsPage = ({ navigate }) => {
  const [sections, setSections] = useState([]);
  const [showAddModal, setShowAddModal] = useState(false);
  const [reportTitle, setReportTitle] = useState("Monthly Performance Report");
  const [editingTitle, setEditingTitle] = useState(false);
  const [viewMode, setViewMode] = useState("edit"); // edit | preview
  const titleRef = useRef(null);

  const addSection = (section) => {
    setSections(prev => [...prev, section]);
    setShowAddModal(false);
  };

  const removeSection = (id) => setSections(prev => prev.filter(s => s.id !== id));

  const moveSection = (id, dir) => {
    setSections(prev => {
      const idx = prev.findIndex(s => s.id === id);
      if ((dir === -1 && idx === 0) || (dir === 1 && idx === prev.length - 1)) return prev;
      const next = [...prev];
      [next[idx], next[idx + dir]] = [next[idx + dir], next[idx]];
      return next;
    });
  };

  const now = new Date();
  const dateStr = now.toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" });

  // Empty state
  if (sections.length === 0 && viewMode === "edit") {
    return (
      <div style={{ animation: "fadeUp 0.5s ease" }}>
        <SectionTitle title="Reports" sub="Generate AI-powered analytics reports with custom sections" />
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "60px 20px" }}>
          <div style={{ fontSize: "48px", marginBottom: "20px", opacity: 0.4 }}>{"\u{1F4DD}"}</div>
          <h3 style={{ fontSize: "18px", fontWeight: 600, color: "var(--text-primary)", marginBottom: "8px" }}>Create a report</h3>
          <p style={{ fontSize: "14px", color: "var(--text-muted)", marginBottom: "28px", textAlign: "center", maxWidth: 420 }}>Add sections to your report using text prompts. Each section generates an AI analysis with supporting charts and data visualisations.</p>
          <button onClick={() => setShowAddModal(true)} style={{
            padding: "14px 32px", borderRadius: "12px", border: "none",
            background: "linear-gradient(135deg, #E8C872, #D4A843)", color: "#0F1117",
            fontSize: "14px", fontWeight: 700, cursor: "pointer", fontFamily: "inherit",
            boxShadow: "0 8px 32px rgba(232,200,114,0.25)", transition: "all 0.2s",
            display: "flex", alignItems: "center", gap: "8px",
          }}>{"\u2795"} Add First Section</button>

          <div style={{ marginTop: "48px", width: "100%", maxWidth: 600 }}>
            <p style={{ fontSize: "12px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.06em", textTransform: "uppercase", textAlign: "center", marginBottom: "16px" }}>Example section prompts</p>
            <div style={{ display: "flex", flexWrap: "wrap", gap: "8px", justifyContent: "center" }}>
              {REPORT_SECTION_PRESETS.map((s, i) => (
                <div key={i} style={{ padding: "8px 14px", borderRadius: "8px", background: "var(--bg-surface)", border: "1px solid var(--border)", fontSize: "12px", color: "var(--text-tertiary)", display: "flex", alignItems: "center", gap: "6px" }}>
                  <span>{s.icon}</span> {s.prompt}
                </div>
              ))}
            </div>
          </div>
        </div>
        {showAddModal && <AddSectionModal onClose={() => setShowAddModal(false)} onAdd={addSection} />}
      </div>
    );
  }

  // Preview mode - clean printable report
  if (viewMode === "preview") {
    return (
      <div style={{ animation: "fadeUp 0.4s ease" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "20px" }}>
          <button onClick={() => setViewMode("edit")} className="link-btn" style={{ display: "flex", alignItems: "center", gap: "6px" }}>{"\u2190"} Back to Editor</button>
          <button onClick={() => window.print?.()} className="link-btn" style={{ display: "flex", alignItems: "center", gap: "6px" }}>{"\u{1F5A8}\uFE0F"} Print Report</button>
        </div>

        {/* Report Document */}
        <div style={{ background: "linear-gradient(180deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0.01) 100%)", border: "1px solid var(--input-border)", borderRadius: "20px", padding: "48px", maxWidth: 900, margin: "0 auto" }}>
          {/* Report Header */}
          <div style={{ borderBottom: "2px solid rgba(232,200,114,0.3)", paddingBottom: "32px", marginBottom: "40px" }}>
            <div style={{ display: "flex", alignItems: "center", gap: "12px", marginBottom: "24px" }}>
              <div style={{ width: 40, height: 40, borderRadius: "10px", background: "linear-gradient(135deg, #E8C872, #D4A843)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "18px", fontWeight: 700, color: "#0F1117" }}>W</div>
              <span style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.08em", textTransform: "uppercase" }}>WooInsight Analytics</span>
            </div>
            <h1 style={{ fontFamily: "'Sora', sans-serif", fontSize: "36px", fontWeight: 700, color: "var(--text-primary)", letterSpacing: "-0.02em", marginBottom: "8px" }}>{reportTitle}</h1>
            <p style={{ fontSize: "14px", color: "var(--text-muted)" }}>Generated {dateStr} &bull; {sections.length} section{sections.length !== 1 ? "s" : ""}</p>
          </div>

          {/* Table of Contents */}
          {sections.length > 2 && (
            <div style={{ marginBottom: "40px", padding: "20px 24px", background: "var(--bg-surface2)", borderRadius: "12px", border: "1px solid rgba(255,255,255,0.04)" }}>
              <p style={{ fontSize: "11px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: "12px" }}>Contents</p>
              {sections.map((s, i) => (
                <div key={s.id} style={{ display: "flex", alignItems: "center", gap: "12px", padding: "6px 0" }}>
                  <span style={{ fontSize: "13px", fontWeight: 600, color: "var(--gold)", minWidth: 24 }}>{i + 1}.</span>
                  <span style={{ fontSize: "13px", color: "var(--text-secondary)" }}>{s.title}</span>
                </div>
              ))}
            </div>
          )}

          {/* Report Sections */}
          {sections.map((section, i) => (
            <div key={section.id} style={{ marginBottom: i < sections.length - 1 ? "48px" : 0, paddingBottom: i < sections.length - 1 ? "48px" : 0, borderBottom: i < sections.length - 1 ? "1px solid var(--border)" : "none" }}>
              {/* Section Header */}
              <div style={{ display: "flex", alignItems: "baseline", gap: "16px", marginBottom: "20px" }}>
                <span style={{ fontFamily: "'Sora', sans-serif", fontSize: "48px", fontWeight: 700, color: "var(--text-faint)", lineHeight: 1 }}>{String(i + 1).padStart(2, "0")}</span>
                <div>
                  <h2 style={{ fontFamily: "'Sora', sans-serif", fontSize: "24px", fontWeight: 700, color: "var(--text-primary)", letterSpacing: "-0.01em", marginBottom: "4px" }}>{section.title}</h2>
                  <p style={{ fontSize: "12px", color: "var(--text-muted)", fontStyle: "italic" }}>{section.prompt}</p>
                </div>
              </div>

              {/* Chart */}
              {section.chartType && section.chartData && (
                <div style={{ background: "var(--bg-surface2)", border: "1px solid var(--border)", borderRadius: "14px", padding: "24px", marginBottom: "24px" }}>
                  <ReportSectionChart section={section} />
                </div>
              )}

              {/* AI Analysis Text */}
              <div style={{ lineHeight: 1.8 }}>
                {section.text.split("\n\n").map((para, pi) => (
                  <p key={pi} style={{ fontSize: "14px", color: "var(--text-secondary)", marginBottom: pi < section.text.split("\n\n").length - 1 ? "16px" : 0 }}>{para}</p>
                ))}
              </div>
            </div>
          ))}

          {/* Report Footer */}
          <div style={{ marginTop: "48px", paddingTop: "24px", borderTop: "2px solid rgba(232,200,114,0.3)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <div>
              <p style={{ fontSize: "11px", color: "var(--text-faint)", letterSpacing: "0.06em", textTransform: "uppercase" }}>Generated by WooInsight</p>
              <p style={{ fontSize: "11px", color: "var(--text-faint)", marginTop: "2px" }}>{dateStr}</p>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
              <div style={{ width: 24, height: 24, borderRadius: "6px", background: "linear-gradient(135deg, #E8C872, #D4A843)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "11px", fontWeight: 700, color: "#0F1117" }}>W</div>
              <span style={{ fontSize: "12px", fontWeight: 600, color: "var(--text-muted)" }}>WooInsight</span>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Edit mode - section builder
  return (
    <div style={{ animation: "fadeUp 0.5s ease" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: "24px" }}>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: "12px", marginBottom: "4px" }}>
            {editingTitle ? (
              <input
                ref={titleRef}
                value={reportTitle}
                onChange={e => setReportTitle(e.target.value)}
                onBlur={() => setEditingTitle(false)}
                onKeyDown={e => { if (e.key === "Enter") setEditingTitle(false); }}
                autoFocus
                style={{ fontFamily: "'Sora', sans-serif", fontSize: "24px", fontWeight: 700, color: "var(--text-primary)", background: "var(--input-bg)", border: "1px solid rgba(232,200,114,0.3)", borderRadius: "8px", padding: "4px 12px", outline: "none", width: 400, letterSpacing: "-0.02em" }}
              />
            ) : (
              <h2 style={{ fontFamily: "'Sora', sans-serif", fontSize: "24px", fontWeight: 700, color: "var(--text-primary)", cursor: "pointer", letterSpacing: "-0.02em" }} onClick={() => setEditingTitle(true)}>{reportTitle}</h2>
            )}
            <button onClick={() => setEditingTitle(!editingTitle)} style={{ background: "none", border: "none", color: "var(--text-muted)", fontSize: "14px", cursor: "pointer", padding: "4px" }}>{"\u270E"}</button>
          </div>
          <p style={{ fontSize: "13px", color: "var(--text-muted)" }}>{sections.length} section{sections.length !== 1 ? "s" : ""} &bull; {dateStr}</p>
        </div>
        <div style={{ display: "flex", gap: "8px" }}>
          <button onClick={() => setShowAddModal(true)} className="link-btn" style={{ display: "flex", alignItems: "center", gap: "6px" }}>{"\u2795"} Add Section</button>
          <button onClick={() => setViewMode("preview")} style={{
            padding: "6px 18px", borderRadius: "6px", fontSize: "12px", fontWeight: 700, cursor: "pointer",
            border: "none", fontFamily: "inherit", transition: "all 0.2s",
            background: "linear-gradient(135deg, #E8C872, #D4A843)", color: "#0F1117",
            display: "flex", alignItems: "center", gap: "6px",
          }}>{"\u{1F4F0}"} Preview Report</button>
        </div>
      </div>

      {/* Section List */}
      <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
        {sections.map((section, i) => (
          <div key={section.id} className="card" style={{ padding: "0", overflow: "hidden", animation: `fadeUp 0.4s ease ${i * 0.05}s both` }}>
            {/* Section Header Bar */}
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 24px", borderBottom: "1px solid var(--border)", background: "var(--bg-surface2)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: "14px" }}>
                <span style={{ fontFamily: "'Sora', sans-serif", fontSize: "20px", fontWeight: 700, color: "rgba(232,200,114,0.4)", minWidth: 28 }}>{String(i + 1).padStart(2, "0")}</span>
                <div>
                  <h4 style={{ fontSize: "15px", fontWeight: 600, color: "var(--text-primary)" }}>{section.title}</h4>
                  <p style={{ fontSize: "11px", color: "var(--text-muted)", fontStyle: "italic", marginTop: "2px" }}>{section.prompt}</p>
                </div>
              </div>
              <div style={{ display: "flex", gap: "4px", alignItems: "center" }}>
                {section.chartType && <span style={{ fontSize: "10px", fontWeight: 600, color: "var(--text-faint)", letterSpacing: "0.06em", textTransform: "uppercase", padding: "3px 8px", background: "var(--input-bg)", borderRadius: "4px", marginRight: "8px" }}>{section.chartType.replace("_", " ")}</span>}
                <button onClick={() => moveSection(section.id, -1)} disabled={i === 0} title="Move up" style={{ background: "none", border: "none", color: i === 0 ? "var(--text-faint)" : "var(--text-muted)", cursor: i === 0 ? "default" : "pointer", fontSize: "14px", padding: "4px", transition: "color 0.2s" }}>{"\u2191"}</button>
                <button onClick={() => moveSection(section.id, 1)} disabled={i === sections.length - 1} title="Move down" style={{ background: "none", border: "none", color: i === sections.length - 1 ? "var(--text-faint)" : "var(--text-muted)", cursor: i === sections.length - 1 ? "default" : "pointer", fontSize: "14px", padding: "4px", transition: "color 0.2s" }}>{"\u2193"}</button>
                <button onClick={() => removeSection(section.id)} title="Remove" style={{ background: "none", border: "none", color: "var(--text-muted)", cursor: "pointer", fontSize: "14px", padding: "4px", transition: "color 0.2s" }} onMouseEnter={e => e.target.style.color = "#E87272"} onMouseLeave={e => e.target.style.color = "rgba(255,255,255,0.25)"}>{"\u2715"}</button>
              </div>
            </div>

            {/* Section Content Preview */}
            <div style={{ padding: "24px" }}>
              <div style={{ display: "grid", gridTemplateColumns: section.chartType ? "1fr 1fr" : "1fr", gap: "24px" }}>
                {/* Chart */}
                {section.chartType && section.chartData && (
                  <div style={{ background: "var(--bg-surface2)", border: "1px solid rgba(255,255,255,0.04)", borderRadius: "12px", padding: "20px" }}>
                    <ReportSectionChart section={section} />
                  </div>
                )}
                {/* Text Preview */}
                <div>
                  <p style={{ fontSize: "11px", fontWeight: 600, color: "var(--gold)", letterSpacing: "0.06em", textTransform: "uppercase", marginBottom: "10px" }}>{"\u2726"} AI Analysis</p>
                  {section.text.split("\n\n").map((para, pi) => (
                    <p key={pi} style={{ fontSize: "13px", color: "var(--text-tertiary)", lineHeight: 1.7, marginBottom: "12px" }}>{para}</p>
                  ))}
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Add More */}
      <div onClick={() => setShowAddModal(true)} style={{ marginTop: "16px", padding: "20px", borderRadius: "14px", border: "2px dashed rgba(255,255,255,0.08)", display: "flex", alignItems: "center", justifyContent: "center", gap: "8px", cursor: "pointer", color: "var(--text-muted)", fontSize: "13px", fontWeight: 500, transition: "all 0.2s" }}
        onMouseEnter={e => { e.currentTarget.style.borderColor = "rgba(232,200,114,0.2)"; e.currentTarget.style.color = "#E8C872"; }}
        onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--border)"; e.currentTarget.style.color = "var(--text-muted)"; }}
      >
        {"\u2795"} Add another section
      </div>

      {showAddModal && <AddSectionModal onClose={() => setShowAddModal(false)} onAdd={addSection} />}
    </div>
  );
};

/* ═══════════════════════════════════════════
   AI CHAT PANEL
   ═══════════════════════════════════════════ */

const STORE_CONTEXT = `You are an AI analytics assistant for a WooCommerce store. Answer using the store data. Use GBP. Revenue data: ${JSON.stringify(revenueData)}. Products: ${JSON.stringify(topProducts.map(p => ({ name: p.name, sold: p.sold, revenue: p.revenue, stock: p.stock, cat: p.cat })))}. Orders: ${JSON.stringify(allOrders.map(o => ({ id: o.id, customer: o.customer, total: o.total, status: o.status, date: o.date })))}. Customers: ${JSON.stringify(allCustomers.map(c => ({ name: c.name, orders: c.orders, spent: c.spent, tier: c.tier })))}. Total revenue: 162600. Orders: 1259. Customers: 876. Conversion: 3.8%. Weekly revenue: 37380 (Sat peak at 7210). Be concise.`;

const suggestedQuestions = ["What were my best sellers this month?", "Who are my top 3 customers?", "Which day had highest revenue?", "Which products are low on stock?", "Compare revenue to last year", "What is my refund rate?"];

const AIChatPanel = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [showSuggestions, setShowSuggestions] = useState(true);
  const endRef = useRef(null);
  const inputRef = useRef(null);

  useEffect(() => { endRef.current?.scrollIntoView({ behavior: "smooth" }); }, [messages]);
  useEffect(() => { if (isOpen) setTimeout(() => inputRef.current?.focus(), 300); }, [isOpen]);

  const sendMessage = async (text) => {
    if (!text.trim() || loading) return;
    const userMsg = { role: "user", content: text.trim() };
    setMessages(prev => [...prev, userMsg]);
    setInput(""); setShowSuggestions(false); setLoading(true);
    try {
      const history = [...messages, userMsg].map(m => ({ role: m.role, content: m.content }));
      const res = await fetch("https://api.openai.com/v1/responses", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model: "gpt-5-mini", max_output_tokens: 1000, input: [{ role: "system", content: [{ type: "input_text", text: STORE_CONTEXT }] }, ...history.map((m) => ({ role: m.role, content: [{ type: "input_text", text: m.content }] }))] }) });
      const data = await res.json();
      const aiText = data.output_text || data.output?.flatMap(item => item.content || []).map(block => block.type === "output_text" ? block.text : "").filter(Boolean).join("\n") || "Sorry, I couldn't process that.";
      setMessages(prev => [...prev, { role: "assistant", content: aiText }]);
    } catch { setMessages(prev => [...prev, { role: "assistant", content: "Connection issue. Please try again." }]); }
    finally { setLoading(false); }
  };

  return (
    <>
      <button onClick={() => setIsOpen(!isOpen)} style={{ position: "fixed", bottom: 28, right: 28, zIndex: 1000, width: 56, height: 56, borderRadius: "16px", border: "none", background: isOpen ? "rgba(255,255,255,0.1)" : "linear-gradient(135deg, #E8C872, #D4A843)", color: isOpen ? "#E8C872" : "#0F1117", fontSize: "22px", cursor: "pointer", boxShadow: isOpen ? "none" : "0 8px 32px rgba(232,200,114,0.35)", transition: "all 0.3s", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "inherit" }}>{isOpen ? "\u2715" : "\u2726"}</button>
      <div style={{ position: "fixed", bottom: 96, right: 28, zIndex: 999, width: 420, maxHeight: "calc(100vh - 140px)", background: "var(--modal-bg)", border: "1px solid var(--input-border)", borderRadius: "20px", boxShadow: "0 24px 80px rgba(0,0,0,0.6)", display: "flex", flexDirection: "column", transform: isOpen ? "translateY(0) scale(1)" : "translateY(16px) scale(0.95)", opacity: isOpen ? 1 : 0, pointerEvents: isOpen ? "auto" : "none", transition: "all 0.3s", overflow: "hidden" }}>
        <div style={{ padding: "20px 24px 16px", borderBottom: "1px solid var(--border)", background: "linear-gradient(180deg, rgba(232,200,114,0.06) 0%, transparent 100%)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: "10px", marginBottom: "4px" }}><div style={{ width: 28, height: 28, borderRadius: "8px", background: "linear-gradient(135deg, #E8C872, #D4A843)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "13px", fontWeight: 700, color: "#0F1117" }}>{"\u2726"}</div><h3 style={{ fontSize: "15px", fontWeight: 700, color: "var(--text-primary)" }}>Store AI Assistant</h3></div>
          <p style={{ fontSize: "12px", color: "var(--text-muted)", marginLeft: "38px" }}>Ask anything about your store data</p>
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: "16px 20px", display: "flex", flexDirection: "column", gap: "14px", minHeight: 200, maxHeight: 400 }}>
          {messages.length === 0 && !loading && <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", flex: 1, padding: "20px 0" }}><div style={{ fontSize: "32px", marginBottom: "12px", opacity: 0.6 }}>{"\u2726"}</div><p style={{ fontSize: "13px", color: "var(--text-muted)", textAlign: "center", lineHeight: 1.5, maxWidth: 260 }}>Ask me about your sales, customers, products, or any store metrics</p></div>}
          {messages.map((msg, i) => (<div key={i} style={{ display: "flex", justifyContent: msg.role === "user" ? "flex-end" : "flex-start", animation: "fadeUp 0.3s ease" }}><div style={{ maxWidth: "85%", padding: "12px 16px", borderRadius: msg.role === "user" ? "14px 14px 4px 14px" : "14px 14px 14px 4px", background: msg.role === "user" ? "linear-gradient(135deg, rgba(232,200,114,0.2), rgba(232,200,114,0.1))" : "rgba(255,255,255,0.04)", border: `1px solid ${msg.role === "user" ? "var(--chat-user-border)" : "var(--chat-ai-border)"}` }}>{msg.role === "assistant" && <div style={{ display: "flex", alignItems: "center", gap: "6px", marginBottom: "6px" }}><span style={{ fontSize: "10px", color: "var(--gold)" }}>{"\u2726"}</span><span style={{ fontSize: "10px", fontWeight: 600, color: "var(--text-muted)", letterSpacing: "0.06em", textTransform: "uppercase" }}>AI Assistant</span></div>}<p style={{ fontSize: "13px", lineHeight: 1.6, color: msg.role === "user" ? "rgba(255,255,255,0.9)" : "rgba(255,255,255,0.7)", whiteSpace: "pre-wrap", wordBreak: "break-word" }}>{msg.content}</p></div></div>))}
          {loading && <div style={{ display: "flex", justifyContent: "flex-start", animation: "fadeUp 0.3s ease" }}><div style={{ padding: "14px 20px", borderRadius: "14px 14px 14px 4px", background: "var(--input-bg)", border: "1px solid var(--border)", display: "flex", gap: "6px" }}>{[0, 1, 2].map(i => <div key={i} style={{ width: 7, height: 7, borderRadius: "50%", background: "#E8C872", animation: `pulse 1.2s ease-in-out ${i * 0.15}s infinite` }} />)}</div></div>}
          <div ref={endRef} />
        </div>
        {showSuggestions && messages.length === 0 && <div style={{ padding: "0 20px 12px", display: "flex", flexWrap: "wrap", gap: "6px" }}>{suggestedQuestions.map((q, i) => (<button key={i} onClick={() => sendMessage(q)} style={{ padding: "7px 12px", borderRadius: "8px", background: "var(--bg-surface)", border: "1px solid var(--border)", color: "var(--text-tertiary)", fontSize: "11px", fontWeight: 500, cursor: "pointer", transition: "all 0.2s", fontFamily: "inherit", lineHeight: 1.3 }} onMouseEnter={e => { e.target.style.borderColor = "rgba(232,200,114,0.25)"; e.target.style.color = "#E8C872"; }} onMouseLeave={e => { e.target.style.borderColor = "rgba(255,255,255,0.06)"; e.target.style.color = "var(--text-tertiary)"; }}>{q}</button>))}</div>}
        <div style={{ padding: "12px 16px 16px", borderTop: "1px solid rgba(255,255,255,0.06)", background: "var(--chat-input-bg)" }}>
          <div style={{ display: "flex", alignItems: "flex-end", gap: "10px", background: "var(--input-bg)", border: "1px solid var(--input-border)", borderRadius: "14px", padding: "4px 4px 4px 16px" }}>
            <textarea ref={inputRef} value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendMessage(input); } }} placeholder="Ask about your store..." rows={1} style={{ flex: 1, background: "none", border: "none", outline: "none", color: "var(--text-primary)", fontSize: "13px", fontFamily: "inherit", resize: "none", padding: "10px 0", lineHeight: 1.4, maxHeight: 80 }} />
            <button onClick={() => sendMessage(input)} disabled={!input.trim() || loading} style={{ width: 36, height: 36, borderRadius: "10px", border: "none", background: input.trim() && !loading ? "linear-gradient(135deg, #E8C872, #D4A843)" : "rgba(255,255,255,0.06)", color: input.trim() && !loading ? "#0F1117" : "rgba(255,255,255,0.2)", fontSize: "16px", cursor: input.trim() && !loading ? "pointer" : "default", transition: "all 0.2s", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>{"\u2191"}</button>
          </div>
          <p style={{ fontSize: "10px", color: "var(--text-faint)", textAlign: "center", marginTop: "8px" }}>Powered by AI \u00B7 Analysing your live store data</p>
        </div>
      </div>
    </>
  );
};

/* ═══════════════════════════════════════════
   MAIN APP SHELL
   ═══════════════════════════════════════════ */

export default function WooCommerceDashboard() {
  const [page, setPage] = useState("overview");
  const [detailId, setDetailId] = useState(null);
  const [dateRange, setDateRange] = useState("6m");
  const [loaded, setLoaded] = useState(false);
  const [theme, setTheme] = useState("dark");

  useEffect(() => { setTimeout(() => setLoaded(true), 100); }, []);

  const navigate = useCallback((target, id = null) => { setPage(target); setDetailId(id); window.scrollTo?.(0, 0); }, []);

  const activeTab = page === "order-detail" ? "orders" : page === "product-detail" ? "products" : page === "customer-detail" ? "customers" : page;

  const renderPage = () => {
    switch (page) {
      case "overview": return <OverviewPage navigate={navigate} />;
      case "orders": return <OrdersPage navigate={navigate} />;
      case "order-detail": return <OrderDetailPage navigate={navigate} detailId={detailId} />;
      case "products": return <ProductsPage navigate={navigate} />;
      case "product-detail": return <ProductDetailPage navigate={navigate} detailId={detailId} />;
      case "customers": return <CustomersPage navigate={navigate} />;
      case "customer-detail": return <CustomerDetailPage navigate={navigate} detailId={detailId} />;
      case "my-dashboard": return <MyDashboardPage />;
      case "reports": return <ReportsPage navigate={navigate} />;
      default: return <OverviewPage navigate={navigate} />;
    }
  };

  return (
    <div className={`woo-root ${theme}`} style={{ minHeight: "100vh", background: "var(--bg)", fontFamily: "'DM Sans', 'Segoe UI', sans-serif", color: "var(--text)", transition: "background 0.4s, color 0.4s" }}>
      <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Sora:wght@400;500;600;700;800&display=swap" rel="stylesheet" />
      <style>{`
        :root, .woo-root.dark {
          --bg: #0F1117;
          --bg-surface: rgba(255,255,255,0.04);
          --bg-surface2: rgba(255,255,255,0.02);
          --bg-hover: rgba(255,255,255,0.02);
          --border: rgba(255,255,255,0.06);
          --border-hover: rgba(232,200,114,0.15);
          --text: #E8E9ED;
          --text-primary: #fff;
          --text-secondary: rgba(255,255,255,0.7);
          --text-tertiary: rgba(255,255,255,0.4);
          --text-muted: rgba(255,255,255,0.25);
          --text-faint: rgba(255,255,255,0.15);
          --gold: #E8C872;
          --gold-dim: rgba(232,200,114,0.1);
          --gold-border: rgba(232,200,114,0.3);
          --gold-glow: rgba(232,200,114,0.25);
          --green: #72E8A8;
          --green-bg: rgba(114,232,168,0.12);
          --green-border: rgba(114,232,168,0.15);
          --blue: #72B4E8;
          --blue-bg: rgba(114,180,232,0.12);
          --red: #E87272;
          --red-bg: rgba(232,114,114,0.12);
          --purple: #B472E8;
          --purple-bg: rgba(180,114,232,0.12);
          --card-bg: linear-gradient(135deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0.01) 100%);
          --card-shadow: 0 8px 40px rgba(0,0,0,0.3);
          --card-inset: inset 0 1px 0 rgba(255,255,255,0.05);
          --tooltip-bg: #1A1D23;
          --ambient1: rgba(232,200,114,0.04);
          --ambient2: rgba(114,180,232,0.03);
          --scrollbar: rgba(255,255,255,0.1);
          --logo-text: #fff;
          --chat-user-bg: linear-gradient(135deg, rgba(232,200,114,0.2), rgba(232,200,114,0.1));
          --chat-user-border: rgba(232,200,114,0.15);
          --chat-ai-bg: rgba(255,255,255,0.04);
          --chat-ai-border: rgba(255,255,255,0.05);
          --chat-input-bg: rgba(0,0,0,0.2);
          --input-bg: rgba(255,255,255,0.04);
          --input-border: rgba(255,255,255,0.08);
          --chart-grid: rgba(255,255,255,0.04);
          --chart-axis: rgba(255,255,255,0.3);
          --modal-overlay: rgba(0,0,0,0.7);
          --modal-bg: #1A1D23;
          --avatar-gradient: linear-gradient(135deg, rgba(232,200,114,0.2), rgba(114,180,232,0.2));
        }
        .woo-root.light {
          --bg: #F4F5F7;
          --bg-surface: rgba(0,0,0,0.02);
          --bg-surface2: rgba(0,0,0,0.01);
          --bg-hover: rgba(0,0,0,0.02);
          --border: rgba(0,0,0,0.08);
          --border-hover: rgba(180,140,40,0.25);
          --text: #2D3142;
          --text-primary: #1A1D2B;
          --text-secondary: rgba(0,0,0,0.65);
          --text-tertiary: rgba(0,0,0,0.4);
          --text-muted: rgba(0,0,0,0.25);
          --text-faint: rgba(0,0,0,0.1);
          --gold: #B8942E;
          --gold-dim: rgba(184,148,46,0.08);
          --gold-border: rgba(184,148,46,0.3);
          --gold-glow: rgba(184,148,46,0.15);
          --green: #2A9D5C;
          --green-bg: rgba(42,157,92,0.1);
          --green-border: rgba(42,157,92,0.2);
          --blue: #3A7BC8;
          --blue-bg: rgba(58,123,200,0.1);
          --red: #D4453A;
          --red-bg: rgba(212,69,58,0.1);
          --purple: #8B5CC4;
          --purple-bg: rgba(139,92,196,0.1);
          --card-bg: linear-gradient(135deg, #FFFFFF 0%, #FAFBFC 100%);
          --card-shadow: 0 4px 24px rgba(0,0,0,0.06);
          --card-inset: inset 0 1px 0 rgba(255,255,255,0.8);
          --tooltip-bg: #FFFFFF;
          --ambient1: rgba(184,148,46,0.03);
          --ambient2: rgba(58,123,200,0.02);
          --scrollbar: rgba(0,0,0,0.12);
          --logo-text: #1A1D2B;
          --chat-user-bg: linear-gradient(135deg, rgba(184,148,46,0.12), rgba(184,148,46,0.06));
          --chat-user-border: rgba(184,148,46,0.2);
          --chat-ai-bg: rgba(0,0,0,0.02);
          --chat-ai-border: rgba(0,0,0,0.06);
          --chat-input-bg: rgba(0,0,0,0.03);
          --input-bg: rgba(0,0,0,0.03);
          --input-border: rgba(0,0,0,0.1);
          --chart-grid: rgba(0,0,0,0.06);
          --chart-axis: rgba(0,0,0,0.35);
          --modal-overlay: rgba(0,0,0,0.3);
          --modal-bg: #FFFFFF;
          --avatar-gradient: linear-gradient(135deg, rgba(184,148,46,0.15), rgba(58,123,200,0.1));
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: var(--scrollbar); border-radius: 3px; }
        @keyframes fadeUp { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
        @keyframes spin { to { transform: rotate(360deg); } }
        .card { background: var(--card-bg); border: 1px solid var(--border); border-radius: 16px; backdrop-filter: blur(20px); transition: all 0.3s cubic-bezier(0.4,0,0.2,1); }
        .card:hover { border-color: var(--border-hover); box-shadow: var(--card-shadow), var(--card-inset); }
        .nav-tab { padding: 8px 18px; border-radius: 8px; font-size: 13px; font-weight: 500; cursor: pointer; transition: all 0.2s; border: none; background: transparent; color: var(--text-tertiary); letter-spacing: 0.01em; font-family: inherit; }
        .nav-tab:hover { color: var(--text-secondary); background: var(--bg-surface); }
        .nav-tab.active { color: var(--gold); background: var(--gold-dim); }
        .date-btn { padding: 6px 14px; border-radius: 6px; font-size: 12px; font-weight: 600; cursor: pointer; transition: all 0.2s; border: 1px solid var(--border); background: transparent; color: var(--text-tertiary); letter-spacing: 0.03em; font-family: inherit; }
        .date-btn:hover { border-color: var(--text-muted); color: var(--text-secondary); }
        .date-btn.active { border-color: var(--gold-border); color: var(--gold); background: var(--gold-dim); }
        .table-row { transition: background 0.15s; } .table-row:hover { background: var(--bg-hover); }
        .link-btn { font-size: 12px; font-weight: 600; color: var(--gold); background: none; border: 1px solid var(--gold-border); padding: 6px 14px; border-radius: 6px; cursor: pointer; letter-spacing: 0.02em; font-family: inherit; transition: all 0.2s; }
        .link-btn:hover { background: var(--gold-dim); }
        .theme-toggle { width: 52px; height: 28px; border-radius: 14px; border: 1px solid var(--border); background: var(--bg-surface); cursor: pointer; position: relative; transition: all 0.3s; display: flex; align-items: center; padding: 0 3px; }
        .theme-toggle:hover { border-color: var(--gold-border); }
        .theme-toggle .thumb { width: 22px; height: 22px; border-radius: 11px; background: var(--gold); transition: all 0.3s cubic-bezier(0.4,0,0.2,1); display: flex; align-items: center; justify-content: center; font-size: 12px; box-shadow: 0 2px 8px var(--gold-glow); }
        .woo-root.dark .theme-toggle .thumb { transform: translateX(0); }
        .woo-root.light .theme-toggle .thumb { transform: translateX(22px); }
      `}</style>

      <div style={{ position: "fixed", inset: 0, pointerEvents: "none", zIndex: 0, background: "radial-gradient(ellipse 80% 50% at 20% 10%, var(--ambient1) 0%, transparent 60%), radial-gradient(ellipse 60% 40% at 80% 80%, var(--ambient2) 0%, transparent 50%)" }} />

      <header style={{ position: "relative", zIndex: 10, padding: "24px 40px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", justifyContent: "space-between", animation: loaded ? "fadeUp 0.6s ease" : "none" }}>
        <div style={{ display: "flex", alignItems: "center", gap: "20px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: "12px", cursor: "pointer" }} onClick={() => navigate("overview")}>
            <div style={{ width: 36, height: 36, borderRadius: "10px", background: "linear-gradient(135deg, #E8C872, #D4A843)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "16px", fontWeight: 700, color: "#0F1117", boxShadow: "0 4px 16px var(--gold-glow)" }}>W</div>
            <div><h1 style={{ fontFamily: "'Sora', sans-serif", fontSize: "20px", fontWeight: 700, letterSpacing: "-0.02em", color: "var(--logo-text)" }}>WooCommerce</h1><p style={{ fontSize: "11px", color: "var(--text-tertiary)", fontWeight: 500, letterSpacing: "0.08em", textTransform: "uppercase" }}>Analytics Dashboard</p></div>
          </div>
          <div style={{ width: 1, height: 32, background: "var(--border)", margin: "0 4px" }} />
          <nav style={{ display: "flex", gap: "4px" }}>
            {[["overview", "Overview"], ["orders", "Orders"], ["products", "Products"], ["customers", "Customers"], ["my-dashboard", "My Dashboard"], ["reports", "Reports"]].map(([key, label]) => (
              <button key={key} className={`nav-tab ${activeTab === key ? "active" : ""}`} onClick={() => navigate(key)}>
                {key === "my-dashboard" && <span style={{ marginRight: "4px" }}>{"\u2728"}</span>}{key === "reports" && <span style={{ marginRight: "4px" }}>{"\u{1F4DD}"}</span>}{label}
              </button>
            ))}
          </nav>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: "16px" }}>
          {page === "overview" && <div style={{ display: "flex", gap: "4px" }}>{[["7d", "7D"], ["1m", "1M"], ["3m", "3M"], ["6m", "6M"], ["1y", "1Y"]].map(([v, l]) => (<button key={v} className={`date-btn ${dateRange === v ? "active" : ""}`} onClick={() => setDateRange(v)}>{l}</button>))}</div>}
          <div style={{ display: "flex", alignItems: "center", gap: "8px", padding: "6px 14px", borderRadius: "8px", background: "var(--green-bg)", border: "1px solid var(--green-border)" }}>
            <div style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--green)", animation: "pulse 2s infinite" }} />
            <span style={{ fontSize: "12px", color: "var(--green)", fontWeight: 600 }}>Store Live</span>
          </div>
          <button className="theme-toggle" onClick={() => setTheme(t => t === "dark" ? "light" : "dark")} title={theme === "dark" ? "Switch to light mode" : "Switch to dark mode"}>
            <div className="thumb">{theme === "dark" ? "\u{1F319}" : "\u2600\uFE0F"}</div>
          </button>
        </div>
      </header>

      <main style={{ position: "relative", zIndex: 10, padding: "28px 40px 40px", maxWidth: 1440, margin: "0 auto" }}>
        {renderPage()}
      </main>

      <AIChatPanel />
    </div>
  );
}
