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: "🎧", 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: "✨", 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: "🪵", 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: "💡", 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: "☕", 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: "🧢", 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: "🫖", 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: "🔊", cat: "Electronics", rating: 4.3, reviews: 156 },
];

const categoryData = [
  { name: "Electronics", value: 38, color: "#E8C872" },
  { name: "Beauty", value: 24, color: "#72B4E8" },
  { name: "Home", value: 18, color: "#E87272" },
  { name: "Food & Drink", value: 12, color: "#72E8A8" },
  { 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" },
  { id: "#WC-4811", customer: "Maria Rossi", custId: "C010", email: "m.rossi@posta.it", items: 4, products: ["Premium Wireless Headphones", "Organic Face Serum 30ml", "Smart LED Strip Kit", "Ceramic Pour-Over Set"], total: 289.96, status: "completed", time: "2 days ago", date: "Feb 26, 2026", method: "Credit Card", shipping: "Express" },
  { id: "#WC-4808", customer: "Maria Rossi", custId: "C010", email: "m.rossi@posta.it", items: 3, products: ["Bamboo Desk Organizer", "Artisan Coffee Blend 500g", "Bluetooth Speaker Mini"], total: 124.97, status: "completed", time: "4 days ago", date: "Feb 24, 2026", method: "Credit Card", shipping: "Standard" },
  { id: "#WC-4802", customer: "Maria Rossi", custId: "C010", email: "m.rossi@posta.it", items: 2, products: ["Premium Wireless Headphones", "Merino Wool Beanie"], total: 114.98, status: "completed", time: "6 days ago", date: "Feb 22, 2026", method: "Apple Pay", shipping: "Express" },
];

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 },
];

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

