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

/* ═══════════════════════════════════════════
   CONSTANTS & API UTILITIES
   ═══════════════════════════════════════════ */

const currency = window.wooInsightData?.currency || "£";

const apiFetch = async (path) => {
  const base  = window.wooInsightData?.apiUrl || "";
  const nonce = window.wooInsightData?.nonce  || "";
  const sep   = path.includes("?") ? "&" : "?";
  const url   = `${base}${path}${sep}_wpnonce=${nonce}`;
  console.debug("[WAD] GET", url, { noncePresent: !!nonce, noncePrefix: nonce.slice(0, 8) });
  const res   = await fetch(url, {
    credentials: "same-origin",
    headers: { "X-WP-Nonce": nonce, "Content-Type": "application/json" },
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    console.error("[WAD] GET error", res.status, url, err);
    throw new Error(err.message || `HTTP ${res.status}`);
  }
  return res.json();
};

const useApi = (path) => {
  const [data,    setData]    = useState(null);
  const [loading, setLoading] = useState(!!path);
  const [error,   setError]   = useState(null);

  const load = useCallback(async () => {
    if (!path) { setLoading(false); return; }
    setData(null);
    setLoading(true);
    setError(null);
    try {
      setData(await apiFetch(path));
    } catch (e) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  }, [path]);

  useEffect(() => { load(); }, [load]);
  return { data, loading, error, refetch: load };
};

// Currency formatter
const fc = (n, dec = 0) =>
  `${currency}${Number(n || 0).toLocaleString(undefined, { minimumFractionDigits: dec, maximumFractionDigits: dec })}`;
/* ═══════════════════════════════════════════
   LOADING & ERROR UI
   ═══════════════════════════════════════════ */

const Skeleton = ({ width = "100%", height = 16, style = {} }) => (
  <div style={{
    width, height, borderRadius: 6,
    background: "rgba(255,255,255,0.06)",
    animation: "pulse 1.5s ease-in-out infinite",
    ...style,
  }} />
);

const ErrorMessage = ({ message, onRetry }) => (
  <div className="card" style={{ padding: "40px", display: "flex", flexDirection: "column", alignItems: "center", gap: "16px", textAlign: "center" }}>
    <span style={{ fontSize: "32px" }}>⚠️</span>
    <p style={{ color: "#E87272", fontSize: "14px", maxWidth: 320 }}>{message || "Something went wrong."}</p>
    {onRetry && <button onClick={onRetry} className="link-btn">Retry</button>}
  </div>
);

const PageLoader = () => (
  <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16 }}>
      {[...Array(4)].map((_, i) => (
        <div key={i} className="card" style={{ padding: 24 }}>
          <Skeleton width="60%" height={12} style={{ marginBottom: 14 }} />
          <Skeleton width="80%" height={32} style={{ marginBottom: 10 }} />
          <Skeleton width="50%" height={12} />
        </div>
      ))}
    </div>
    <div className="card" style={{ padding: 24 }}>
      <Skeleton width="40%" height={16} style={{ marginBottom: 8 }} />
      <Skeleton width="60%" height={12} style={{ marginBottom: 24 }} />
      <Skeleton height={240} />
    </div>
  </div>
);

const Pagination = ({ page, totalPages, onChange }) => {
  if (totalPages <= 1) return null;

  const pages = [];
  for (let i = 1; i <= totalPages; i++) {
    if (i === 1 || i === totalPages || (i >= page - 1 && i <= page + 1)) {
      pages.push(i);
    } else if (pages[pages.length - 1] !== "…") {
      pages.push("…");
    }
  }

  const btn = (active, disabled) => ({
    padding: "6px 14px", borderRadius: 6, fontSize: 13, fontWeight: active ? 700 : 400,
    cursor: disabled ? "default" : "pointer", minWidth: 36, textAlign: "center",
    border: active ? "none" : "1px solid rgba(255,255,255,0.1)",
    background: active ? "#E8C872" : "rgba(255,255,255,0.05)",
    color: active ? "#0f1117" : disabled ? "rgba(255,255,255,0.2)" : "#fff",
    transition: "background 0.15s, color 0.15s",
  });

  return (
    <div style={{ display: "flex", justifyContent: "center", alignItems: "center", gap: 6, marginTop: 32, flexWrap: "wrap" }}>
      <button style={btn(false, page === 1)} disabled={page === 1} onClick={() => onChange(page - 1)}>← Prev</button>
      {pages.map((p, i) =>
        p === "…"
          ? <span key={`e${i}`} style={{ color: "rgba(255,255,255,0.3)", padding: "0 2px", fontSize: 13 }}>…</span>
          : <button key={p} style={btn(p === page, false)} onClick={() => p !== page && onChange(p)}>{p}</button>
      )}
      <button style={btn(false, page === totalPages)} disabled={page === totalPages} onClick={() => onChange(page + 1)}>Next →</button>
    </div>
  );
};

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

const AnimatedNumber = ({ value, prefix = "", suffix = "", decimals = 0 }) => {
  const [display, setDisplay] = useState(0);
  useEffect(() => {
    const dur = 1000, t0 = performance.now();
    const step = (now) => {
      const p = Math.min((now - t0) / 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: "#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"   },
    pending:    { bg: "rgba(180,114,232,0.12)", color: "#B472E8", label: "Pending"    },
  }[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 ? `${currency}${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", 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, dateRange }) => {
  const { data, loading, error, refetch } = useApi(`/overview?range=${dateRange}`);

  if (error) return <ErrorMessage message={error} onRetry={refetch} />;

  // Derive KPI cards from API data
  const kpis = data ? [
    { label: "Total Revenue",    value: data.kpis.revenue.value,   prefix: currency, change: data.kpis.revenue.change,  icon: "💰", sub: `vs ${fc(data.kpis.revenue.prev)} last period` },
    { label: "Orders",           value: data.kpis.orders.value,    change: data.kpis.orders.change,   icon: "📦", sub: `Avg. ${fc(data.kpis.orders.avg, 2)} per order`, nav: "orders" },
    { label: "Customers",        value: data.kpis.customers.value, change: data.kpis.customers.change, icon: "👥", sub: "Total unique customers", nav: "customers" },
    { label: "Avg. Order Value", value: data.kpis.orders.avg,      prefix: currency, change: 0, decimals: 2, icon: "💳", sub: "Per completed order" },
  ] : [];

  const dailyRevenue  = data?.daily_revenue  || [];
  const maxDayIdx     = dailyRevenue.reduce((mi, d, i, a) => d.amount > a[mi].amount ? i : mi, 0);
  const weekTotal     = dailyRevenue.reduce((s, d) => s + d.amount, 0);
  const categoryChart = data?.category_chart || [];
  const revenueChart  = data?.revenue_chart  || [];
  const custGrowth    = data?.customer_growth || [];
  const recentOrders  = data?.recent_orders  || [];
  const topProducts   = data?.top_products   || [];

  return (
    <>
      {/* KPIs */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "16px", marginBottom: "24px" }}>
        {loading
          ? [...Array(4)].map((_, i) => (
              <div key={i} className="card" style={{ padding: 24 }}>
                <Skeleton width="60%" height={12} style={{ marginBottom: 14 }} />
                <Skeleton width="80%" height={32} style={{ marginBottom: 10 }} />
                <Skeleton width="50%" height={12} />
              </div>
            ))
          : kpis.map((kpi, i) => (
              <div key={i} className="card" style={{ padding: "24px", animation: `fadeUp 0.6s ease ${i * 0.08}s both`, cursor: kpi.nav ? "pointer" : "default" }}
                onClick={() => kpi.nav && navigate(kpi.nav)}>
                <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.decimals || 0} />
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: "8px", marginTop: "10px" }}>
                  {kpi.change !== 0 && (
                    <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 */}
      <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" }}>
          {loading ? (
            <><Skeleton width="40%" height={16} style={{ marginBottom: 8 }} /><Skeleton width="60%" height={12} style={{ marginBottom: 24 }} /><Skeleton height={240} /></>
          ) : (
            <>
              <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 vs. same period last 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={revenueChart} 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 => `${currency}${(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>
          {loading ? (
            <Skeleton height={200} style={{ borderRadius: "50%", width: 200, margin: "0 auto" }} />
          ) : categoryChart.length === 0 ? (
            <p style={{ fontSize: "13px", color: "rgba(255,255,255,0.3)", textAlign: "center", padding: "40px 0" }}>No category data for this period</p>
          ) : (
            <>
              <div style={{ display: "flex", justifyContent: "center" }}>
                <ResponsiveContainer width={200} height={200}>
                  <PieChart>
                    <Pie data={categoryChart} cx="50%" cy="50%" innerRadius={60} outerRadius={85} paddingAngle={3} dataKey="value" stroke="none">
                      {categoryChart.map((e, i) => <Cell key={i} fill={e.color} />)}
                    </Pie>
                  </PieChart>
                </ResponsiveContainer>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: "10px", marginTop: "8px" }}>
                {categoryChart.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" }}>
            {loading ? "Loading…" : `Daily breakdown — ${fc(weekTotal)} total`}
          </p>
          {loading ? <Skeleton height={200} /> : (
            <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 => `${currency}${(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 === maxDayIdx ? "#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>
          {loading ? <Skeleton height={200} /> : (
            <ResponsiveContainer width="100%" height={200}>
              <AreaChart data={custGrowth} 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" }}>
        {/* Recent Orders */}
        <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: "90px 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>
          {loading
            ? [...Array(6)].map((_, i) => (
                <div key={i} style={{ display: "grid", gridTemplateColumns: "90px 1fr 80px 90px 80px", padding: "12px 0", gap: 8, borderBottom: "1px solid rgba(255,255,255,0.03)" }}>
                  {[...Array(5)].map((__, j) => <Skeleton key={j} height={13} />)}
                </div>
              ))
            : recentOrders.map((o, i) => (
                <div key={i} className="table-row" style={{ display: "grid", gridTemplateColumns: "90px 1fr 80px 90px 80px", padding: "12px 0", alignItems: "center", borderBottom: i < recentOrders.length - 1 ? "1px solid rgba(255,255,255,0.03)" : "none" }}>
                  <Clickable onClick={() => navigate("order-detail", o.id)} style={{ fontSize: "12px", fontWeight: 600, color: "#E8C872" }}>{o.number}</Clickable>
                  {o.custId > 0
                    ? <Clickable onClick={() => navigate("customer-detail", o.custId)} style={{ fontSize: "13px", color: "rgba(255,255,255,0.7)" }}>{o.customer}</Clickable>
                    : <span style={{ fontSize: "13px", color: "rgba(255,255,255,0.7)" }}>{o.customer}</span>
                  }
                  <span style={{ fontSize: "13px", fontWeight: 600, color: "#fff" }}>{fc(o.total, 2)}</span>
                  <StatusBadge status={o.status} />
                  <span style={{ fontSize: "11px", color: "rgba(255,255,255,0.3)" }}>{o.time}</span>
                </div>
              ))
          }
        </div>

        {/* Top Products */}
        <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>
          {loading
            ? [...Array(5)].map((_, i) => (
                <div key={i} style={{ display: "grid", gridTemplateColumns: "28px 1fr 60px 85px 60px", padding: "14px 0", gap: 8, borderBottom: "1px solid rgba(255,255,255,0.03)" }}>
                  {[...Array(5)].map((__, j) => <Skeleton key={j} height={13} />)}
                </div>
              ))
            : topProducts.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 < topProducts.length - 1 ? "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" }}>{fc(p.revenue)}</span>
                  <span style={{ fontSize: "12px", fontWeight: 600, color: p.trend > 0 ? "#72E8A8" : p.trend < 0 ? "#E87272" : "rgba(255,255,255,0.25)" }}>
                    {p.trend !== 0 ? `${p.trend > 0 ? "↑" : "↓"}${Math.abs(p.trend)}%` : "—"}
                  </span>
                </div>
              ))
          }
        </div>
      </div>
    </>
  );
};

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

const OrdersPage = ({ navigate }) => {
  const [filter,     setFilter]     = useState("all");
  const [page,       setPage]       = useState(1);
  const [tabCounts,  setTabCounts]  = useState({});
  const { data, loading, error, refetch } = useApi(`/orders?status=${filter}&per_page=20&page=${page}`);
  const orders     = data?.orders      || [];
  const total      = data?.total       || 0;
  const totalPages = data?.total_pages || 1;

  // Persist status counts so they stay visible while switching tabs
  useEffect(() => {
    if (data?.status_counts) setTabCounts(data.status_counts);
  }, [data]);

  const allTotal     = Object.values(tabCounts).reduce((s, n) => s + n, 0);
  const changeFilter = (f) => { setFilter(f); setPage(1); };
  const goToPage     = (p) => { setPage(p); window.scrollTo({ top: 0, behavior: "smooth" }); };

  const tabCount = (f) => {
    if (f === "all") return allTotal || null;
    const n = tabCounts[f];
    return n > 0 ? n : null;
  };

  return (
    <div style={{ animation: "fadeUp 0.5s ease" }}>
      <SectionTitle
        title="Orders"
        sub={!loading && data ? `${total} ${filter !== "all" ? filter : ""} orders` : " "}
      />

      {error && <ErrorMessage message={error} onRetry={refetch} />}

      <div style={{ display: "flex", gap: "6px", marginBottom: "20px", flexWrap: "wrap" }}>
        {["all", "completed", "processing", "on-hold", "refunded", "pending"].map(f => (
          <button key={f} onClick={() => changeFilter(f)} className={`date-btn ${filter === f ? "active" : ""}`} style={{ textTransform: "capitalize" }}>
            {f === "all" ? "All" : f.replace("-", " ")}
            {tabCount(f) !== null && <span style={{ opacity: 0.5, marginLeft: 4 }}>({tabCount(f)})</span>}
          </button>
        ))}
      </div>

      <div className="card" style={{ padding: "0", overflow: "hidden" }}>
        <div style={{ display: "grid", gridTemplateColumns: "90px 1fr 160px 60px 100px 100px 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>Order</span><span>Customer</span><span>Email</span><span>Items</span><span>Total</span><span>Status</span><span>Date</span>
        </div>
        {loading
          ? [...Array(8)].map((_, i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "90px 1fr 160px 60px 100px 100px 100px", padding: "14px 24px", gap: 8, borderBottom: "1px solid rgba(255,255,255,0.03)" }}>
                {[...Array(7)].map((__, j) => <Skeleton key={j} height={13} />)}
              </div>
            ))
          : orders.length === 0
            ? <p style={{ padding: "40px 24px", color: "rgba(255,255,255,0.3)", fontSize: "14px" }}>No orders found.</p>
            : orders.map((o, i) => (
                <div key={i} className="table-row" style={{ display: "grid", gridTemplateColumns: "90px 1fr 160px 60px 100px 100px 100px", 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.number}</Clickable>
                  {o.custId > 0
                    ? <Clickable onClick={() => navigate("customer-detail", o.custId)} style={{ fontSize: "13px", color: "rgba(255,255,255,0.7)" }}>{o.customer}</Clickable>
                    : <span style={{ fontSize: "13px", color: "rgba(255,255,255,0.7)" }}>{o.customer}</span>
                  }
                  <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" }}>{fc(o.total, 2)}</span>
                  <StatusBadge status={o.status} />
                  <span style={{ fontSize: "11px", color: "rgba(255,255,255,0.3)" }}>{o.date}</span>
                </div>
              ))
        }
      </div>

      {!loading && <Pagination page={page} totalPages={totalPages} onChange={goToPage} />}
    </div>
  );
};

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

const OrderDetailPage = ({ navigate, detailId }) => {
  const { data: order, loading, error, refetch } = useApi(detailId ? `/orders/${detailId}` : null);

  if (loading) return <PageLoader />;
  if (error)   return <><BackButton onClick={() => navigate("orders")} label="All Orders" /><ErrorMessage message={error} onRetry={refetch} /></>;
  if (!order)  return null;

  const products = Array.isArray(order.products) ? order.products : [];

  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.number}</h2>
        <StatusBadge status={order.status} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "16px", marginBottom: "16px" }}>
        {/* Order Details */}
        <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={fc(order.total, 2)} accent="#E8C872" />
        </div>

        {/* Customer */}
        <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", flexShrink: 0 }}>
              {(order.customer || "?").split(" ").map(n => n[0]).join("").slice(0, 2)}
            </div>
            <div>
              {order.custId > 0
                ? <Clickable onClick={() => navigate("customer-detail", order.custId)} style={{ fontSize: "15px", fontWeight: 600, color: "#fff" }}>{order.customer}</Clickable>
                : <span style={{ fontSize: "15px", fontWeight: 600, color: "#fff" }}>{order.customer}</span>
              }
              <p style={{ fontSize: "12px", color: "rgba(255,255,255,0.35)", marginTop: "2px" }}>{order.email}</p>
            </div>
          </div>
          {order.custId > 0 && <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>
          <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
            {products.map((item, i) => {
              const name  = typeof item === "string" ? item : item.name;
              const price = typeof item === "object" ? item.price : 0;
              const img   = typeof item === "object" ? item.img  : "";
              const pid   = typeof item === "object" ? item.id   : null;
              return (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: "10px", padding: "10px 0", borderBottom: i < products.length - 1 ? "1px solid rgba(255,255,255,0.04)" : "none" }}>
                  <div style={{ width: 32, height: 32, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    {img ? <img src={img} alt={name} style={{ width: 32, height: 32, objectFit: "cover", borderRadius: 6 }} /> : <span style={{ fontSize: "18px" }}>📦</span>}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    {pid
                      ? <Clickable onClick={() => navigate("product-detail", pid)} style={{ fontSize: "13px", color: "rgba(255,255,255,0.8)", fontWeight: 500 }}>{name}</Clickable>
                      : <span style={{ fontSize: "13px", color: "rgba(255,255,255,0.8)", fontWeight: 500 }}>{name}</span>
                    }
                    {price > 0 && <p style={{ fontSize: "11px", color: "rgba(255,255,255,0.3)", marginTop: "2px" }}>{fc(price, 2)}</p>}
                  </div>
                </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", 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",       color: "#72E8A8", active: true },
            { label: "Payment confirmed",  color: "#72B4E8", active: order.status !== "on-hold" && order.status !== "pending" },
            { label: "Shipped",            color: "#E8C872", active: order.status === "completed" },
            { label: "Delivered",          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.active ? order.date : "Pending"}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

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

const ProductsPage = ({ navigate }) => {
  const [page, setPage] = useState(1);
  const { data, loading, error, refetch } = useApi(`/products?per_page=20&page=${page}`);
  const products   = data?.products    || [];
  const totalPages = data?.total_pages || 1;

  const goToPage = (p) => {
    setPage(p);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  return (
    <div style={{ animation: "fadeUp 0.5s ease" }}>
      <SectionTitle
        title="Products"
        sub={!loading && data ? `${data.total} products in your store` : " "}
      />

      {error && <ErrorMessage message={error} onRetry={refetch} />}

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "16px" }}>
        {loading
          ? [...Array(20)].map((_, i) => (
              <div key={i} className="card" style={{ padding: 24 }}>
                <Skeleton height={48} width={48} style={{ borderRadius: 12, marginBottom: 14 }} />
                <Skeleton width="80%" height={14} style={{ marginBottom: 6 }} />
                <Skeleton width="50%" height={11} style={{ marginBottom: 14 }} />
                <Skeleton width="60%" height={20} />
              </div>
            ))
          : products.map((p, i) => (
              <div key={p.id ?? i} className="card" style={{ padding: "24px", cursor: "pointer", animation: `fadeUp 0.5s ease ${i * 0.04}s both` }}
                onClick={() => navigate("product-detail", p.id)}>
                <div style={{ width: 48, height: 48, borderRadius: "12px", background: "rgba(255,255,255,0.05)", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: "14px", overflow: "hidden" }}>
                  {p.img
                    ? <img src={p.img} alt={p.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                    : <span style={{ fontSize: "24px" }}>📦</span>
                  }
                </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].filter(Boolean).join(" · ") || "No category"}
                </p>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                  <span style={{ fontSize: "20px", fontWeight: 700, color: "#E8C872" }}>{fc(p.price, 2)}</span>
                  {p.trend !== 0 && (
                    <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 != null && p.stock < 10 ? "#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 > 0 ? `⭐ ${p.rating}` : "—"}</p>
                  </div>
                </div>
              </div>
            ))
        }
      </div>

      {!loading && <Pagination page={page} totalPages={totalPages} onChange={goToPage} />}
    </div>
  );
};

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

const ProductDetailPage = ({ navigate, detailId }) => {
  const { data: product, loading, error, refetch } = useApi(detailId ? `/products/${detailId}` : null);

  if (loading) return <PageLoader />;
  if (error)   return <><BackButton onClick={() => navigate("products")} label="All Products" /><ErrorMessage message={error} onRetry={refetch} /></>;
  if (!product) return null;

  const history       = product.history       || [];
  const relatedOrders = product.related_orders || [];

  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: "rgba(255,255,255,0.05)", display: "flex", alignItems: "center", justifyContent: "center", overflow: "hidden" }}>
          {product.img
            ? <img src={product.img} alt={product.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
            : <span style={{ fontSize: "32px" }}>📦</span>
          }
        </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, product.sku ? `SKU: ${product.sku}` : null].filter(Boolean).join(" · ")}
          </p>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "16px", marginBottom: "16px" }}>
        {[
          { label: "Price",      value: fc(product.price, 2), icon: "💷" },
          { label: "Units Sold", value: product.sold ?? "—",  icon: "📊" },
          { label: "Revenue",    value: product.revenue > 0 ? fc(product.revenue) : "—", icon: "💰" },
          { label: "In Stock",   value: product.stock ?? "N/A", 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>
          {history.length === 0
            ? <p style={{ color: "rgba(255,255,255,0.3)", fontSize: "13px" }}>No sales history available</p>
            : (
              <ResponsiveContainer width="100%" height={200}>
                <AreaChart data={history} 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>
          {product.cat    && <DetailRow label="Category"     value={product.cat} />}
          {product.sku    && <DetailRow label="SKU"          value={product.sku} />}
          {product.rating > 0 && <DetailRow label="Rating"  value={`⭐ ${product.rating} (${product.reviews} reviews)`} />}
          {product.trend !== 0 && (
            <DetailRow label="Trend" value={`${product.trend > 0 ? "↑" : "↓"} ${Math.abs(product.trend)}%`} accent={product.trend > 0 ? "#72E8A8" : "#E87272"} />
          )}
          <DetailRow
            label="Stock Status"
            value={product.stock == null ? "Unknown" : product.stock < 10 ? "Low Stock" : "In Stock"}
            accent={product.stock == null ? undefined : product.stock < 10 ? "#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 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.number}</Clickable>
                  {o.custId > 0
                    ? <Clickable onClick={() => navigate("customer-detail", o.custId)} style={{ fontSize: "13px", color: "rgba(255,255,255,0.7)" }}>{o.customer}</Clickable>
                    : <span style={{ fontSize: "13px", color: "rgba(255,255,255,0.7)" }}>{o.customer}</span>
                  }
                  <span style={{ fontSize: "13px", fontWeight: 600, color: "#fff" }}>{fc(o.total, 2)}</span>
                  <StatusBadge status={o.status} />
                  <span style={{ fontSize: "11px", color: "rgba(255,255,255,0.3)" }}>{o.date}</span>
                </div>
              ))}
            </>
          )
        }
      </div>
    </div>
  );
};

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

const CustomersPage = ({ navigate }) => {
  const [sort, setSort] = useState("spent");
  const [page, setPage] = useState(1);
  const { data, loading, error, refetch } = useApi(`/customers?sort=${sort}&per_page=20&page=${page}`);
  const customers  = data?.customers   || [];
  const totalPages = data?.total_pages || 1;

  const changeSort = (s) => { setSort(s); setPage(1); };
  const goToPage   = (p) => { setPage(p); window.scrollTo({ top: 0, behavior: "smooth" }); };

  return (
    <div style={{ animation: "fadeUp 0.5s ease" }}>
      <SectionTitle
        title="Customers"
        sub={!loading && data ? `${data.total} registered customers` : " "}
      />

      {error && <ErrorMessage message={error} onRetry={refetch} />}

      <div style={{ display: "flex", gap: "6px", marginBottom: "20px" }}>
        {[["spent", "Top Spenders"], ["orders", "Most Orders"], ["name", "Alphabetical"]].map(([v, l]) => (
          <button key={v} onClick={() => changeSort(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 120px 80px 110px", 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>
        {loading
          ? [...Array(8)].map((_, i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "50px 1fr 160px 80px 120px 80px 110px", padding: "14px 24px", gap: 8, borderBottom: "1px solid rgba(255,255,255,0.03)" }}>
                {[...Array(7)].map((__, j) => <Skeleton key={j} height={13} />)}
              </div>
            ))
          : customers.length === 0
            ? <p style={{ padding: "40px 24px", color: "rgba(255,255,255,0.3)", fontSize: "14px" }}>No customers found.</p>
            : customers.map((c, i) => (
                <div key={i} className="table-row" onClick={() => navigate("customer-detail", c.id)} style={{ display: "grid", gridTemplateColumns: "50px 1fr 160px 80px 120px 80px 110px", 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, c.joined ? `Joined ${c.joined}` : null].filter(Boolean).join(" · ")}</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" }}>{fc(c.spent, 2)}</span>
                  <TierBadge tier={c.tier} />
                  <span style={{ fontSize: "11px", color: "rgba(255,255,255,0.3)" }}>{c.lastOrder}</span>
                </div>
              ))
        }
      </div>

      {!loading && <Pagination page={page} totalPages={totalPages} onChange={goToPage} />}
    </div>
  );
};

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

const CustomerDetailPage = ({ navigate, detailId }) => {
  const { data: customer, loading, error, refetch } = useApi(detailId ? `/customers/${detailId}` : null);

  if (loading) return <PageLoader />;
  if (error)   return <><BackButton onClick={() => navigate("customers")} label="All Customers" /><ErrorMessage message={error} onRetry={refetch} /></>;
  if (!customer) return null;

  const spendHistory = customer.spendHistory || [];
  const ordersList   = customer.orders_list  || [];

  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].filter(Boolean).join(" · ")}
          </p>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "16px", marginBottom: "16px" }}>
        {[
          { label: "Total Spent",   value: fc(customer.spent, 2),                                    icon: "💰" },
          { label: "Orders",        value: customer.orders,                                           icon: "📦" },
          { label: "Avg. Order",    value: customer.orders > 0 ? fc(customer.spent / customer.orders, 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>
          {spendHistory.length === 0
            ? <p style={{ color: "rgba(255,255,255,0.3)", fontSize: "13px" }}>No spend history available</p>
            : (
              <ResponsiveContainer width="100%" height={200}>
                <BarChart data={spendHistory} 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 => `${currency}${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} />
          {customer.city && <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 ({ordersList.length} orders)
        </h4>
        {ordersList.length === 0
          ? <p style={{ color: "rgba(255,255,255,0.3)", fontSize: "13px" }}>No orders found</p>
          : (
            <>
              <div style={{ display: "grid", gridTemplateColumns: "90px 60px 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>
              {ordersList.map((o, i) => (
                <div key={i} className="table-row" style={{ display: "grid", gridTemplateColumns: "90px 60px 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.number}</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" }}>
                    {Array.isArray(o.products) ? o.products.map(p => typeof p === "string" ? p : p.name).join(", ") : ""}
                  </span>
                  <span style={{ fontSize: "13px", fontWeight: 600, color: "#fff" }}>{fc(o.total, 2)}</span>
                  <StatusBadge status={o.status} />
                </div>
              ))}
            </>
          )
        }
      </div>
    </div>
  );
};

/* ═══════════════════════════════════════════
   AI ASSISTANT CHAT PANEL
   All messages are proxied through the WP REST
   endpoint — the API key never leaves the server.
   ═══════════════════════════════════════════ */

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?",
  "What is my average order value?",
  "Which products are low on stock?",
  "How many orders have I had recently?",
];

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);

  const aiEnabled = window.wooInsightData?.aiEnabled !== false;

  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 apiUrl = window.wooInsightData?.apiUrl || "";
      const nonce  = window.wooInsightData?.nonce  || "";
      const aiUrl = `${apiUrl}/ai-query?_wpnonce=${nonce}`;
      console.debug("[WAD] POST ai-query", aiUrl, { noncePresent: !!nonce, noncePrefix: nonce.slice(0, 8) });
      const res    = await fetch(aiUrl, {
        method: "POST",
        credentials: "same-origin",
        headers: { "Content-Type": "application/json", "X-WP-Nonce": nonce },
        body: JSON.stringify({
          message: text.trim(),
          history: [...messages].slice(-10).map(m => ({ role: m.role, content: m.content })),
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        console.error("[WAD] ai-query error", res.status, data);
        throw new Error(data.message || "Request failed");
      }
      setMessages(prev => [...prev, { role: "assistant", content: data.response || "Sorry, no response." }]);
    } 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); } };

  if (!aiEnabled) return null;

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

      <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)", 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" }}>
        <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>

        <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" }}>
              <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>

        {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>
        )}

        <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" }}>
            <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 OpenAI · Live store data</p>
        </div>
      </div>
    </>
  );
};

/* ═══════════════════════════════════════════
   MY DASHBOARD — CUSTOM WIDGET BUILDER
   ═══════════════════════════════════════════ */

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

const WIDGET_TYPE_DISPLAY = {
  line_chart:  { icon: "📈", label: "Line Chart"  },
  bar_chart:   { icon: "📊", label: "Bar Chart"   },
  area_chart:  { icon: "🌊", label: "Area Chart"  },
  donut_chart: { icon: "🍩", label: "Donut Chart" },
  kpi_card:    { icon: "🎯", label: "KPI Card"    },
  table:       { icon: "📋", label: "Table"       },
  comparison:  { icon: "⚖️", label: "Comparison"  },
};

undefined

const PRESET_TEMPLATES = [
  {
    name: "Sales Overview", icon: "💰", 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: "👥", 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 order value",                     size: "small"  },
    ],
  },
  {
    name: "Product Performance", icon: "📦", 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: "⚡", 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" },
    ],
  },
];