const AnimatedNumber = ({ value, prefix = "", suffix = "", decimals = 0 }) => {
  const [display, setDisplay] = useState(0);
  useEffect(() => {
    const duration = 1000;
    const start = performance.now();
    const step = (now) => {
      const p = Math.min((now - start) / duration, 1);
      const eased = 1 - Math.pow(1 - p, 3);
      setDisplay(value * eased);
      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: "#72E8A8", label: "Completed" },
    processing: { bg: "rgba(114,180,232,0.12)", color: "#72B4E8", label: "Processing" },
    "on-hold": { bg: "rgba(232,200,114,0.12)", color: "#E8C872", label: "On Hold" },
    refunded: { bg: "rgba(232,114,114,0.12)", color: "#E87272", 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: "#1A1D23", border: "1px solid rgba(255,255,255,0.08)", borderRadius: "10px", padding: "12px 16px", boxShadow: "0 8px 32px rgba(0,0,0,0.4)" }}>
      <p style={{ color: "rgba(255,255,255,0.5)", 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 ? `£${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: "rgba(255,255,255,0.4)", fontSize: "13px", fontWeight: 500, cursor: "pointer",
    padding: "6px 0", marginBottom: "16px", transition: "color 0.2s",
    fontFamily: "inherit",
  }}
    onMouseEnter={e => e.target.style.color = "#E8C872"}
    onMouseLeave={e => e.target.style.color = "rgba(255,255,255,0.4)"}
  >
    ← {label}
  </button>
);

const DetailRow = ({ label, value, accent }) => (
  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "12px 0", borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
    <span style={{ fontSize: "13px", color: "rgba(255,255,255,0.4)", fontWeight: 500 }}>{label}</span>
    <span style={{ fontSize: "13px", color: accent || "#fff", fontWeight: 600 }}>{value}</span>
  </div>
);

const SectionTitle = ({ title, sub }) => (
  <div style={{ marginBottom: "20px" }}>
    <h2 style={{ fontFamily: "'Playfair Display', serif", fontSize: "24px", fontWeight: 700, color: "#fff", letterSpacing: "-0.02em" }}>{title}</h2>
    {sub && <p style={{ fontSize: "13px", color: "rgba(255,255,255,0.35)", 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>
);

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

const OverviewPage = ({ navigate }) => {
  const kpis = [
    { label: "Total Revenue", value: 162600, prefix: "£", change: +18.4, icon: "💰", sub: "vs £137,300 last period" },
    { label: "Orders", value: 1259, change: +12.1, icon: "📦", sub: "Avg. £129.15 per order" },
    { label: "Customers", value: 876, change: +24.6, icon: "👥", sub: "134 new this month" },
    { label: "Conversion Rate", value: 3.8, suffix: "%", change: +0.6, icon: "🎯", sub: "From 11,240 visitors" },
  ];

  return (
    <>
      {/* KPIs */}
      <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: "pointer" }}
            onClick={() => {
              if (i === 1) navigate("orders");
              else if (i === 2) navigate("customers");
            }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: "14px" }}>
              <span style={{ fontSize: "12px", fontWeight: 600, color: "rgba(255,255,255,0.4)", letterSpacing: "0.06em", textTransform: "uppercase" }}>{kpi.label}</span>
              <span style={{ fontSize: "20px" }}>{kpi.icon}</span>
            </div>
            <div style={{ fontSize: "32px", fontWeight: 700, color: "#fff", 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 ? "↑" : "↓"} {Math.abs(kpi.change)}%
              </span>
              <span style={{ fontSize: "11px", color: "rgba(255,255,255,0.3)" }}>{kpi.sub}</span>
            </div>
          </div>
        ))}
      </div>

      {/* Revenue + Category Row */}
      <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: "#fff", marginBottom: "4px" }}>Revenue Overview</h3>
              <p style={{ fontSize: "12px", color: "rgba(255,255,255,0.35)" }}>Monthly revenue compared to 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: "rgba(255,255,255,0.4)" }}>{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="rgba(255,255,255,0.04)" />
              <XAxis dataKey="month" tick={{ fontSize: 11, fill: "rgba(255,255,255,0.3)" }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fontSize: 11, fill: "rgba(255,255,255,0.3)" }} axisLine={false} tickLine={false} tickFormatter={v => `£${(v/1000).toFixed(0)}k`} />
              <Tooltip content={<CustomTooltip />} />
              <Area type="monotone" dataKey="lastYear" stroke="rgba(255,255,255,0.15)" 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: "#fff", marginBottom: "4px" }}>Sales by Category</h3>
          <p style={{ fontSize: "12px", color: "rgba(255,255,255,0.35)", 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: "rgba(255,255,255,0.6)" }}>{cat.name}</Clickable>
                </div>
                <span style={{ fontSize: "13px", fontWeight: 600, color: "rgba(255,255,255,0.8)" }}>{cat.value}%</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Daily Revenue + Customer Growth */}
      <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: "#fff", marginBottom: "4px" }}>This Week's Revenue</h3>
          <p style={{ fontSize: "12px", color: "rgba(255,255,255,0.35)", marginBottom: "24px" }}>Daily breakdown — £37,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="rgba(255,255,255,0.04)" vertical={false} />
              <XAxis dataKey="day" tick={{ fontSize: 11, fill: "rgba(255,255,255,0.3)" }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fontSize: 11, fill: "rgba(255,255,255,0.3)" }} axisLine={false} tickLine={false} tickFormatter={v => `£${(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: "#fff", marginBottom: "4px" }}>Customer Growth</h3>
              <p style={{ fontSize: "12px", color: "rgba(255,255,255,0.35)" }}>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: "rgba(255,255,255,0.4)" }}>{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="rgba(255,255,255,0.04)" />
              <XAxis dataKey="month" tick={{ fontSize: 11, fill: "rgba(255,255,255,0.3)" }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fontSize: 11, fill: "rgba(255,255,255,0.3)" }} 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>

      {/* Recent Orders + Top Products */}
      <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: "#fff", marginBottom: "4px" }}>Recent Orders</h3>
              <p style={{ fontSize: "12px", color: "rgba(255,255,255,0.35)" }}>Latest transactions</p>
            </div>
            <button onClick={() => navigate("orders")} className="link-btn">View All →</button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "80px 1fr 80px 90px 80px", padding: "0 0 10px", borderBottom: "1px solid rgba(255,255,255,0.05)", fontSize: "10px", fontWeight: 600, color: "rgba(255,255,255,0.25)", letterSpacing: "0.08em", textTransform: "uppercase" }}>
            <span>Order</span><span>Customer</span><span>Total</span><span>Status</span><span>Time</span>
          </div>
          {allOrders.slice(0, 6).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 < 5 ? "1px solid rgba(255,255,255,0.03)" : "none" }}>
              <Clickable onClick={() => navigate("order-detail", o.id)} style={{ fontSize: "12px", fontWeight: 600, color: "#E8C872" }}>{o.id}</Clickable>
              <Clickable onClick={() => navigate("customer-detail", o.custId)} style={{ fontSize: "13px", color: "rgba(255,255,255,0.7)" }}>{o.customer}</Clickable>
              <span style={{ fontSize: "13px", fontWeight: 600, color: "#fff" }}>{`£${o.total.toFixed(2)}`}</span>
              <StatusBadge status={o.status} />
              <span style={{ fontSize: "11px", color: "rgba(255,255,255,0.3)" }}>{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: "#fff", marginBottom: "4px" }}>Top Products</h3>
              <p style={{ fontSize: "12px", color: "rgba(255,255,255,0.35)" }}>Best performers this period</p>
            </div>
            <button onClick={() => navigate("products")} className="link-btn">View All →</button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "28px 1fr 60px 85px 60px", padding: "0 0 10px", borderBottom: "1px solid rgba(255,255,255,0.05)", fontSize: "10px", fontWeight: 600, color: "rgba(255,255,255,0.25)", 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: "rgba(255,255,255,0.8)", fontWeight: 500 }}>{p.name}</Clickable>
              <span style={{ fontSize: "13px", color: "rgba(255,255,255,0.5)" }}>{p.sold}</span>
              <span style={{ fontSize: "13px", fontWeight: 600, color: "#fff" }}>{`£${p.revenue.toLocaleString()}`}</span>
              <span style={{ fontSize: "12px", fontWeight: 600, color: p.trend > 0 ? "#72E8A8" : "#E87272" }}>{p.trend > 0 ? "↑" : "↓"}{Math.abs(p.trend)}%</span>
            </div>
          ))}
        </div>
      </div>
    </>
  );
};