// Infer the best widget type from a natural-language prompt
const inferWidgetType = (prompt) => {
  const p = prompt.toLowerCase();
  if (p.includes("list") || p.includes("table") || p.includes("top customer") || p.includes("low stock") || p.includes("stock below"))
    return "table";
  if ((p.includes("total") || p.includes("average") || p.includes("avg") || p.includes("rate") || p.includes("how many") || p.includes("count")) &&
      !p.includes("monthly") && !p.includes("weekly") && !p.includes("daily") && !p.includes("over time") && !p.includes("trend") && !p.includes("per month"))
    return "kpi_card";
  if (p.includes(" vs ") || p.includes("versus") || p.includes("new and returning") || p.includes("new vs returning"))
    return "comparison";
  if (p.includes("by status") || p.includes("by category") || p.includes("by tier") || p.includes("breakdown") || p.includes("distribution") || p.includes("categor"))
    return "donut_chart";
  if (p.includes("top ") || p.includes("best selling") || p.includes("daily") || p.includes("per day") || p.includes("this week") || p.includes("each day"))
    return "bar_chart";
  if (p.includes("trend") || p.includes("weekly") || p.includes("over time") || p.includes("growth"))
    return "line_chart";
  return "area_chart";
};

// ── Widget data via AI-powered server endpoint ─────────────────────────────