/* ═══════════════════════════════════════════
   PAGE: ALL ORDERS
   ═══════════════════════════════════════════ */

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 — £${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("-", " ")} <span style={{ opacity: 0.5, marginLeft: 4 }}>({counts[f] || 0})</span>
          </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 rgba(255,255,255,0.06)", fontSize: "10px", fontWeight: 600, color: "rgba(255,255,255,0.3)", 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 rgba(255,255,255,0.03)" }}>
            <Clickable onClick={() => navigate("order-detail", o.id)} style={{ fontSize: "13px", fontWeight: 600, color: "#E8C872" }}>{o.id}</Clickable>
            <Clickable onClick={() => navigate("customer-detail", o.custId)} style={{ fontSize: "13px", color: "rgba(255,255,255,0.7)" }}>{o.customer}</Clickable>
            <span style={{ fontSize: "12px", color: "rgba(255,255,255,0.35)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{o.email}</span>
            <span style={{ fontSize: "13px", color: "rgba(255,255,255,0.5)", textAlign: "center" }}>{o.items}</span>
            <span style={{ fontSize: "13px", fontWeight: 600, color: "#fff" }}>{`£${o.total.toFixed(2)}`}</span>
            <StatusBadge status={o.status} />
            <span style={{ fontSize: "11px", color: "rgba(255,255,255,0.3)" }}>{o.date}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

/* ═══════════════════════════════════════════
   PAGE: ORDER DETAIL
   ═══════════════════════════════════════════ */

const OrderDetailPage = ({ navigate, detailId }) => {
  const order = allOrders.find(o => o.id === detailId);
  if (!order) return <div style={{ color: "#fff" }}>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: "'Playfair Display', serif", fontSize: "28px", fontWeight: 700, color: "#fff" }}>{order.id}</h2>
        <StatusBadge status={order.status} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "16px", marginBottom: "16px" }}>
        {/* Order Info */}
        <div className="card" style={{ padding: "24px" }}>
          <h4 style={{ fontSize: "12px", fontWeight: 600, color: "rgba(255,255,255,0.35)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: "16px" }}>Order Details</h4>
          <DetailRow label="Date" value={order.date} />
          <DetailRow label="Time" value={order.time} />
          <DetailRow label="Payment" value={order.method} />
          <DetailRow label="Shipping" value={order.shipping} />
          <DetailRow label="Total" value={`£${order.total.toFixed(2)}`} accent="#E8C872" />
        </div>

        {/* Customer Info */}
        <div className="card" style={{ padding: "24px" }}>
          <h4 style={{ fontSize: "12px", fontWeight: 600, color: "rgba(255,255,255,0.35)", 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: "#E8C872" }}>
              {order.customer.split(" ").map(n => n[0]).join("")}
            </div>
            <div>
              <Clickable onClick={() => navigate("customer-detail", order.custId)} style={{ fontSize: "15px", fontWeight: 600, color: "#fff" }}>{order.customer}</Clickable>
              <p style={{ fontSize: "12px", color: "rgba(255,255,255,0.35)", marginTop: "2px" }}>{order.email}</p>
            </div>
          </div>
          <DetailRow label="Customer ID" value={order.custId} />
        </div>

        {/* Items */}
        <div className="card" style={{ padding: "24px" }}>
          <h4 style={{ fontSize: "12px", fontWeight: 600, color: "rgba(255,255,255,0.35)", 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 || "📦"}</span>
                <div style={{ flex: 1 }}>
                  <Clickable onClick={() => prod && navigate("product-detail", prod.id)} style={{ fontSize: "13px", color: "rgba(255,255,255,0.8)", fontWeight: 500 }}>{pName}</Clickable>
                  {prod && <p style={{ fontSize: "11px", color: "rgba(255,255,255,0.3)", marginTop: "2px" }}>{`£${prod.price.toFixed(2)}`}</p>}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Timeline */}
      <div className="card" style={{ padding: "24px" }}>
        <h4 style={{ fontSize: "12px", fontWeight: 600, color: "rgba(255,255,255,0.35)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: "20px" }}>Order Timeline</h4>
        <div style={{ display: "flex", flexDirection: "column", gap: "0", position: "relative", paddingLeft: "24px" }}>
          <div style={{ position: "absolute", left: "6px", top: "8px", bottom: "8px", width: "1px", background: "rgba(255,255,255,0.06)" }} />
          {[
            { label: "Order placed", time: order.date, color: "#72E8A8", active: true },
            { label: "Payment confirmed", time: order.date, color: "#72B4E8", active: order.status !== "on-hold" },
            { label: "Shipped", time: order.status === "completed" ? order.date : "Pending", color: "#E8C872", active: order.status === "completed" },
            { label: "Delivered", time: order.status === "completed" ? order.date : "Pending", color: "#B472E8", active: order.status === "completed" },
          ].map((step, i) => (
            <div key={i} style={{ display: "flex", alignItems: "flex-start", gap: "14px", padding: "12px 0", position: "relative" }}>
              <div style={{ width: 13, height: 13, borderRadius: "50%", background: step.active ? step.color : "rgba(255,255,255,0.08)", border: `2px solid ${step.active ? step.color : "rgba(255,255,255,0.1)"}`, position: "absolute", left: "-24px", top: "14px", zIndex: 1 }} />
              <div>
                <p style={{ fontSize: "13px", fontWeight: 600, color: step.active ? "#fff" : "rgba(255,255,255,0.25)" }}>{step.label}</p>
                <p style={{ fontSize: "11px", color: "rgba(255,255,255,0.3)", marginTop: "2px" }}>{step.time}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

/* ═══════════════════════════════════════════
   PAGE: ALL PRODUCTS
   ═══════════════════════════════════════════ */

const ProductsPage = ({ navigate }) => (
  <div style={{ animation: "fadeUp 0.5s ease" }}>
    <SectionTitle title="Products" sub={`${topProducts.length} products — £${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: "#fff", marginBottom: "4px", lineHeight: 1.3 }}>{p.name}</h4>
          <p style={{ fontSize: "11px", color: "rgba(255,255,255,0.3)", marginBottom: "14px" }}>{p.cat} · {p.sku}</p>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <span style={{ fontSize: "20px", fontWeight: 700, color: "#E8C872" }}>{`£${p.price}`}</span>
            <span style={{ fontSize: "12px", fontWeight: 600, color: p.trend > 0 ? "#72E8A8" : "#E87272" }}>{p.trend > 0 ? "↑" : "↓"}{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: "rgba(255,255,255,0.3)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Sold</p><p style={{ fontSize: "14px", fontWeight: 600, color: "#fff" }}>{p.sold}</p></div>
            <div><p style={{ fontSize: "10px", color: "rgba(255,255,255,0.3)", 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: "rgba(255,255,255,0.3)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Rating</p><p style={{ fontSize: "14px", fontWeight: 600, color: "#fff" }}>⭐ {p.rating}</p></div>
          </div>
        </div>
      ))}
    </div>
  </div>
);

/* ═══════════════════════════════════════════
   PAGE: PRODUCT DETAIL
   ═══════════════════════════════════════════ */

const ProductDetailPage = ({ navigate, detailId }) => {
  const product = topProducts.find(p => p.id === detailId);
  if (!product) return <div style={{ color: "#fff" }}>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: "'Playfair Display', serif", fontSize: "26px", fontWeight: 700, color: "#fff" }}>{product.name}</h2>
          <p style={{ fontSize: "13px", color: "rgba(255,255,255,0.35)", marginTop: "4px" }}>{product.cat} · SKU: {product.sku}</p>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "16px", marginBottom: "16px" }}>
        {[
          { label: "Price", value: `£${product.price}`, icon: "💷" },
          { label: "Units Sold", value: product.sold, icon: "📊" },
          { label: "Revenue", value: `£${product.revenue.toLocaleString()}`, icon: "💰" },
          { label: "In Stock", value: product.stock, icon: "📦" },
        ].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: "rgba(255,255,255,0.35)", letterSpacing: "0.06em", textTransform: "uppercase" }}>{s.label}</span>
              <span style={{ fontSize: "16px" }}>{s.icon}</span>
            </div>
            <span style={{ fontSize: "24px", fontWeight: 700, color: "#fff" }}>{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: "#fff", 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="pSalesG" 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="rgba(255,255,255,0.04)" />
              <XAxis dataKey="week" tick={{ fontSize: 11, fill: "rgba(255,255,255,0.3)" }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fontSize: 11, fill: "rgba(255,255,255,0.3)" }} axisLine={false} tickLine={false} />
              <Tooltip content={<CustomTooltip />} />
              <Area type="monotone" dataKey="units" stroke="#E8C872" strokeWidth={2} fill="url(#pSalesG)" 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: "#fff", marginBottom: "16px" }}>Product Details</h4>
          <DetailRow label="Category" value={product.cat} />
          <DetailRow label="SKU" value={product.sku} />
          <DetailRow label="Rating" value={`⭐ ${product.rating} (${product.reviews} reviews)`} />
          <DetailRow label="Trend" value={`${product.trend > 0 ? "↑" : "↓"} ${Math.abs(product.trend)}%`} accent={product.trend > 0 ? "#72E8A8" : "#E87272"} />
          <DetailRow label="Stock Status" value={product.stock < 70 ? "Low Stock" : "In Stock"} accent={product.stock < 70 ? "#E87272" : "#72E8A8"} />
        </div>
      </div>

      <div className="card" style={{ padding: "24px" }}>
        <h4 style={{ fontSize: "13px", fontWeight: 600, color: "#fff", marginBottom: "16px" }}>Recent Orders Containing This Product ({relatedOrders.length})</h4>
        {relatedOrders.length === 0 ? <p style={{ color: "rgba(255,255,255,0.3)", fontSize: "13px" }}>No recent orders</p> : (
          <div>
            <div style={{ display: "grid", gridTemplateColumns: "90px 1fr 90px 100px 90px", padding: "0 0 10px", borderBottom: "1px solid rgba(255,255,255,0.05)", fontSize: "10px", fontWeight: 600, color: "rgba(255,255,255,0.25)", letterSpacing: "0.08em", textTransform: "uppercase" }}>
              <span>Order</span><span>Customer</span><span>Total</span><span>Status</span><span>Date</span>
            </div>
            {relatedOrders.map((o, i) => (
              <div key={i} className="table-row" style={{ display: "grid", gridTemplateColumns: "90px 1fr 90px 100px 90px", padding: "12px 0", alignItems: "center", borderBottom: "1px solid rgba(255,255,255,0.03)" }}>
                <Clickable onClick={() => navigate("order-detail", o.id)} style={{ fontSize: "13px", fontWeight: 600, color: "#E8C872" }}>{o.id}</Clickable>
                <Clickable onClick={() => navigate("customer-detail", o.custId)} style={{ fontSize: "13px", color: "rgba(255,255,255,0.7)" }}>{o.customer}</Clickable>
                <span style={{ fontSize: "13px", fontWeight: 600, color: "#fff" }}>{`£${o.total.toFixed(2)}`}</span>
                <StatusBadge status={o.status} />
                <span style={{ fontSize: "11px", color: "rgba(255,255,255,0.3)" }}>{o.date}</span>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

/* ═══════════════════════════════════════════
   PAGE: ALL CUSTOMERS
   ═══════════════════════════════════════════ */

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} registered customers — £${allCustomers.reduce((s, c) => s + c.spent, 0).toLocaleString(undefined, { minimumFractionDigits: 2 })} total 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" }}>
        <div style={{ display: "grid", gridTemplateColumns: "50px 1fr 160px 80px 100px 80px 100px", padding: "14px 24px", borderBottom: "1px solid rgba(255,255,255,0.06)", fontSize: "10px", fontWeight: 600, color: "rgba(255,255,255,0.3)", letterSpacing: "0.08em", textTransform: "uppercase" }}>
          <span></span><span>Name</span><span>Email</span><span>Orders</span><span>Total Spent</span><span>Tier</span><span>Last Order</span>
        </div>
        {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 rgba(255,255,255,0.03)", 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: "#fff" }}>{c.name}</span>
              <p style={{ fontSize: "11px", color: "rgba(255,255,255,0.25)", marginTop: "1px" }}>{c.city} · Joined {c.joined}</p>
            </div>
            <span style={{ fontSize: "12px", color: "rgba(255,255,255,0.35)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.email}</span>
            <span style={{ fontSize: "13px", fontWeight: 600, color: "#fff", textAlign: "center" }}>{c.orders}</span>
            <span style={{ fontSize: "13px", fontWeight: 600, color: "#E8C872" }}>{`£${c.spent.toLocaleString(undefined, { minimumFractionDigits: 2 })}`}</span>
            <TierBadge tier={c.tier} />
            <span style={{ fontSize: "11px", color: "rgba(255,255,255,0.3)" }}>{c.lastOrder}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

/* ═══════════════════════════════════════════
   PAGE: CUSTOMER DETAIL
   ═══════════════════════════════════════════ */

const CustomerDetailPage = ({ navigate, detailId }) => {
  const customer = allCustomers.find(c => c.id === detailId);
  if (!customer) return <div style={{ color: "#fff" }}>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: "'Playfair Display', serif", fontSize: "26px", fontWeight: 700, color: "#fff" }}>{customer.name}</h2>
            <TierBadge tier={customer.tier} />
          </div>
          <p style={{ fontSize: "13px", color: "rgba(255,255,255,0.35)", marginTop: "4px" }}>{customer.email} · {customer.city}</p>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "16px", marginBottom: "16px" }}>
        {[
          { label: "Total Spent", value: `£${customer.spent.toLocaleString(undefined, { minimumFractionDigits: 2 })}`, icon: "💰" },
          { label: "Orders", value: customer.orders, icon: "📦" },
          { label: "Avg. Order", value: `£${(customer.spent / customer.orders).toFixed(2)}`, icon: "📊" },
          { label: "Member Since", value: customer.joined, icon: "📅" },
        ].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: "rgba(255,255,255,0.35)", letterSpacing: "0.06em", textTransform: "uppercase" }}>{s.label}</span>
              <span style={{ fontSize: "16px" }}>{s.icon}</span>
            </div>
            <span style={{ fontSize: "24px", fontWeight: 700, color: "#fff" }}>{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: "#fff", 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="rgba(255,255,255,0.04)" vertical={false} />
              <XAxis dataKey="month" tick={{ fontSize: 11, fill: "rgba(255,255,255,0.3)" }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fontSize: 11, fill: "rgba(255,255,255,0.3)" }} axisLine={false} tickLine={false} tickFormatter={v => `£${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: "#fff", marginBottom: "16px" }}>Customer Profile</h4>
          <DetailRow label="Customer 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>

      <div className="card" style={{ padding: "24px" }}>
        <h4 style={{ fontSize: "13px", fontWeight: 600, color: "#fff", marginBottom: "16px" }}>Order History ({custOrders.length} orders found in recent data)</h4>
        {custOrders.length === 0 ? <p style={{ color: "rgba(255,255,255,0.3)", fontSize: "13px" }}>No recent orders in current dataset</p> : (
          <div>
            <div style={{ display: "grid", gridTemplateColumns: "90px 80px 1fr 90px 100px", padding: "0 0 10px", borderBottom: "1px solid rgba(255,255,255,0.05)", fontSize: "10px", fontWeight: 600, color: "rgba(255,255,255,0.25)", letterSpacing: "0.08em", textTransform: "uppercase" }}>
              <span>Order</span><span>Items</span><span>Products</span><span>Total</span><span>Status</span>
            </div>
            {custOrders.map((o, i) => (
              <div key={i} className="table-row" style={{ display: "grid", gridTemplateColumns: "90px 80px 1fr 90px 100px", padding: "12px 0", alignItems: "center", borderBottom: "1px solid rgba(255,255,255,0.03)" }}>
                <Clickable onClick={() => navigate("order-detail", o.id)} style={{ fontSize: "13px", fontWeight: 600, color: "#E8C872" }}>{o.id}</Clickable>
                <span style={{ fontSize: "13px", color: "rgba(255,255,255,0.5)", textAlign: "center" }}>{o.items}</span>
                <span style={{ fontSize: "12px", color: "rgba(255,255,255,0.5)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{o.products.join(", ")}</span>
                <span style={{ fontSize: "13px", fontWeight: 600, color: "#fff" }}>{`£${o.total.toFixed(2)}`}</span>
                <StatusBadge status={o.status} />
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

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

const STORE_CONTEXT = `You are an AI analytics assistant embedded inside a WooCommerce store dashboard. Answer questions about the store's data concisely and helpfully. Use £ for all currency. Here is the store data:

REVENUE BY MONTH:
${JSON.stringify(revenueData)}

DAILY REVENUE (this week):
${JSON.stringify(dailyRevenue)}

PRODUCTS:
${JSON.stringify(topProducts)}

CATEGORIES:
${JSON.stringify(categoryData)}

ORDERS:
${JSON.stringify(allOrders)}

CUSTOMERS:
${JSON.stringify(allCustomers)}

CUSTOMER GROWTH:
${JSON.stringify(customerGrowth)}

Key metrics: Total revenue £162,600 (+18.4% YoY). 1,259 orders. 876 customers. 3.8% conversion rate from 11,240 visitors. This week's revenue £37,380 with Saturday being peak at £7,210.

When answering:
- Be specific with numbers, names and £ amounts
- Reference actual product names, customer names, order IDs from the data
- Keep answers concise (2-4 sentences for simple questions, more for complex analysis)
- If asked about dates, use the order dates available in the data
- Format numbers nicely and always use £ for currency`;

const suggestedQuestions = [
  "What were my best sellers this month?",
  "Who are my top 3 customers by spend?",
  "Which day had the highest revenue this week?",
  "How is my conversion rate trending?",
  "Which products are low on stock?",
  "Compare this year's revenue to last year",
];

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 messagesEndRef = useRef(null);
  const inputRef = useRef(null);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  useEffect(() => {
    if (isOpen && inputRef.current) {
      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 conversationHistory = [...messages, userMsg].map(m => ({
        role: m.role, content: m.content
      }));

      const response = 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 }],
            },
            ...conversationHistory.map((m) => ({
              role: m.role,
              content: [{ type: "input_text", text: m.content }],
            })),
          ],
        }),
      });

      const data = await response.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 request. Please try again.";
      setMessages(prev => [...prev, { role: "assistant", content: aiText }]);
    } catch (err) {
      setMessages(prev => [...prev, { role: "assistant", content: "I'm having trouble connecting right now. Please try again in a moment." }]);
    } finally {
      setLoading(false);
    }
  };

  const handleKeyDown = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      sendMessage(input);
    }
  };

  return (
    <>
      {/* Floating Button */}
      <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 cubic-bezier(0.4,0,0.2,1)",
          display: "flex", alignItems: "center", justifyContent: "center",
          fontFamily: "inherit",
        }}
      >
        {isOpen ? "✕" : "✦"}
      </button>

      {/* Chat Panel */}
      <div style={{
        position: "fixed", bottom: 96, right: 28, zIndex: 999,
        width: 420, maxHeight: "calc(100vh - 140px)",
        background: "#14161C",
        border: "1px solid rgba(255,255,255,0.08)",
        borderRadius: "20px",
        boxShadow: "0 24px 80px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.03)",
        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 cubic-bezier(0.4,0,0.2,1)",
        overflow: "hidden",
      }}>
        {/* Chat Header */}
        <div style={{
          padding: "20px 24px 16px",
          borderBottom: "1px solid rgba(255,255,255,0.06)",
          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",
            }}>✦</div>
            <h3 style={{ fontSize: "15px", fontWeight: 700, color: "#fff", letterSpacing: "-0.01em" }}>Store AI Assistant</h3>
          </div>
          <p style={{ fontSize: "12px", color: "rgba(255,255,255,0.35)", marginLeft: "38px" }}>Ask anything about your store data</p>
        </div>

        {/* Messages Area */}
        <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 }}>✦</div>
              <p style={{ fontSize: "13px", color: "rgba(255,255,255,0.3)", 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" ? "rgba(232,200,114,0.15)" : "rgba(255,255,255,0.05)"}`,
              }}>
                {msg.role === "assistant" && (
                  <div style={{ display: "flex", alignItems: "center", gap: "6px", marginBottom: "6px" }}>
                    <span style={{ fontSize: "10px", color: "#E8C872" }}>✦</span>
                    <span style={{ fontSize: "10px", fontWeight: 600, color: "rgba(255,255,255,0.3)", 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: "rgba(255,255,255,0.04)",
                border: "1px solid rgba(255,255,255,0.05)",
                display: "flex", alignItems: "center", 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={messagesEndRef} />
        </div>

        {/* Suggestions */}
        {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: "rgba(255,255,255,0.03)",
                border: "1px solid rgba(255,255,255,0.06)",
                color: "rgba(255,255,255,0.5)",
                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"; e.target.style.background = "rgba(232,200,114,0.05)"; }}
                onMouseLeave={e => { e.target.style.borderColor = "rgba(255,255,255,0.06)"; e.target.style.color = "rgba(255,255,255,0.5)"; e.target.style.background = "rgba(255,255,255,0.03)"; }}
              >
                {q}
              </button>
            ))}
          </div>
        )}

        {/* Input Area */}
        <div style={{
          padding: "12px 16px 16px",
          borderTop: "1px solid rgba(255,255,255,0.06)",
          background: "rgba(0,0,0,0.2)",
        }}>
          <div style={{
            display: "flex", alignItems: "flex-end", gap: "10px",
            background: "rgba(255,255,255,0.04)",
            border: "1px solid rgba(255,255,255,0.08)",
            borderRadius: "14px",
            padding: "4px 4px 4px 16px",
            transition: "border-color 0.2s",
          }}>
            <textarea
              ref={inputRef}
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder="Ask about your store..."
              rows={1}
              style={{
                flex: 1, background: "none", border: "none", outline: "none",
                color: "#fff", fontSize: "13px", fontFamily: "inherit",
                resize: "none", padding: "10px 0", lineHeight: 1.4,
                maxHeight: 80, overflowY: "auto",
              }}
              onInput={e => {
                e.target.style.height = "auto";
                e.target.style.height = Math.min(e.target.scrollHeight, 80) + "px";
              }}
            />
            <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,
              }}
            >
              ↑
            </button>
          </div>
          <p style={{ fontSize: "10px", color: "rgba(255,255,255,0.2)", textAlign: "center", marginTop: "8px" }}>
            Powered by AI · 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);

  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} />;
      default: return <OverviewPage navigate={navigate} />;
    }
  };

  return (
    <div style={{ minHeight: "100vh", background: "#0F1117", fontFamily: "'DM Sans', 'Segoe UI', sans-serif", color: "#E8E9ED" }}>
      <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Playfair+Display:wght@600;700&display=swap" rel="stylesheet" />

      <style>{`
        * { box-sizing: border-box; margin: 0; padding: 0; }
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); 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; } }
        .card {
          background: linear-gradient(135deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0.01) 100%);
          border: 1px solid rgba(255,255,255,0.06); border-radius: 16px;
          backdrop-filter: blur(20px); transition: all 0.3s cubic-bezier(0.4,0,0.2,1);
        }
        .card:hover { border-color: rgba(232,200,114,0.15); box-shadow: 0 8px 40px rgba(0,0,0,0.3), inset 0 1px 0 rgba(255,255,255,0.05); }
        .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: rgba(255,255,255,0.4); letter-spacing: 0.01em; font-family: inherit; }
        .nav-tab:hover { color: rgba(255,255,255,0.7); background: rgba(255,255,255,0.04); }
        .nav-tab.active { color: #E8C872; background: rgba(232,200,114,0.1); }
        .date-btn { padding: 6px 14px; border-radius: 6px; font-size: 12px; font-weight: 600; cursor: pointer; transition: all 0.2s; border: 1px solid rgba(255,255,255,0.06); background: transparent; color: rgba(255,255,255,0.4); letter-spacing: 0.03em; font-family: inherit; }
        .date-btn:hover { border-color: rgba(255,255,255,0.12); color: rgba(255,255,255,0.6); }
        .date-btn.active { border-color: rgba(232,200,114,0.3); color: #E8C872; background: rgba(232,200,114,0.06); }
        .table-row { transition: background 0.15s; }
        .table-row:hover { background: rgba(255,255,255,0.02); }
        .link-btn { font-size: 12px; font-weight: 600; color: #E8C872; background: none; border: 1px solid rgba(232,200,114,0.2); padding: 6px 14px; border-radius: 6px; cursor: pointer; letter-spacing: 0.02em; font-family: inherit; transition: all 0.2s; }
        .link-btn:hover { background: rgba(232,200,114,0.08); border-color: rgba(232,200,114,0.35); }
      `}</style>

      {/* Ambient BG */}
      <div style={{ position: "fixed", inset: 0, pointerEvents: "none", zIndex: 0, background: "radial-gradient(ellipse 80% 50% at 20% 10%, rgba(232,200,114,0.04) 0%, transparent 60%), radial-gradient(ellipse 60% 40% at 80% 80%, rgba(114,180,232,0.03) 0%, transparent 50%)" }} />

      {/* Header */}
      <header style={{ position: "relative", zIndex: 10, padding: "24px 40px", borderBottom: "1px solid rgba(255,255,255,0.05)", 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 rgba(232,200,114,0.25)" }}>W</div>
            <div>
              <h1 style={{ fontFamily: "'Playfair Display', serif", fontSize: "20px", fontWeight: 700, letterSpacing: "-0.02em", color: "#fff" }}>WooCommerce</h1>
              <p style={{ fontSize: "11px", color: "rgba(255,255,255,0.3)", fontWeight: 500, letterSpacing: "0.08em", textTransform: "uppercase" }}>Analytics Dashboard</p>
            </div>
          </div>
          <div style={{ width: 1, height: 32, background: "rgba(255,255,255,0.06)", margin: "0 4px" }} />
          <nav style={{ display: "flex", gap: "4px" }}>
            {["overview", "orders", "products", "customers"].map(tab => (
              <button key={tab} className={`nav-tab ${activeTab === tab ? "active" : ""}`}
                onClick={() => navigate(tab)} style={{ textTransform: "capitalize" }}>{tab}</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: "rgba(114,232,168,0.08)", border: "1px solid rgba(114,232,168,0.15)" }}>
            <div style={{ width: 7, height: 7, borderRadius: "50%", background: "#72E8A8", animation: "pulse 2s infinite" }} />
            <span style={{ fontSize: "12px", color: "#72E8A8", fontWeight: 600 }}>Store Live</span>
          </div>
        </div>
      </header>

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

      {/* AI Chat */}
      <AIChatPanel />
    </div>
  );
}