const fetchWidgetData = async (prompt, type) => {
  const apiUrl = window.wooInsightData?.apiUrl || '';
  const nonce  = window.wooInsightData?.nonce  || '';


  const widgetUrl = `${apiUrl}/widget-data?_wpnonce=${nonce}`;
  console.debug("[WAD] POST widget-data", widgetUrl, { noncePresent: !!nonce, noncePrefix: nonce.slice(0, 8) });
  const res = await fetch(widgetUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-WP-Nonce': nonce,
    },
    credentials: 'same-origin',
    body: JSON.stringify({ prompt, type }),
  });

  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    console.error("[WAD] widget-data error", res.status, err);
    const msg = err?.message || `Server error ${res.status}`;
    throw new Error(msg);
  }

  const data = await res.json();
  return data;
};


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: "rgba(255,255,255,0.3)" }, axisLine: false, tickLine: false };
  const yFmt        = data.yFormat === "currency" ? v => `${currency}${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: "#fff", 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 rgba(255,255,255,0.06)", fontSize: "10px", fontWeight: 600, color: "rgba(255,255,255,0.3)", 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 rgba(255,255,255,0.03)", fontSize: "13px" }}>
            {row.map((cell, ci) => <span key={ci} style={{ color: ci === 0 ? "rgba(255,255,255,0.8)" : "rgba(255,255,255,0.5)", 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], flexShrink: 0 }} />
              <span style={{ fontSize: "12px", color: "rgba(255,255,255,0.6)" }}>{d.name}</span>
              <span style={{ fontSize: "12px", fontWeight: 600, color: "rgba(255,255,255,0.8)" }}>{d.value}%</span>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // Dual-series comparison (area chart)
  if (data.series?.length === 2) {
    return (
      <ResponsiveContainer width="100%" height={200}>
        <AreaChart data={data.data} margin={chartMargin}>
          <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.04)" />
          <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>
    );
  }

  // Single-series charts
  if (widget.type === "bar_chart") {
    return (
      <ResponsiveContainer width="100%" height={200}>
        <BarChart data={data.data} margin={chartMargin}>
          <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.04)" vertical={false} />
          <XAxis dataKey="label" {...axisProps} />
          <YAxis {...axisProps} tickFormatter={yFmt} />
          <Tooltip content={<CustomTooltip />} />
          <Bar dataKey="value" name="Value" radius={[6, 6, 0, 0]} fill="#E8C872" maxBarSize={40} />
        </BarChart>
      </ResponsiveContainer>
    );
  }
  if (widget.type === "area_chart") {
    return (
      <ResponsiveContainer width="100%" height={200}>
        <AreaChart data={data.data} margin={chartMargin}>
          <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.04)" />
          <XAxis dataKey="label" {...axisProps} />
          <YAxis {...axisProps} tickFormatter={yFmt} />
          <Tooltip content={<CustomTooltip />} />
          <defs><linearGradient id="wG" 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>
          <Area type="monotone" dataKey="value" stroke="#E8C872" strokeWidth={2} fill="url(#wG)" name="Value" />
        </AreaChart>
      </ResponsiveContainer>
    );
  }
  // line_chart default
  return (
    <ResponsiveContainer width="100%" height={200}>
      <LineChart data={data.data} margin={chartMargin}>
        <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.04)" />
        <XAxis dataKey="label" {...axisProps} />
        <YAxis {...axisProps} tickFormatter={yFmt} />
        <Tooltip content={<CustomTooltip />} />
        <Line type="monotone" dataKey="value" stroke="#E8C872" strokeWidth={2.5} name="Value" dot={{ r: 3, fill: "#E8C872", strokeWidth: 0 }} activeDot={{ r: 5 }} />
      </LineChart>
    </ResponsiveContainer>
  );
};

const SUGGESTIONS = [
  "Monthly revenue last 6 months",
  "Daily revenue this week",
  "Top 5 products by stock sold",
  "Top 5 products by revenue",
  "Orders by status",
  "Revenue by category",
  "New vs returning customers per month",
  "Total revenue this month",
  "Total orders this month",
  "Average order value",
  "Low stock products",
  "Top customers by spend",
];

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

  const inferredType = prompt.trim() ? inferWidgetType(prompt) : null;
  const inferred     = inferredType ? WIDGET_TYPE_DISPLAY[inferredType] : null;

  const [error, setError] = useState(null);

  const handleAdd = async () => {
    if (!prompt.trim()) return;
    const type = inferWidgetType(prompt);
    setLoading(true);
    setError(null);
    try {
      const data = await fetchWidgetData(prompt, type);
      const widget = { id: `w_${Date.now()}`, type, prompt: prompt.trim(), title: data.title || prompt.trim(), data, size: type === "kpi_card" ? "small" : "medium", created: new Date().toISOString() };
      onAdd(widget);
    } catch (err) {
      setError(err.message || "Failed to fetch data. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 2000, display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(0,0,0,0.7)", backdropFilter: "blur(8px)", animation: "fadeUp 0.2s ease" }}
      onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{ width: 540, background: "#1A1D23", border: "1px solid rgba(255,255,255,0.08)", 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: "'Playfair Display', serif", fontSize: "20px", fontWeight: 700, color: "#fff" }}>Add Widget</h3>
          <button onClick={onClose} style={{ background: "none", border: "none", color: "rgba(255,255,255,0.4)", fontSize: "18px", cursor: "pointer", fontFamily: "inherit" }}>✕</button>
        </div>

        <label style={{ fontSize: "11px", fontWeight: 600, color: "rgba(255,255,255,0.35)", 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 6 months" or "Top 5 products by units sold"'
          rows={2} autoFocus
          style={{ width: "100%", background: "rgba(255,255,255,0.04)", border: "1px solid rgba(255,255,255,0.1)", borderRadius: "12px", padding: "12px 16px", color: "#fff", fontSize: "14px", fontFamily: "inherit", resize: "none", outline: "none", lineHeight: 1.5, marginBottom: "10px" }}
        />

        {/* Live chart-type preview */}
        <div style={{ height: 34, marginBottom: "16px", display: "flex", alignItems: "center" }}>
          {inferred ? (
            <div style={{ display: "flex", alignItems: "center", gap: "8px", padding: "6px 12px", borderRadius: "8px", background: "rgba(232,200,114,0.06)", border: "1px solid rgba(232,200,114,0.14)" }}>
              <span style={{ fontSize: "15px" }}>{inferred.icon}</span>
              <span style={{ fontSize: "12px", color: "rgba(255,255,255,0.45)" }}>Will generate a</span>
              <span style={{ fontSize: "12px", fontWeight: 600, color: "#E8C872" }}>{inferred.label}</span>
            </div>
          ) : (
            <span style={{ fontSize: "12px", color: "rgba(255,255,255,0.2)", fontStyle: "italic" }}>Start typing to see the suggested chart type</span>
          )}
        </div>

        {/* Suggestion chips */}
        <label style={{ fontSize: "11px", fontWeight: 600, color: "rgba(255,255,255,0.25)", letterSpacing: "0.06em", textTransform: "uppercase", display: "block", marginBottom: "8px" }}>Or pick a suggestion</label>
        <div style={{ display: "flex", flexWrap: "wrap", gap: "6px", marginBottom: "28px" }}>
          {SUGGESTIONS.map(s => (
            <button key={s} onClick={() => setPrompt(s)}
              style={{ padding: "5px 10px", borderRadius: "6px", fontSize: "11px", background: prompt === s ? "rgba(232,200,114,0.08)" : "rgba(255,255,255,0.03)", border: `1px solid ${prompt === s ? "rgba(232,200,114,0.25)" : "rgba(255,255,255,0.05)"}`, color: prompt === s ? "#E8C872" : "rgba(255,255,255,0.4)", cursor: "pointer", fontFamily: "inherit", transition: "all 0.15s" }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = "rgba(232,200,114,0.2)"; e.currentTarget.style.color = "#E8C872"; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = prompt === s ? "rgba(232,200,114,0.25)" : "rgba(255,255,255,0.05)"; e.currentTarget.style.color = prompt === s ? "#E8C872" : "rgba(255,255,255,0.4)"; }}
            >{s}</button>
          ))}
        </div>

        {error && (
          <div style={{ padding: "10px 14px", borderRadius: "8px", background: "rgba(232,114,114,0.1)", border: "1px solid rgba(232,114,114,0.2)", color: "#E87272", fontSize: "12px", marginBottom: "16px" }}>{error}</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" : "rgba(255,255,255,0.3)",
          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…</>
            : "✨ Generate Widget"
          }
        </button>
      </div>
    </div>
  );
};

/* ═══════════════════════════════════════════
   REPORTS PAGE
   ═══════════════════════════════════════════ */

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

const fetchReportText = async (prompt) => {
  const apiUrl = window.wooInsightData?.apiUrl || "";
  const nonce  = window.wooInsightData?.nonce  || "";
  const reportUrl = `${apiUrl}/report-section?_wpnonce=${nonce}`;
  console.debug("[WAD] POST report-section", reportUrl, { noncePresent: !!nonce, noncePrefix: nonce.slice(0, 8) });
  const res = await fetch(reportUrl, {
    method: "POST",
    headers: { "Content-Type": "application/json", "X-WP-Nonce": nonce },
    credentials: "same-origin",
    body: JSON.stringify({ prompt }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    console.error("[WAD] report-section error", res.status, err);
    throw new Error(err?.message || `Server error ${res.status}`);
  }
  const data = await res.json();
  return data.text;
};

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

  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);
    setError(null);
    try {
      const [text, chartData] = await Promise.all([
        fetchReportText(prompt),
        chartType !== "text_only" ? fetchWidgetData(prompt, chartType) : Promise.resolve(null),
      ]);
      onAdd({
        id: `rs_${Date.now()}`,
        prompt: prompt.trim(),
        title: chartData?.title || prompt.trim(),
        text,
        chartType: chartType === "text_only" ? null : chartType,
        chartData,
      });
    } catch (err) {
      setError(err.message || "Failed to generate section.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 2000, display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(0,0,0,0.7)", backdropFilter: "blur(8px)", animation: "fadeUp 0.2s ease" }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{ width: 560, background: "#1A1D23", border: "1px solid rgba(255,255,255,0.08)", 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: "'Playfair Display', serif", fontSize: "20px", fontWeight: 700, color: "#fff" }}>Add Report Section</h3>
          <button onClick={onClose} style={{ background: "none", border: "none", color: "rgba(255,255,255,0.4)", fontSize: "18px", cursor: "pointer", fontFamily: "inherit" }}>{"\u2715"}</button>
        </div>

        <label style={{ fontSize: "11px", fontWeight: 600, color: "rgba(255,255,255,0.35)", 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} autoFocus
          style={{ width: "100%", background: "rgba(255,255,255,0.04)", border: "1px solid rgba(255,255,255,0.1)", borderRadius: "12px", padding: "14px 16px", color: "#fff", 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: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.06)", color: "rgba(255,255,255,0.4)", 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 = "rgba(255,255,255,0.06)"; e.currentTarget.style.color = "rgba(255,255,255,0.4)"; }}
            ><span>{s.icon}</span> {s.prompt}</button>
          ))}
        </div>

        <label style={{ fontSize: "11px", fontWeight: 600, color: "rgba(255,255,255,0.35)", 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 ? "#E8C872" : "rgba(255,255,255,0.4)",
              cursor: "pointer", fontFamily: "inherit", transition: "all 0.2s",
              display: "flex", alignItems: "center", gap: "6px",
            }}>{ct.icon} {ct.label}</button>
          ))}
        </div>

        {error && (
          <div style={{ padding: "10px 14px", borderRadius: "8px", background: "rgba(232,114,114,0.1)", border: "1px solid rgba(232,114,114,0.2)", color: "#E87272", fontSize: "12px", marginBottom: "16px" }}>{error}</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" : "rgba(255,255,255,0.3)",
          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 chartMargin = { top: 5, right: 10, left: -10, bottom: 0 };
  const axisProps = { tick: { fontSize: 11, fill: "rgba(255,255,255,0.3)" }, axisLine: false, tickLine: false };
  const yFmt = section.chartData.yFormat === "currency" ? v => `${currency}${(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 rgba(255,255,255,0.06)", fontSize: "10px", fontWeight: 600, color: "rgba(255,255,255,0.35)", 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 rgba(255,255,255,0.03)", fontSize: "13px" }}>
            {row.map((cell, ci) => <span key={ci} style={{ color: ci === 0 ? "rgba(255,255,255,0.7)" : "rgba(255,255,255,0.5)", 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: "rgba(255,255,255,0.7)" }}>{d.name}</span><span style={{ fontSize: "13px", fontWeight: 600, color: "rgba(255,255,255,0.7)" }}>{d.value}{typeof d.value === "number" && d.value <= 100 ? "%" : ""}</span></div>))}
        </div>
      </div>
    );
  }

  if (section.chartData.data) {
    const ChartComp = section.chartType === "bar_chart" ? BarChart : section.chartType === "area_chart" ? AreaChart : LineChart;
    const DataComp  = section.chartType === "bar_chart" ? Bar : section.chartType === "area_chart" ? Area : Line;
    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="rgba(255,255,255,0.04)" />
            <XAxis dataKey="label" {...axisProps} /><YAxis {...axisProps} tickFormatter={yFmt} />
            <Tooltip contentStyle={{ background: "#1A1D23", border: "1px solid rgba(255,255,255,0.1)", borderRadius: "8px" }} />
            <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="rgba(255,255,255,0.04)" vertical={section.chartType === "bar_chart" ? false : undefined} />
          <XAxis dataKey="label" {...axisProps} /><YAxis {...axisProps} tickFormatter={yFmt} />
          <Tooltip contentStyle={{ background: "#1A1D23", border: "1px solid rgba(255,255,255,0.1)", borderRadius: "8px" }} />
          {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 = () => {
  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");
  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: "#fff", marginBottom: "8px" }}>Create a report</h3>
          <p style={{ fontSize: "14px", color: "rgba(255,255,255,0.4)", 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: "rgba(255,255,255,0.35)", 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: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.06)", fontSize: "12px", color: "rgba(255,255,255,0.4)", 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
  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>

        <div style={{ background: "rgba(255,255,255,0.02)", border: "1px solid rgba(255,255,255,0.06)", borderRadius: "16px", padding: "48px", maxWidth: 900, margin: "0 auto" }}>
          <div style={{ textAlign: "center", marginBottom: "40px", paddingBottom: "24px", borderBottom: "2px solid rgba(232,200,114,0.2)" }}>
            <h1 style={{ fontFamily: "'Playfair Display', serif", fontSize: "28px", fontWeight: 700, color: "#fff", marginBottom: "8px" }}>{reportTitle}</h1>
            <p style={{ fontSize: "13px", color: "rgba(255,255,255,0.4)" }}>Generated on {dateStr}</p>
          </div>

          {sections.length > 1 && (
            <div style={{ marginBottom: "32px", padding: "20px", background: "rgba(255,255,255,0.02)", borderRadius: "12px" }}>
              <h4 style={{ fontSize: "13px", fontWeight: 600, color: "rgba(255,255,255,0.5)", letterSpacing: "0.06em", textTransform: "uppercase", marginBottom: "12px" }}>Contents</h4>
              {sections.map((s, i) => (
                <div key={s.id} style={{ fontSize: "14px", color: "rgba(255,255,255,0.6)", padding: "4px 0" }}>{i + 1}. {s.title}</div>
              ))}
            </div>
          )}

          {sections.map((section, i) => (
            <div key={section.id} style={{ marginBottom: "40px" }}>
              <h2 style={{ fontFamily: "'Playfair Display', serif", fontSize: "20px", fontWeight: 700, color: "#fff", marginBottom: "16px", paddingBottom: "8px", borderBottom: "1px solid rgba(255,255,255,0.06)" }}>{i + 1}. {section.title}</h2>
              {section.chartData && section.chartType && (
                <div style={{ marginBottom: "20px" }}>
                  <ReportSectionChart section={section} />
                </div>
              )}
              <div style={{ fontSize: "14px", lineHeight: 1.8, color: "rgba(255,255,255,0.6)", whiteSpace: "pre-wrap" }}>{section.text}</div>
            </div>
          ))}

          <div style={{ marginTop: "40px", paddingTop: "20px", borderTop: "1px solid rgba(255,255,255,0.06)", textAlign: "center" }}>
            <p style={{ fontSize: "11px", color: "rgba(255,255,255,0.2)" }}>Report generated by WooInsight Analytics</p>
          </div>
        </div>
      </div>
    );
  }

  // Edit mode
  return (
    <div style={{ animation: "fadeUp 0.5s ease" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "20px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
          {editingTitle ? (
            <input ref={titleRef} value={reportTitle} onChange={e => setReportTitle(e.target.value)}
              onBlur={() => setEditingTitle(false)} onKeyDown={e => e.key === "Enter" && setEditingTitle(false)}
              autoFocus
              style={{ fontSize: "22px", fontFamily: "'Playfair Display', serif", fontWeight: 700, background: "transparent", border: "1px solid rgba(232,200,114,0.3)", borderRadius: "8px", padding: "4px 12px", color: "#fff", outline: "none", width: 400 }}
            />
          ) : (
            <h2 style={{ fontFamily: "'Playfair Display', serif", fontSize: "22px", fontWeight: 700, color: "#fff", cursor: "pointer" }} onClick={() => setEditingTitle(true)} title="Click to rename">{reportTitle}</h2>
          )}
          <span style={{ fontSize: "12px", color: "rgba(255,255,255,0.3)" }}>{sections.length} section{sections.length !== 1 ? "s" : ""}</span>
        </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: "8px 18px", borderRadius: "8px", border: "none",
            background: "linear-gradient(135deg, #E8C872, #D4A843)", color: "#0F1117",
            fontSize: "13px", fontWeight: 700, cursor: "pointer", fontFamily: "inherit",
            display: "flex", alignItems: "center", gap: "6px",
          }}>{"\u{1F4F0}"} Preview Report</button>
        </div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
        {sections.map((section, i) => (
          <div key={section.id} className="card" style={{ padding: "24px", animation: `fadeUp 0.4s ease ${i * 0.05}s both` }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px" }}>
              <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
                <span style={{ fontSize: "12px", color: "rgba(255,255,255,0.2)", fontWeight: 600 }}>{i + 1}.</span>
                <h4 style={{ fontSize: "15px", fontWeight: 600, color: "#fff" }}>{section.title}</h4>
                {section.chartType && <span style={{ fontSize: "10px", padding: "3px 8px", borderRadius: "4px", background: "rgba(232,200,114,0.08)", color: "#E8C872", fontWeight: 600, textTransform: "uppercase" }}>{section.chartType.replace("_", " ")}</span>}
              </div>
              <div style={{ display: "flex", gap: "4px" }}>
                <button onClick={() => moveSection(section.id, -1)} disabled={i === 0} title="Move up" style={{ background: "none", border: "none", color: i === 0 ? "rgba(255,255,255,0.1)" : "rgba(255,255,255,0.25)", 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 ? "rgba(255,255,255,0.1)" : "rgba(255,255,255,0.25)", 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: "rgba(255,255,255,0.25)", 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.chartData && section.chartType && (
              <div style={{ marginBottom: "16px", padding: "16px", background: "rgba(255,255,255,0.02)", borderRadius: "12px" }}>
                <ReportSectionChart section={section} />
              </div>
            )}

            <div style={{ fontSize: "13px", lineHeight: 1.7, color: "rgba(255,255,255,0.5)", whiteSpace: "pre-wrap" }}>{section.text}</div>
          </div>
        ))}
      </div>

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

/* ═══════════════════════════════════════════
   MY DASHBOARD PAGE
   ═══════════════════════════════════════════ */

const MyDashboardPage = () => {
  const [widgets,    setWidgets]    = useState(() => {
    try { const s = localStorage.getItem("wad_my_dashboard"); return s ? JSON.parse(s) : []; } catch { return []; }
  });
  const [editMode,   setEditMode]   = useState(false);
  const [showModal,  setShowModal]  = useState(false);
  const [draggingId, setDraggingId] = useState(null);
  const [dragOverId, setDragOverId] = useState(null);
  const dragIdx     = useRef(null);
  const dragOverIdx = useRef(null);
  useEffect(() => {
    try { localStorage.setItem("wad_my_dashboard", JSON.stringify(widgets)); } catch {}
  }, [widgets]);

  const handleDragStart = (i, id) => { dragIdx.current = i; setDraggingId(id); };
  const handleDragEnter = (i, id) => { dragOverIdx.current = i; setDragOverId(id); };
  const handleDragEnd   = () => {
    if (dragIdx.current !== null && dragOverIdx.current !== null && dragIdx.current !== dragOverIdx.current) {
      const next    = [...widgets];
      const dragged = next.splice(dragIdx.current, 1)[0];
      next.splice(dragOverIdx.current, 0, dragged);
      setWidgets(next);
    }
    dragIdx.current = null;
    dragOverIdx.current = null;
    setDraggingId(null);
    setDragOverId(null);
  };

  const addWidget = (widget) => { setWidgets(prev => [...prev, widget]); setShowModal(false); };
  const removeWidget = (id)  => setWidgets(prev => prev.filter(w => w.id !== id));

  const applyTemplate = async (template) => {
    const newWidgets = await Promise.all(template.widgets.map(async (tw, i) => {
      try {
        const data = await fetchWidgetData(tw.prompt, tw.type);
        return { id: `w_${Date.now()}_${i}`, type: tw.type, prompt: tw.prompt, title: data?.title || tw.prompt, data: data || {}, size: tw.size, created: new Date().toISOString() };
      } catch {
        return { id: `w_${Date.now()}_${i}`, type: tw.type, prompt: tw.prompt, 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"];
      return { ...w, size: sizes[(sizes.indexOf(w.size) + 1) % sizes.length] };
    }));
  };

  const refreshWidget = async (id) => {
    const w = widgets.find(x => x.id === id);
    if (!w) return;
    try {
      const data = await fetchWidgetData(w.prompt, w.type);
      if (data) setWidgets(prev => prev.map(x => x.id === id ? { ...x, data } : x));
    } catch (err) {
    }
  };

  // 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 }}>✨</div>
          <h3 style={{ fontSize: "18px", fontWeight: 600, color: "#fff", marginBottom: "8px" }}>Build your own dashboard</h3>
          <p style={{ fontSize: "14px", color: "rgba(255,255,255,0.35)", marginBottom: "28px", textAlign: "center", maxWidth: 400 }}>
            Add widgets by describing what you want to see — charts, KPI cards, and tables built from your live store data.
          </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)", display: "flex", alignItems: "center", gap: "8px" }}>
            ＋ Add Your First Widget
          </button>

          <div style={{ marginTop: "48px", width: "100%" }}>
            <p style={{ fontSize: "12px", fontWeight: 600, color: "rgba(255,255,255,0.25)", 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: "#fff", marginBottom: "4px" }}>{t.name}</h4>
                  <p style={{ fontSize: "11px", color: "rgba(255,255,255,0.3)", lineHeight: 1.4 }}>{t.desc}</p>
                </div>
              ))}
            </div>
          </div>
        </div>
        {showModal && <AddWidgetModal onClose={() => setShowModal(false)} onAdd={addWidget} />}
      </div>
    );
  }

  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 ? "✓ Done Editing" : "✎ Edit Layout"}
          </button>
          <button onClick={() => setShowModal(true)} className="link-btn">＋ Add Widget</button>
          <button onClick={() => { if (window.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: "#E87272", fontFamily: "inherit", transition: "all 0.2s" }}>
            🗑 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";
          const isDragged = draggingId === w.id;
          const isTarget  = dragOverId === w.id && !isDragged;
          return (
            <div
              key={w.id}
              className="card"
              draggable={editMode}
              onDragStart={() => handleDragStart(i, w.id)}
              onDragEnter={() => handleDragEnter(i, w.id)}
              onDragEnd={handleDragEnd}
              onDragOver={e => e.preventDefault()}
              style={{
                gridColumn: `span ${colSpan}`, padding: "20px 24px",
                minHeight: isKpi ? 120 : isTable ? 200 : undefined,
                height: !isKpi && !isTable ? 280 : undefined,
                position: "relative",
                animation: draggingId ? "none" : `fadeUp 0.4s ease ${i * 0.05}s both`,
                cursor: editMode ? (isDragged ? "grabbing" : "grab") : undefined,
                opacity: isDragged ? 0.35 : 1,
                border: editMode
                  ? isTarget
                    ? "1px dashed rgba(232,200,114,0.7)"
                    : "1px dashed rgba(232,200,114,0.25)"
                  : undefined,
                boxShadow: isTarget ? "0 0 0 2px rgba(232,200,114,0.15), 0 8px 40px rgba(0,0,0,0.3)" : undefined,
                transform: isTarget ? "scale(1.01)" : undefined,
                transition: "opacity 0.15s, border-color 0.15s, transform 0.15s, box-shadow 0.15s",
              }}
            >
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: isKpi ? "4px" : "16px" }}>
                <div style={{ display: "flex", alignItems: "flex-start", gap: "8px" }}>
                  {editMode && (
                    <span title="Drag to reorder" style={{ color: "rgba(255,255,255,0.2)", fontSize: "14px", lineHeight: 1, paddingTop: "1px", cursor: "grab", userSelect: "none" }}>⠿</span>
                  )}
                  <div>
                    <h4 style={{ fontSize: "13px", fontWeight: 600, color: "#fff", marginBottom: "2px" }}>{w.title}</h4>
                    {!isKpi && <p style={{ fontSize: "11px", color: "rgba(255,255,255,0.25)", fontStyle: "italic" }}>{w.prompt}</p>}
                  </div>
                </div>
                <div style={{ display: "flex", gap: "4px", alignItems: "center" }}>
                  <button onClick={() => refreshWidget(w.id)} title="Refresh" style={{ background: "none", border: "none", color: "rgba(255,255,255,0.25)", 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)"}>🔄</button>
                  {editMode && (
                    <>
                      <button onClick={() => cycleSize(w.id)} title="Resize" style={{ background: "none", border: "none", color: "rgba(255,255,255,0.25)", 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)"}
                      >⤢</button>
                      <button onClick={() => removeWidget(w.id)} title="Remove" style={{ background: "none", border: "none", color: "rgba(255,255,255,0.25)", 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)"}
                      >✕</button>
                    </>
                  )}
                </div>
              </div>
              <div style={{ height: isKpi ? "auto" : isTable ? "auto" : 200 }}>
                <WidgetRenderer widget={w} />
              </div>
              {editMode && (
                <div style={{ position: "absolute", bottom: 6, right: 10, fontSize: "9px", color: "rgba(255,255,255,0.15)", letterSpacing: "0.06em", textTransform: "uppercase" }}>{w.size}</div>
              )}
            </div>
          );
        })}
      </div>

      {showModal && <AddWidgetModal onClose={() => setShowModal(false)} onAdd={addWidget} />}
    </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 dashName = window.wooInsightData?.dashName || "WooCommerce";

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

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

  const activeTab = {
    "order-detail":    "orders",
    "product-detail":  "products",
    "customer-detail": "customers",
  }[page] || page;

  const renderPage = () => {
    switch (page) {
      case "overview":        return <OverviewPage navigate={navigate} dateRange={dateRange} />;
      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 />;
      default:                return <OverviewPage navigate={navigate} dateRange={dateRange} />;
    }
  };

  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.4; } }
        @keyframes spin { to { transform: rotate(360deg); } }
        .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>

      <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 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" }}>{dashName}</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", "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" }}>✨</span>}{key === "reports" && <span style={{ marginRight: "4px" }}>📋</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: "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>

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

      <AIChatPanel />
    </div>
  );
}
