const { useState, useEffect, useMemo, useCallback, useRef } = React;

/* ------------------------- Minimal inline icon set (no external deps, offline-safe) ------------------------- */
function Glyph({ name, size = 16, color = "currentColor", style }) {
  const p = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: color, strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round", style };
  switch (name) {
    case "dashboard": return <svg {...p}><rect x="3" y="3" width="7" height="9" /><rect x="14" y="3" width="7" height="5" /><rect x="14" y="10" width="7" height="11" /><rect x="3" y="14" width="7" height="7" /></svg>;
    case "cart": return <svg {...p}><path d="M6 7h12l-1.2 12.5a1 1 0 0 1-1 .5H8.2a1 1 0 0 1-1-.9L6 7z" /><path d="M9 7V5a3 3 0 0 1 6 0v2" /></svg>;
    case "phone": return <svg {...p}><rect x="7" y="2" width="10" height="20" rx="2" /><line x1="11" y1="18" x2="13" y2="18" /></svg>;
    case "wallet": return <svg {...p}><rect x="2.5" y="6" width="19" height="13" rx="2" /><path d="M16 12.5h3" /></svg>;
    case "chart": return <svg {...p}><line x1="4" y1="20" x2="4" y2="11" /><line x1="10" y1="20" x2="10" y2="4" /><line x1="16" y1="20" x2="16" y2="14" /><line x1="20" y1="20" x2="20" y2="8" /></svg>;
    case "settings": return <svg {...p}><circle cx="12" cy="12" r="3" /><path d="M19 12a7 7 0 0 0-.2-1.6l2-1.5-2-3.4-2.3.9a7 7 0 0 0-2.7-1.6L15.4 2h-2.8l-.4 2.8a7 7 0 0 0-2.7 1.6l-2.3-.9-2 3.4 2 1.5A7 7 0 0 0 5 12c0 .5.1 1 .2 1.6l-2 1.5 2 3.4 2.3-.9a7 7 0 0 0 2.7 1.6l.4 2.8h2.8l.4-2.8a7 7 0 0 0 2.7-1.6l2.3.9 2-3.4-2-1.5c.1-.6.2-1.1.2-1.6z" /></svg>;
    case "plus": return <svg {...p}><line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" /></svg>;
    case "x": return <svg {...p}><line x1="6" y1="6" x2="18" y2="18" /><line x1="18" y1="6" x2="6" y2="18" /></svg>;
    case "menu": return <svg {...p}><line x1="4" y1="6" x2="20" y2="6" /><line x1="4" y1="12" x2="20" y2="12" /><line x1="4" y1="18" x2="20" y2="18" /></svg>;
    case "search": return <svg {...p}><circle cx="11" cy="11" r="7" /><line x1="21" y1="21" x2="16.5" y2="16.5" /></svg>;
    case "edit": return <svg {...p}><path d="M12 20h9" /><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z" /></svg>;
    case "trash": return <svg {...p}><polyline points="3 6 5 6 21 6" /><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m2 0-1 14a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L6 6" /></svg>;
    case "check": return <svg {...p}><circle cx="12" cy="12" r="9" /><polyline points="8 12.5 11 15.5 16 9" /></svg>;
    case "warn": return <svg {...p}><path d="M12 3 2 20h20L12 3z" /><line x1="12" y1="10" x2="12" y2="15" /><circle cx="12" cy="17.5" r="0.6" fill={color} stroke="none" /></svg>;
    case "clock": return <svg {...p}><circle cx="12" cy="12" r="9" /><polyline points="12 7 12 12 16 14" /></svg>;
    case "chevronRight": return <svg {...p}><polyline points="9 6 15 12 9 18" /></svg>;
    case "chevronLeft": return <svg {...p}><polyline points="15 6 9 12 15 18" /></svg>;
    case "store": return <svg {...p}><path d="M3 9l1.5-5h15L21 9" /><path d="M4 9v10h16V9" /><path d="M4 9a3 3 0 0 0 6 0 3 3 0 0 0 6 0 3 3 0 0 0 6 0" /><rect x="10" y="13" width="4" height="6" /></svg>;
    case "palette": return <svg {...p}><path d="M12 3a9 9 0 1 0 0 18c1.1 0 1.8-.9 1.8-1.8 0-.5-.2-.9-.5-1.2-.3-.3-.5-.7-.5-1.2 0-.9.7-1.6 1.6-1.6H16a4 4 0 0 0 4-4c0-4.4-3.6-8.2-8-8.2z" /><circle cx="7.5" cy="10.5" r="1.1" fill={color} stroke="none" /><circle cx="11" cy="7.5" r="1.1" fill={color} stroke="none" /><circle cx="15" cy="8" r="1.1" fill={color} stroke="none" /></svg>;
    case "cloudUpload": return <svg {...p}><path d="M7 18a4.5 4.5 0 0 1-1-8.9A5.5 5.5 0 0 1 16.5 8H17a4 4 0 0 1 0 8h-1" /><polyline points="9 13 12 10 15 13" /><line x1="12" y1="10" x2="12" y2="19" /></svg>;
    case "image": return <svg {...p}><rect x="3" y="4" width="18" height="16" rx="2" /><circle cx="8.5" cy="9.5" r="1.6" /><path d="M21 16.5 15.5 11 6 20" /></svg>;
    case "dollar": return <svg {...p}><line x1="12" y1="2" x2="12" y2="22" /><path d="M17 6.5c0-1.9-2-3-5-3s-5 1.2-5 3 2 2.7 5 3.3 5 1.6 5 3.4-2 3.3-5 3.3-5-1.1-5-3" /></svg>;
    case "cash": return <svg {...p}><rect x="2" y="6" width="20" height="12" rx="2" /><circle cx="12" cy="12" r="3" /></svg>;
    case "users": return <svg {...p}><circle cx="9" cy="8" r="3.2" /><path d="M2.5 20c0-4 3-6.5 6.5-6.5S15.5 16 15.5 20" /><circle cx="17" cy="9" r="2.6" /><path d="M15.2 13.8c2.7.2 4.8 2.3 4.8 6.2" /></svg>;
    case "truck": return <svg {...p}><rect x="1.5" y="7" width="12" height="9" rx="1" /><path d="M13.5 10h3.5l3 3v3h-6.5" /><circle cx="6" cy="18" r="1.6" /><circle cx="16.5" cy="18" r="1.6" /></svg>;
    case "tag": return <svg {...p}><path d="M20.5 12.7 12.7 20.5a2 2 0 0 1-2.8 0l-6.4-6.4a2 2 0 0 1 0-2.8L11.3 3.5H19a1.5 1.5 0 0 1 1.5 1.5v7.2z" /><circle cx="15.5" cy="8.5" r="1.3" /></svg>;
    case "list": return <svg {...p}><line x1="9" y1="6" x2="21" y2="6" /><line x1="9" y1="12" x2="21" y2="12" /><line x1="9" y1="18" x2="21" y2="18" /><polyline points="3 6 4 7 5.5 5" /><polyline points="3 12 4 13 5.5 11" /><polyline points="3 18 4 19 5.5 17" /></svg>;
    case "history": return <svg {...p}><path d="M3 12a9 9 0 1 0 3-6.7" /><polyline points="3 3 3 8 8 8" /><polyline points="12 7 12 12 15.5 14" /></svg>;
    case "boxCheck": return <svg {...p}><path d="M21 8 12 3 3 8v8l9 5 9-5V8z" /><polyline points="8 12 11 14.5 16 9.5" /></svg>;
    case "boxX": return <svg {...p}><path d="M21 8 12 3 3 8v8l9 5 9-5V8z" /><line x1="9.5" y1="9.5" x2="14.5" y2="14.5" /><line x1="14.5" y1="9.5" x2="9.5" y2="14.5" /></svg>;
    case "download": return <svg {...p}><path d="M12 3v12" /><polyline points="7 10 12 15 17 10" /><path d="M4 20h16" /></svg>;
    case "upload": return <svg {...p}><path d="M12 21V9" /><polyline points="7 14 12 9 17 14" /><path d="M4 4h16" /></svg>;
    case "returnArrow": return <svg {...p}><path d="M3 7v6h6" /><path d="M3 13a9 9 0 1 0 2.6-6.4L3 9" /></svg>;
    case "arrowLeft": return <svg {...p}><line x1="19" y1="12" x2="5" y2="12" /><polyline points="12 19 5 12 12 5" /></svg>;
    case "trendUp": return <svg {...p}><polyline points="3 17 9 11 13 15 21 6" /><polyline points="15 6 21 6 21 12" /></svg>;
    case "scale": return <svg {...p}><line x1="12" y1="3" x2="12" y2="21" /><path d="M12 5 6 8l-3.5 7a4 4 0 0 0 7 0L6 8" /><path d="M12 5l6 3 3.5 7a4 4 0 0 1-7 0L18 8" /><line x1="7" y1="21" x2="17" y2="21" /></svg>;
    case "bell": return <svg {...p}><path d="M6 9a6 6 0 0 1 12 0c0 4 1.5 5.5 2 6.5H4c.5-1 2-2.5 2-6.5z" /><path d="M10 19a2 2 0 0 0 4 0" /></svg>;
    case "refresh": return <svg {...p}><path d="M20 11a8 8 0 0 0-14.9-3.8L3 10" /><polyline points="3 5 3 10 8 10" /><path d="M4 13a8 8 0 0 0 14.9 3.8L21 14" /><polyline points="21 19 21 14 16 14" /></svg>;
    default: return <svg {...p}><circle cx="12" cy="12" r="9" /></svg>;
  }
}
const mkIcon = (name) => (props) => <Glyph name={name} {...props} />;
const LayoutDashboard = mkIcon("dashboard");
const ShoppingBag = mkIcon("cart");
const Smartphone = mkIcon("phone");
const Wallet = mkIcon("wallet");
const FileBarChart = mkIcon("chart");
const SettingsIcon = mkIcon("settings");
const Plus = mkIcon("plus");
const X = mkIcon("x");
const MenuIcon = mkIcon("menu");
const Search = mkIcon("search");
const Pencil = mkIcon("edit");
const Trash2 = mkIcon("trash");
const CheckCircle2 = mkIcon("check");
const AlertTriangle = mkIcon("warn");
const Clock = mkIcon("clock");
const ChevronRight = mkIcon("chevronRight");
const DollarSign = mkIcon("dollar");
const Banknote = mkIcon("cash");
const Users = mkIcon("users");
const Truck = mkIcon("truck");
const Tag = mkIcon("tag");
const ListChecks = mkIcon("list");
const History = mkIcon("history");
const PackageCheck = mkIcon("boxCheck");
const PackageX = mkIcon("boxX");
const CircleDollarSign = mkIcon("dollar");
const DownloadIcon = mkIcon("download");
const UploadIcon = mkIcon("upload");
const Undo2 = mkIcon("returnArrow");
const ArrowLeft = mkIcon("arrowLeft");
const TrendUp = mkIcon("trendUp");
const Scale = mkIcon("scale");
const Bell = mkIcon("bell");
const RefreshCw = mkIcon("refresh");
const ChevronLeft = mkIcon("chevronLeft");
const Store = mkIcon("store");
const Palette = mkIcon("palette");
const CloudUpload = mkIcon("cloudUpload");
const ImageIcon = mkIcon("image");

/* ---------------------------------- THEME ---------------------------------- */
const THEME_PALETTES = {
  ocean: {
    bg:"#F4F7FB", surface:"#FFFFFF", ink:"#10233F", sub:"#60708A", faint:"#9AA9BD", border:"#DCE5EF",
    primary:"#173B63", primarySoft:"#E7F0F8", accent:"#0B8F88", accentSoft:"#E2F6F3",
    success:"#17824D", successSoft:"#E4F6EC", warning:"#B66A09", warningSoft:"#FFF0D8",
    danger:"#C23B35", dangerSoft:"#FBE8E6", gold:"#B07A16", goldSoft:"#FFF3D9"
  },
  emerald: {
    bg:"#F3F8F6", surface:"#FFFFFF", ink:"#102A25", sub:"#5E756F", faint:"#9BAFA9", border:"#DCE9E5",
    primary:"#14594F", primarySoft:"#E4F1EE", accent:"#0A8F72", accentSoft:"#E1F6F0",
    success:"#187A50", successSoft:"#E2F5EC", warning:"#A96816", warningSoft:"#FFF0DA",
    danger:"#BD3C45", dangerSoft:"#FBE7E9", gold:"#A77919", goldSoft:"#FFF4D8"
  },
  midnight: {
    bg:"#0E1726", surface:"#162238", ink:"#F2F6FC", sub:"#A9B7CA", faint:"#72839A", border:"#293A53",
    primary:"#214B78", primarySoft:"#1B3858", accent:"#18A69B", accentSoft:"#173E3B",
    success:"#2EBB72", successSoft:"#173D2D", warning:"#D29A32", warningSoft:"#41331A",
    danger:"#E15B63", dangerSoft:"#43262B", gold:"#D5A743", goldSoft:"#443719"
  }
};
const ACTIVE_THEME = localStorage.getItem("karwan-ui-theme") || "ocean";
const ACTIVE_BG = localStorage.getItem("karwan-bg") || "";
const C = THEME_PALETTES[ACTIVE_THEME] || THEME_PALETTES.ocean;

function useFonts() {
  useEffect(() => {
    const l = document.createElement("link");
    l.rel = "stylesheet";
    l.href = "https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap";
    document.head.appendChild(l);
    return () => document.head.removeChild(l);
  }, []);
}

const FONT = "'Manrope', system-ui, sans-serif";
const MONO = "'JetBrains Mono', ui-monospace, monospace";

function useDesignSystem() {
  useEffect(() => {
    const style = document.createElement("style");
    style.id = "karwan-design-system";
    style.textContent = `
      :root {
        color-scheme: ${ACTIVE_THEME === "midnight" ? "dark" : "light"};
        --karwan-bg: ${C.bg};
        --karwan-surface: ${C.surface};
        --karwan-ink: ${C.ink};
        --karwan-sub: ${C.sub};
        --karwan-faint: ${C.faint};
        --karwan-border: ${C.border};
        --karwan-accent: ${C.accent};
        --karwan-accent-soft: ${C.accentSoft};
      }
      html, body { background: ${C.bg} !important; color: ${C.ink} !important; }
      body { font-family: ${FONT}; -webkit-font-smoothing: antialiased; }
      button, input, select, textarea { font-family: ${FONT}; }
      input, select, textarea {
        color: ${C.ink} !important;
        background-color: ${C.surface} !important;
        border-color: ${C.border} !important;
        caret-color: ${C.accent} !important;
        color-scheme: ${ACTIVE_THEME === "midnight" ? "dark" : "light"};
        transition: border-color .18s ease, box-shadow .18s ease, background .18s ease;
      }
      input::placeholder, textarea::placeholder {
        color: ${C.faint} !important;
        opacity: 1 !important;
      }
      select option, select optgroup {
        color: ${C.ink} !important;
        background: ${C.surface} !important;
      }
      input[type="date"]::-webkit-datetime-edit,
      input[type="number"]::-webkit-inner-spin-button,
      input[type="date"]::-webkit-calendar-picker-indicator {
        color: ${C.ink};
      }
      input:focus, select:focus, textarea:focus {
        outline: none !important; border-color: ${C.accent} !important;
        box-shadow: 0 0 0 3px ${C.accentSoft} !important;
      }
      button { transition: transform .15s ease, box-shadow .15s ease, filter .15s ease; }
      button:hover:not(:disabled) { filter: brightness(1.035); }
      button:active:not(:disabled) { transform: translateY(1px); }
      table { border-collapse: separate !important; border-spacing: 0 !important; }
      th { font-size: 10.5px !important; letter-spacing: .05em !important; text-transform: uppercase !important; }
      td, th { border-bottom-color: ${C.border} !important; }
      /* Midnight: normalize legacy light controls/chips so no white fragments remain */
      ${ACTIVE_THEME === "midnight" ? `
      button:disabled {
        color: ${C.faint} !important;
        background: ${C.primarySoft} !important;
        border-color: ${C.border} !important;
      }
      input, select, textarea {
        background-color: ${C.surface} !important;
        color: ${C.ink} !important;
      }
      input::placeholder, textarea::placeholder { color: ${C.faint} !important; }
      select option, select optgroup { background: ${C.surface} !important; color: ${C.ink} !important; }
      ` : ""}
      ::selection { background: ${C.accentSoft}; color: ${C.ink}; }
      @media (max-width: 760px) {
        .karwan-responsive-grid { grid-template-columns: 1fr !important; }
        .karwan-chart-grid { grid-template-columns: 1fr !important; }
      }
    `;
    document.head.appendChild(style);
    return () => style.remove();
  }, []);
}


/* ---------------------------------- HELPERS ---------------------------------- */
const uid = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
const nowISO = () => new Date().toISOString();
const todayDate = () => new Date().toISOString().slice(0, 10);

function fmtMoney(amount, currency) {
  const n = Number(amount) || 0;
  if (currency === "USD") return "$" + n.toLocaleString(undefined, { maximumFractionDigits: 2 });
  return n.toLocaleString(undefined, { maximumFractionDigits: 0 }) + " IQD";
}
function fmtDate(d) {
  if (!d) return "-";
  try { return new Date(d).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" }); }
  catch { return d; }
}
function fmtDateTime(d) {
  if (!d) return "-";
  try { return new Date(d).toLocaleString(undefined, { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }); }
  catch { return d; }
}
// Short relative time for the notifications feed ("5m ago", "3h ago"), falling
// back to a full date once something is more than a week old.
function timeAgo(ts) {
  if (!ts) return "-";
  const then = typeof ts === "number" ? ts : new Date(ts).getTime();
  if (Number.isNaN(then)) return "-";
  const diffSec = Math.max(0, Math.floor((Date.now() - then) / 1000));
  if (diffSec < 60) return "just now";
  const diffMin = Math.floor(diffSec / 60);
  if (diffMin < 60) return `${diffMin}m ago`;
  const diffHr = Math.floor(diffMin / 60);
  if (diffHr < 24) return `${diffHr}h ago`;
  const diffDay = Math.floor(diffHr / 24);
  if (diffDay < 7) return `${diffDay}d ago`;
  return fmtDateTime(then);
}
function getPurchaseRate(phone, invoices, settings) {
  const r = Number(phone?.purchaseExchangeRate || invoices?.find(i => i.id === phone?.invoiceId)?.exchangeRate || settings?.exchangeRate || 1);
  return r > 0 ? r : 1;
}
function purchaseCostInCurrency(phone, targetCurrency, invoices, settings) {
  const cost = Number(phone?.purchasePrice) || 0;
  const source = phone?.purchaseCurrency || "USD";
  if (source === targetCurrency) return cost;
  const rate = getPurchaseRate(phone, invoices, settings);
  return source === "USD" && targetCurrency === "IQD" ? cost * rate : cost / rate;
}
function saleProfit(phone, invoices, settings) {
  if (!phone?.sale) return 0;
  const saleTotal = Number(phone.sale.totalPrice ?? phone.sale.price) || 0;
  return saleTotal - purchaseCostInCurrency(phone, phone.sale.currency || "USD", invoices, settings);
}

// Converts an amount between USD and IQD using a specific rate (not "today's" rate).
// This is what lets every past purchase/sale keep the exchange rate that was actually
// in effect on the day it happened, since IQD/USD fluctuates day to day in Iraq.
function convertCurrency(amount, fromCurrency, toCurrency, rate) {
  const amt = Number(amount) || 0;
  if (fromCurrency === toCurrency) return amt;
  const r = Number(rate) > 0 ? Number(rate) : 1;
  if (fromCurrency === "USD" && toCurrency === "IQD") return amt * r;
  if (fromCurrency === "IQD" && toCurrency === "USD") return amt / r;
  return amt;
}
// The exchange rate recorded at the moment a sale was made. Falls back to the phone's
// purchase rate, then today's rate, only for older sales recorded before this field existed.
function getSaleRate(phone, settings) {
  const r = Number(phone?.sale?.exchangeRate || phone?.purchaseExchangeRate || settings?.exchangeRate || 1);
  return r > 0 ? r : 1;
}
function saleValueInCurrency(phone, targetCurrency, settings) {
  const total = Number(phone?.sale?.totalPrice ?? phone?.sale?.price) || 0;
  const cur = phone?.sale?.currency || "USD";
  return convertCurrency(total, cur, targetCurrency, getSaleRate(phone, settings));
}
function saleProfitInCurrency(phone, targetCurrency, invoices, settings) {
  if (!phone?.sale) return 0;
  const saleCur = phone.sale.currency || "USD";
  const saleTotal = Number(phone.sale.totalPrice ?? phone.sale.price) || 0;
  const cost = purchaseCostInCurrency(phone, saleCur, invoices, settings);
  const profitInSaleCur = saleTotal - cost;
  return convertCurrency(profitInSaleCur, saleCur, targetCurrency, getSaleRate(phone, settings));
}

const DEFAULT_SETTINGS = {
  shopName: "My Mobile Shop",
  brands: ["Apple", "Samsung", "Xiaomi", "Huawei", "Oppo"],
  modelsByBrand: {
    Apple: ["iPhone 13", "iPhone 14", "iPhone 15"],
    Samsung: ["Galaxy S23", "Galaxy A54"],
    Xiaomi: ["Redmi Note 12"],
    Huawei: [],
    Oppo: [],
  },
  suppliers: ["Al-Karkh Wholesale", "Baghdad Mobile Traders"],
  customers: ["Walk-in Customer"],
  supplierPhones: {},
  customerPhones: {},
  supplierLocations: {},
  customerLocations: {},
  paymentMethods: ["Cash", "Bank Transfer", "Zain Cash", "FastPay", "FIB"],
  exchangeRate: 1460,
  uiTheme: "ocean",
};

const STORAGE_KEYS = ["settings", "phones", "invoices", "payments", "customerPayments", "activityLog", "recycleBin", "supplierReturns"];

// Notifications are per-device history (built from what THIS device's realtime
// listener has received), not shared shop data, so they get their own storage
// key namespaced by device id instead of living in STORAGE_KEYS — every "personal"
// key in this app is still stored on one shared cloud row per shop, so without this
// namespacing every device would overwrite the same notification history.
function notificationsStorageKey() {
  const id = (typeof localStorage !== "undefined" && localStorage.getItem("karwan-device-id")) || "unknown-device";
  return "notifications:" + id;
}

function defaultFor(key) {
  if (key === "settings") return DEFAULT_SETTINGS;
  return [];
}

// Upgrades settings saved by older versions of the app (flat "models" list)
// into the brand-scoped "modelsByBrand" structure. Safe to run every load.
function migrateSettings(raw) {
  const s = { ...raw };
  const brands = Array.isArray(s.brands) && s.brands.length ? s.brands : DEFAULT_SETTINGS.brands;
  let modelsByBrand = s.modelsByBrand && typeof s.modelsByBrand === "object" ? { ...s.modelsByBrand } : null;

  if (!modelsByBrand) {
    modelsByBrand = {};
    brands.forEach((b) => { modelsByBrand[b] = []; });
    const legacyModels = Array.isArray(s.models) ? s.models : [];
    const guessBrand = (name) => {
      const n = name.toLowerCase();
      if (n.includes("iphone")) return "Apple";
      if (n.includes("galaxy")) return "Samsung";
      if (n.includes("redmi") || n.includes("poco") || n.includes("xiaomi") || n.includes("mi ")) return "Xiaomi";
      if (n.includes("huawei") || n.includes("mate") || n.includes("nova")) return "Huawei";
      if (n.includes("oppo") || n.includes("reno")) return "Oppo";
      return null;
    };
    legacyModels.forEach((m) => {
      const guessed = guessBrand(m);
      const target = guessed && brands.includes(guessed) ? guessed : brands[0];
      if (target && !modelsByBrand[target].includes(m)) modelsByBrand[target].push(m);
    });
  }

  // Make sure every current brand has a models bucket (e.g. brand added but never saved yet)
  brands.forEach((b) => { if (!modelsByBrand[b]) modelsByBrand[b] = []; });

  const next = { ...s, brands, modelsByBrand };
  delete next.models;
  return next;
}

/* ---------------------------------- SMALL UI PRIMITIVES ---------------------------------- */

function Badge({ tone = "sub", children, mono }) {
  const map = {
    success: { bg: C.successSoft, fg: C.success },
    warning: { bg: C.warningSoft, fg: C.warning },
    danger: { bg: C.dangerSoft, fg: C.danger },
    accent: { bg: C.accentSoft, fg: C.accent },
    gold: { bg: C.goldSoft, fg: C.gold },
    sub: { bg: ACTIVE_THEME === "midnight" ? C.primarySoft : "#EEF0F5", fg: C.sub },
  };
  const t = map[tone] || map.sub;
  return (
    <span
      style={{
        background: t.bg, color: t.fg, fontFamily: mono ? MONO : FONT,
        fontSize: 12, fontWeight: 600, padding: "3px 9px", borderRadius: 999,
        display: "inline-flex", alignItems: "center", gap: 4, whiteSpace: "nowrap",
      }}
    >
      {children}
    </span>
  );
}

function Card({ children, style, onClick }) {
  return (
    <div
      onClick={onClick}
      style={{
        background: ACTIVE_BG ? (ACTIVE_THEME === "midnight" ? "rgba(22,34,56,0.72)" : "rgba(255,255,255,0.72)") : C.surface,
        backdropFilter: ACTIVE_BG ? "blur(20px) saturate(180%)" : undefined,
        WebkitBackdropFilter: ACTIVE_BG ? "blur(20px) saturate(180%)" : undefined,
        border: `1px solid ${C.border}`, borderRadius: 14,
        boxShadow: "0 1px 2px rgba(18,23,43,0.04)", ...style,
      }}
    >
      {children}
    </div>
  );
}

function StatCard({ icon: Icon, label, value, sub, tone = "primary", extra }) {
  const toneColor = { primary: C.primary, accent: C.accent, success: C.success, warning: C.warning, danger: C.danger, gold: C.gold }[tone];
  return (
    <Card style={{ padding: 18, flex: "1 1 220px", minWidth: 210 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <span style={{ color: C.sub, fontSize: 12.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: 0.4 }}>{label}</span>
        <div style={{ width: 30, height: 30, borderRadius: 9, background: toneColor + "1A", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon size={16} color={toneColor} />
        </div>
      </div>
      <div style={{ fontFamily: MONO, fontSize: 24, fontWeight: 700, color: C.ink, marginTop: 10 }}>{value}</div>
      {sub && <div style={{ fontSize: 12.5, color: C.sub, marginTop: 4 }}>{sub}</div>}
      {extra && (
        <div style={{ marginTop: 10, paddingTop: 8, borderTop: `1px dashed ${C.border}`, fontSize: 11.5, color: C.sub }}>
          {extra}
        </div>
      )}
    </Card>
  );
}

function Button({ children, onClick, variant = "primary", icon: Icon, size = "md", type = "button", disabled, style }) {
  const variants = {
    primary: { bg: C.primary, fg: "#fff", border: C.primary },
    accent: { bg: C.accent, fg: "#fff", border: C.accent },
    ghost: { bg: "transparent", fg: C.ink, border: C.border },
    danger: { bg: C.dangerSoft, fg: C.danger, border: C.dangerSoft },
    subtle: { bg: C.primarySoft, fg: ACTIVE_THEME === "midnight" ? "#6FA3DD" : C.primary, border: C.primarySoft },
  };
  const v = variants[variant];
  const pad = size === "sm" ? "6px 10px" : "9px 14px";
  return (
    <button
      type={type}
      disabled={disabled}
      onClick={onClick}
      style={{
        display: "inline-flex", alignItems: "center", gap: 6, background: v.bg, color: v.fg,
        border: `1px solid ${v.border}`, borderRadius: 9, padding: pad, fontFamily: FONT,
        fontSize: 13.5, fontWeight: 600, cursor: disabled ? "not-allowed" : "pointer",
        opacity: disabled ? 0.5 : 1, whiteSpace: "nowrap", ...style,
      }}
    >
      {Icon && <Icon size={15} />}
      {children}
    </button>
  );
}

function Field({ label, children }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 5, fontSize: 12.5, color: C.sub, fontWeight: 600 }}>
      {label}
      {children}
    </label>
  );
}

const inputStyle = {
  border: `1px solid ${C.border}`, borderRadius: 8, padding: "8px 10px", fontFamily: FONT,
  fontSize: 13.5, color: C.ink, outline: "none", background: C.surface, width: "100%", boxSizing: "border-box",
};

function Input(props) { return <input {...props} style={{ ...inputStyle, ...(props.style || {}) }} />; }
function Select({ children, ...props }) { return <select {...props} style={{ ...inputStyle, ...(props.style || {}) }}>{children}</select>; }
function TextArea(props) { return <textarea {...props} rows={2} style={{ ...inputStyle, resize: "vertical", ...(props.style || {}) }} />; }

function Modal({ title, onClose, children, width = 560, confirmClose = false }) {
  const handleClose = () => {
    if (confirmClose && !window.confirm("Discard unsaved changes?")) return;
    onClose();
  };
  return (
    <div style={{
      position: "fixed", inset: 0, background: "rgba(18,23,43,0.45)", display: "flex",
      alignItems: "flex-start", justifyContent: "center", padding: "5vh 16px", zIndex: 60, overflowY: "auto",
    }} onClick={handleClose}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: C.surface, borderRadius: 16, width: "100%", maxWidth: width,
        boxShadow: "0 20px 60px rgba(18,23,43,0.25)", overflow: "hidden", marginBottom: 40,
      }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 20px", borderBottom: `1px solid ${C.border}` }}>
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: C.ink }}>{title}</h3>
          <button onClick={handleClose} style={{ background: "none", border: "none", cursor: "pointer", color: C.sub, padding: 4 }}><X size={18} /></button>
        </div>
        <div style={{ padding: 20 }}>{children}</div>
      </div>
    </div>
  );
}

function EmptyState({ icon: Icon, text }) {
  return (
    <div style={{ padding: "36px 20px", textAlign: "center", color: C.faint }}>
      <Icon size={26} style={{ marginBottom: 8 }} />
      <div style={{ fontSize: 13.5 }}>{text}</div>
    </div>
  );
}

function SignalBars({ ratio }) {
  // ratio 0..1 of stock sold-through, signature shop motif
  const bars = [0.25, 0.5, 0.75, 1];
  const color = ratio > 0.66 ? C.success : ratio > 0.33 ? C.gold : C.danger;
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 2, height: 16 }}>
      {bars.map((b, i) => (
        <div key={i} style={{
          width: 4, height: 4 + i * 4, borderRadius: 1,
          background: ratio >= b - 0.001 || (i === 0 && ratio > 0) ? color : "#E1E4EB",
        }} />
      ))}
    </div>
  );
}

/* ---------------------------------- MAIN APP ---------------------------------- */

const SECTIONS = [
  { id: "notifications", label: "Notifications", icon: Bell },
  { id: "dashboard", label: "Dashboard", icon: LayoutDashboard },
  { id: "purchases", label: "Purchases", icon: ShoppingBag },
  { id: "sales", label: "Sales", icon: Smartphone },
  { id: "stock", label: "Stock", icon: PackageCheck },
  { id: "brands", label: "Brands", icon: Tag },
  { id: "analytics", label: "Analytics", icon: FileBarChart },
  { id: "returns", label: "Supplier Returns", icon: Undo2 },
  { id: "payments", label: "Supplier Payments", icon: Wallet },
  { id: "customerPayments", label: "Customer Payments", icon: CircleDollarSign },
  { id: "personalInfo", label: "Personal Information", icon: Users },
  { id: "recycleBin", label: "Recycle Bin", icon: Trash2 },
  { id: "settings", label: "Settings", icon: SettingsIcon },
];


/* ------------------------- Storage / RAM helpers ------------------------- */
// Older versions stored Android specs together as values such as "256/6".
// Keep those records intact while exposing separate storage and RAM fields.
function normalizeCapacity(value) {
  const s = String(value ?? "").trim();
  if (!s) return "";
  if (/[a-zA-Z]/.test(s)) return s;
  return `${s}GB`;
}

function migratePhoneSpecs(phone) {
  if (!phone || typeof phone !== "object") return phone;
  let storage = phone.storage == null ? "" : String(phone.storage).trim();
  let ram = phone.ram == null ? "" : String(phone.ram).trim();

  // Only split legacy combined storage/RAM values when RAM is not already stored.
  if (!ram && storage.includes("/")) {
    const parts = storage.split("/");
    if (parts.length >= 2) {
      storage = parts[0].trim();
      ram = parts.slice(1).join("/").trim();
    }
  }

  const next = { ...phone };
  if (storage) next.storage = normalizeCapacity(storage);
  else next.storage = "";
  if (ram) next.ram = normalizeCapacity(ram);
  else next.ram = "";
  return next;
}

function migratePhones(list) {
  if (!Array.isArray(list)) return [];
  return list.map(migratePhoneSpecs);
}

function phoneSpecLabel(phone) {
  const storage = phone?.storage ? normalizeCapacity(phone.storage) : "";
  const ram = phone?.ram ? normalizeCapacity(phone.ram) : "";
  if (storage && ram) return `${storage} / ${ram} RAM`;
  if (storage) return storage;
  if (ram) return `${ram} RAM`;
  return "-";
}

// SIM configuration options a phone can be sold/purchased with.
const SIM_TYPES = ["eSIM", "1 SIM", "2 SIM"];

// Combines storage/RAM specs with the SIM type into one compact label, used anywhere
// a phone is shown inline (Stock, Sales, Purchases, Supplier Returns, search, etc.)
// so the SIM type is reflected everywhere the storage/RAM spec already is.
function phoneFullSpecLabel(phone) {
  const spec = phoneSpecLabel(phone);
  const sim = phone?.simType || "";
  if (spec !== "-" && sim) return `${spec} · ${sim}`;
  if (sim) return sim;
  return spec;
}


/* ------------------------- Language / Kurdish (Sorani) ------------------------- */
const LANGUAGE_KEY = "karwan_app_language";
const KU = {
  "Dashboard":"داشبۆرد","Purchases":"کڕینەکان","Sales":"فرۆشتن","Stock":"کۆگا","Supplier Returns":"گەڕاندنەوە بۆ دابینکەر",
  "Supplier Payments":"پارەدان بە دابینکەر","Customer Payments":"پارەدانەکانی کڕیار","Reports & Activity":"ڕاپۆرت و چالاکی","Date Analysis":"شیکردنەوەی بەروار",
  "Recycle Bin":"سەڵەی دووبارە","Settings":"ڕێکخستنەکان","Undo":"گەڕاندنەوە","Nothing to undo":"هیچ گۆڕانکارییەک نییە بۆ گەڕاندنەوە",
  "Exchange rate":"نرخی گۆڕین","Loading shop data…":"داتاکانی دوکان بار دەکرێن…","Save":"پاشەکەوتکردن","Save Changes":"پاشەکەوتکردنی گۆڕانکارییەکان",
  "Discard":"هەڵوەشاندنەوە","Cancel":"هەڵوەشاندنەوە","Close":"داخستن","Add":"زیادکردن","Edit":"دەستکاریکردن","Delete":"سڕینەوە",
  "Search":"گەڕان","Filter":"فلتەر","Notes":"تێبینی","Notes (optional)":"تێبینی (ئارەزوومەندانە)",
  "Shop Information":"زانیاری دوکان","Shop Name":"ناوی دوکان","Language":"زمان","English":"ئینگلیزی","Kurdish":"کوردی",
  "Kurdish (Sorani)":"کوردی (سۆرانی)","System Language":"زمانی سیستەم","Master data and system configuration":"داتای سەرەکی و ڕێکخستنی سیستەم",
  "Brands":"براندەکان","Models":"مۆدێلەکان","Suppliers":"دابینکەرەکان","Customers":"کڕیارەکان","Payment Methods":"شێوازەکانی پارەدان",
  "Exchange Rate (IQD per 1 USD)":"نرخی گۆڕین (دینار بۆ ١ دۆلار)","Automatic Daily Backup":"باپەکەپی خۆکارانەی ڕۆژانە",
  "Backup":"باپەکەپ","Restore":"گەڕاندنەوەی باپەکەپ","Cash":"نەقد","Cash Purchase":"کڕینی نەقد","Installment":"قیست",
  "Purchase":"کڕین","Sale":"فرۆشتن","Phone":"مۆبایل","Phones":"مۆبایلەکان","IMEI":"IMEI","Brand":"براند","Model":"مۆدێل",
  "Date":"بەروار","Price":"نرخ","Total":"کۆی گشتی","Paid":"پارەدراو","Remaining":"ماوە","Status":"دۆخ",
  "In Stock":"لە کۆگادایە","Sold":"فرۆشراو","Returned":"گەڕێندرایەوە","Return":"گەڕاندنەوە","Record Payment":"تۆمارکردنی پارەدان",
  "Actual Paid":"پارەی ڕاستەقینەی دراو","Due Date":"بەرواری پارەدان","Planned":"پلانکراو","Paid Date":"بەرواری پارەدان",
  "Payment Method":"شێوازی پارەدان","Supplier":"دابینکەر","Invoice":"پسووڵە","Invoice #":"ژمارەی پسووڵە",
  "Customer":"کڕیار","Profit":"قازانج","Loss":"زیان","Reports":"ڕاپۆرتەکان","Activity":"چالاکی",
  "View":"بینین","Hide":"شاردنەوە","All":"هەموو","Unpaid":"پارە نەدراوە","Partially Paid":"بەشێک پارەدراوە",
  "Paid in full":"تەواو پارەدراوە","Save failed — your last change may not have been stored.":"پاشەکەوتکردن سەرکەوتوو نەبوو — ڕەنگە دوا گۆڕانکارییەکەت پاشەکەوت نەکرابێت.",
  "Search customer or IMEI":"گەڕان بە ناوی کڕیار یان IMEI","Search by IMEI, brand, model...":"گەڕان بە IMEI، براند، مۆدێل...",
  "No installment sales yet.":"هێشتا هیچ فرۆشتنێکی قیستی نییە.","No invoices match this filter.":"هیچ پسووڵەیەک لەگەڵ ئەم فلتەرە ناگونجێت.",
  "14 months":"١٤ مانگ","View 14 Payments":"بینینی ١٤ پارەدان","Payment":"پارەدان","Payments":"پارەدانەکان",
  "Record":"تۆمارکردن","Delete permanently":"سڕینەوەی هەمیشەیی","Restore item":"گەڕاندنەوەی دانە",
  "No records yet.":"هێشتا هیچ تۆمارێک نییە.","No phones found.":"هیچ مۆبایلێک نەدۆزرایەوە.",
  "Payment Deadlines":"کاتی وادەی پارەدان","Supplier Payment Deadlines":"وادەی پارەدانی دابینکەر","Customer Payment Deadlines":"وادەی پارەدانی کڕیار",
  "Overdue":"دواکەوتووە","Due Today":"ئەمڕۆ وادەیە","Upcoming":"لە داهاتوودا","No deadline set":"هیچ وادەیەک دانەنراوە","Deadline":"وادە","Days Overdue":"ڕۆژەکانی دواکەوتن","Customer Payment":"پارەدانی کڕیار","Installment":"قیست","Invoice Due Date":"بەرواری وادەی پسووڵە","Payment Deadline":"وادەی پارەدان","No overdue supplier payments.":"هیچ پارەدانێکی دابینکەر دواکەوتوو نییە.","No overdue customer payments.":"هیچ پارەدانی کڕیار دواکەوتوو نییە.","No supplier deadlines recorded.":"هیچ وادەیەکی پارەدانی دابینکەر تۆمار نەکراوە.","No customer installment deadlines recorded.":"هیچ وادەیەکی قیستی کڕیار تۆمار نەکراوە.",
  "SIM Type":"جۆری سیم","SIM Type (optional)":"جۆری سیم (ئارەزوومەندانە)","eSIM":"ئی-سیم","1 SIM":"١ سیم","2 SIM":"٢ سیم","Not specified":"دیارینەکراوە"
};
function translateText(text, lang) {
  const raw = String(text);
  const dict = lang === "ku" ? KU : Object.fromEntries(Object.entries(KU).map(([en,ku]) => [ku,en]));
  if (dict[raw]) return dict[raw];
  let out = raw;
  Object.keys(dict).sort((a,b)=>b.length-a.length).forEach(k=>{ if(out.includes(k)) out=out.split(k).join(dict[k]); });
  return out;
}
function LanguageTranslator({ language }) {
  useEffect(() => {
    document.documentElement.lang = language === "ku" ? "ku" : "en";
    document.documentElement.dir = language === "ku" ? "rtl" : "ltr";
    document.body.style.direction = language === "ku" ? "rtl" : "ltr";
    const translate = () => {
      const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
      const nodes = [];
      let n; while ((n = walker.nextNode())) {
        if (!n.nodeValue.trim()) continue;
        const el = n.parentElement;
        if (el && !["SCRIPT","STYLE","NOSCRIPT","TEXTAREA"].includes(el.tagName)) nodes.push(n);
      }
      nodes.forEach(n => { n.nodeValue = translateText(n.nodeValue, language); });
      document.querySelectorAll("input[placeholder],textarea[placeholder],button[title]").forEach(el => {
        const attr = el.hasAttribute("placeholder") ? "placeholder" : "title";
        el.setAttribute(attr, translateText(el.getAttribute(attr), language));
      });
    };
    translate();
    const obs = new MutationObserver(() => translate());
    obs.observe(document.body, {childList:true, subtree:true});
    return () => { obs.disconnect(); document.documentElement.dir="ltr"; document.body.style.direction="ltr"; };
  }, [language]);
  return null;
}

function App() {
  useFonts();
  useDesignSystem();
  const [loading, setLoading] = useState(true);
  const [saveError, setSaveError] = useState("");
  const [pullDistance, setPullDistance] = useState(0);
  const pullStartYRef = useRef(null);
  const pullTrackingRef = useRef(false);
  const pullDistanceRef = useRef(0);
  const pullTriggeredRef = useRef(false);
  const [section, setSection] = useState("home");
  const [language, setLanguage] = useState(() => localStorage.getItem(LANGUAGE_KEY) || "en");
  const [settings, setSettings] = useState(DEFAULT_SETTINGS);
  const [phones, setPhones] = useState([]);
  const [invoices, setInvoices] = useState([]);
  const [payments, setPayments] = useState([]);
  const [customerPayments, setCustomerPayments] = useState([]);
  const [activityLog, setActivityLog] = useState([]);
  const [recycleBin, setRecycleBin] = useState([]);
  const [supplierReturns, setSupplierReturns] = useState([]);
  const [notifications, setNotifications] = useState([]);
  // Global search results open a detail modal directly on top of whatever screen is
  // currently showing, rather than always dropping the user onto a list section.
  const [globalDetail, setGlobalDetail] = useState(null); // { type: 'phone' | 'contact' | 'invoice', id }
  const openDetail = (type, id) => setGlobalDetail({ type, id });
  const closeDetail = () => setGlobalDetail(null);
  const navigateFromDetail = (sec) => { setGlobalDetail(null); setSection(sec); };
  // Undo keeps a short local history of the complete business data state.
  // One user action that changes several tables (for example deleting an invoice
  // and its phones/payments) is treated as one undoable action.
  const undoStackRef = useRef([]);
  const undoBatchRef = useRef(false);
  const undoingRef = useRef(false);
  const [undoCount, setUndoCount] = useState(0);
  useEffect(() => { localStorage.setItem(LANGUAGE_KEY, language); }, [language]);
  useEffect(() => {
    // Native-feeling pull-to-refresh for the PWA. It only activates when the
    // page is already scrolled to the very top, so normal vertical scrolling
    // elsewhere is unaffected.
    const onTouchStart = (e) => {
      if (e.touches.length !== 1 || window.scrollY > 2) return;
      pullStartYRef.current = e.touches[0].clientY;
      pullTrackingRef.current = true;
      pullTriggeredRef.current = false;
    };
    const onTouchMove = (e) => {
      if (!pullTrackingRef.current || pullStartYRef.current == null || window.scrollY > 2) return;
      const dy = e.touches[0].clientY - pullStartYRef.current;
      if (dy <= 0) { pullDistanceRef.current = 0; setPullDistance(0); return; }
      const distance = Math.min(92, dy * 0.55);
      pullDistanceRef.current = distance;
      setPullDistance(distance);
      if (distance > 8) e.preventDefault();
    };
    const onTouchEnd = () => {
      if (!pullTrackingRef.current) return;
      const distance = pullDistanceRef.current;
      pullTrackingRef.current = false;
      pullDistanceRef.current = 0;
      pullStartYRef.current = null;
      setPullDistance(0);
      if (distance >= 58 && !pullTriggeredRef.current) {
        pullTriggeredRef.current = true;
        window.location.reload();
      }
    };
    document.addEventListener("touchstart", onTouchStart, { passive: true });
    document.addEventListener("touchmove", onTouchMove, { passive: false });
    document.addEventListener("touchend", onTouchEnd, { passive: true });
    document.addEventListener("touchcancel", onTouchEnd, { passive: true });
    return () => {
      document.removeEventListener("touchstart", onTouchStart);
      document.removeEventListener("touchmove", onTouchMove);
      document.removeEventListener("touchend", onTouchEnd);
      document.removeEventListener("touchcancel", onTouchEnd);
    };
  }, []);


  useEffect(() => {
    (async () => {
      const out = {};
      for (const key of STORAGE_KEYS) {
        try {
          const r = await window.storage.get(key, false);
          out[key] = r ? JSON.parse(r.value) : defaultFor(key);
        } catch (e) {
          out[key] = defaultFor(key);
        }
      }
      setSettings(migrateSettings({ ...DEFAULT_SETTINGS, ...out.settings }));
      const migratedPhones = migratePhones(out.phones || []);
      setPhones(migratedPhones);
      // Persist the migrated phone records so the old "256/6" format is converted
      // once and is available as separate storage + RAM fields thereafter.
      if (JSON.stringify(migratedPhones) !== JSON.stringify(out.phones || [])) {
        try { await window.storage.set("phones", JSON.stringify(migratedPhones), false); } catch (e) {}
      }
      setInvoices(out.invoices || []);
      setPayments(out.payments || []);
      setCustomerPayments(out.customerPayments || []);
      setActivityLog(out.activityLog || []);
      setRecycleBin(out.recycleBin || []);
      setSupplierReturns(out.supplierReturns || []);
      setLoading(false);
    })();
  }, []);

  // Notifications load separately from the main STORAGE_KEYS loop since they live
  // under a per-device key (see notificationsStorageKey). notifications.js (loaded
  // outside React) writes new "someone else changed something" entries straight into
  // storage and fires this event so the Notifications section and its home-screen
  // badge update live, even while the app is already open.
  useEffect(() => {
    const load = async () => {
      try {
        const r = await window.storage.get(notificationsStorageKey(), false);
        setNotifications(r ? JSON.parse(r.value) || [] : []);
      } catch { setNotifications([]); }
    };
    load();
    window.addEventListener("karwan:notifications-changed", load);
    return () => window.removeEventListener("karwan:notifications-changed", load);
  }, []);

  // Automatic daily backup: checked once when the app opens, again if the
  // tab is left open across midnight, and again if the app regains focus
  // (e.g. the user switches back to it the next day).
  useEffect(() => {
    const runCheck = () => {
      window.autoBackup?.checkDaily(() => window.storage.exportBackup(STORAGE_KEYS)).catch(() => {});
    };
    runCheck();
    const interval = setInterval(runCheck, 60 * 60 * 1000); // hourly re-check
    const onVisible = () => { if (document.visibilityState === "visible") runCheck(); };
    document.addEventListener("visibilitychange", onVisible);
    return () => { clearInterval(interval); document.removeEventListener("visibilitychange", onVisible); };
  }, []);

  const persist = useCallback(async (key, value) => {
    try {
      const res = await window.storage.set(key, JSON.stringify(value), false);
      if (!res) setSaveError("Save failed — your last change may not have been stored.");
      else setSaveError("");
    } catch (e) {
      setSaveError("Save failed — your last change may not have been stored.");
    }
  }, []);

  const recordUndo = () => {
    if (undoingRef.current || undoBatchRef.current) return;
    undoBatchRef.current = true;
    undoStackRef.current.push({
      settings: JSON.parse(JSON.stringify(settings)),
      phones: JSON.parse(JSON.stringify(phones)),
      invoices: JSON.parse(JSON.stringify(invoices)),
      payments: JSON.parse(JSON.stringify(payments)),
      customerPayments: JSON.parse(JSON.stringify(customerPayments)),
      recycleBin: JSON.parse(JSON.stringify(recycleBin)),
      supplierReturns: JSON.parse(JSON.stringify(supplierReturns)),
    });
    // Keep the history small and safe for phones with many records.
    if (undoStackRef.current.length > 20) undoStackRef.current.shift();
    setUndoCount(undoStackRef.current.length);
    setTimeout(() => { undoBatchRef.current = false; }, 0);
  };

  const updateSettings = (next) => { recordUndo(); setSettings(next); persist("settings", next); };
  const updatePhones = (next) => { recordUndo(); setPhones(next); persist("phones", next); };
  const updateInvoices = (next) => { recordUndo(); setInvoices(next); persist("invoices", next); };
  const updatePayments = (next) => { recordUndo(); setPayments(next); persist("payments", next); };
  const updateSupplierReturns = (next) => { recordUndo(); setSupplierReturns(next); persist("supplierReturns", next); };
  const updateCustomerPayments = (next) => { recordUndo(); setCustomerPayments(next); persist("customerPayments", next); };
  const updateActivity = (next) => { setActivityLog(next); persist("activityLog", next); };
  const updateNotifications = (next) => { setNotifications(next); persist(notificationsStorageKey(), next); };

  const undoLastChange = async () => {
    const snapshot = undoStackRef.current.pop();
    if (!snapshot) return;
    undoingRef.current = true;
    setUndoCount(undoStackRef.current.length);
    setSettings(snapshot.settings);
    setPhones(snapshot.phones);
    setInvoices(snapshot.invoices);
    setPayments(snapshot.payments);
    setCustomerPayments(snapshot.customerPayments);
    setRecycleBin(snapshot.recycleBin || []);
    setSupplierReturns(snapshot.supplierReturns || []);
    await Promise.all([
      persist("settings", snapshot.settings),
      persist("phones", snapshot.phones),
      persist("invoices", snapshot.invoices),
      persist("payments", snapshot.payments),
      persist("customerPayments", snapshot.customerPayments),
      persist("recycleBin", snapshot.recycleBin || []),
      persist("supplierReturns", snapshot.supplierReturns || []),
    ]);
    undoingRef.current = false;
  };

  const logActivity = (action, entity, details = {}) => {
    const entry = { id: uid(), timestamp: nowISO(), action, entity, ...details };
    updateActivity([entry, ...activityLog].slice(0, 500));
  };

  const unreadNotifications = useMemo(() => notifications.filter((n) => !n.read).length, [notifications]);

  /* ---------- derived maps ---------- */
  const invoiceMap = useMemo(() => Object.fromEntries(invoices.map((i) => [i.id, i])), [invoices]);
  const paymentsByInvoice = useMemo(() => {
    const m = {};
    payments.forEach((p) => { (m[p.invoiceId] = m[p.invoiceId] || []).push(p); });
    return m;
  }, [payments]);
  // Converts a supplier-payment amount into a target currency. Payments carry their own
  // currency + exchange rate (the rate in effect the day cash was handed over); older
  // payment records made before this field existed fall back to the invoice's rate.
  const paymentAmountInCurrency = (payment, targetCurrency, inv) => {
    const amt = Number(payment?.amount) || 0;
    const cur = payment?.currency || inv?.currency || "USD";
    const rate = Number(payment?.exchangeRate) > 0 ? Number(payment.exchangeRate)
      : (Number(inv?.exchangeRate) > 0 ? Number(inv.exchangeRate) : (Number(settings?.exchangeRate) || 1));
    return convertCurrency(amt, cur, targetCurrency, rate);
  };

  const invoiceTotals = useMemo(() => {
    const m = {};
    invoices.forEach((inv) => {
      const invPhones = phones.filter((p) => p.invoiceId === inv.id);
      // Returned phones no longer count toward what's owed to the supplier.
      const billablePhones = invPhones.filter((p) => p.status !== "returned");
      const invPayments = paymentsByInvoice[inv.id] || [];

      // Each phone (and each payment) can be in either currency and keeps the exchange
      // rate from the day it was recorded, so every total below is converted phone-by-phone
      // / payment-by-payment rather than assuming the whole invoice is one currency.
      const total = billablePhones.reduce((s, p) => s + purchaseCostInCurrency(p, inv.currency, invoices, settings), 0);
      const totalUSD = billablePhones.reduce((s, p) => s + purchaseCostInCurrency(p, "USD", invoices, settings), 0);
      const totalIQD = billablePhones.reduce((s, p) => s + purchaseCostInCurrency(p, "IQD", invoices, settings), 0);

      const paid = invPayments.reduce((s, p) => s + paymentAmountInCurrency(p, inv.currency, inv), 0);
      const paidUSD = invPayments.reduce((s, p) => s + paymentAmountInCurrency(p, "USD", inv), 0);
      const paidIQD = invPayments.reduce((s, p) => s + paymentAmountInCurrency(p, "IQD", inv), 0);

      const remaining = Math.max(0, total - paid);
      const remainingUSD = Math.max(0, totalUSD - paidUSD);
      const remainingIQD = Math.max(0, totalIQD - paidIQD);
      const status = remaining <= 0 ? "Paid" : paid > 0 ? "Partially Paid" : "Unpaid";
      m[inv.id] = {
        total, paid, remaining, status, phoneCount: invPhones.length,
        totalUSD, totalIQD, paidUSD, paidIQD, remainingUSD, remainingIQD,
      };
    });
    return m;
  }, [invoices, phones, paymentsByInvoice, settings]);

  const addToRecycleBin = (item) => {
    const next = [{ ...item, id: uid(), deletedAt: nowISO() }, ...recycleBin].slice(0, 500);
    setRecycleBin(next);
    persist("recycleBin", next);
  };

  /* ---------- shared data ops passed down ---------- */
  const ctx = {
    settings, updateSettings, phones, updatePhones, invoices, updateInvoices,
    payments, updatePayments, customerPayments, updateCustomerPayments, activityLog, logActivity, invoiceMap, invoiceTotals, paymentsByInvoice,
    notifications, updateNotifications, unreadNotifications,
    recycleBin, setRecycleBin, addToRecycleBin,
    supplierReturns, updateSupplierReturns,
    undoLastChange, undoCount, language, setLanguage,
    openDetail,
  };

  if (loading) {
    return (
      <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: C.bg, fontFamily: FONT, color: C.sub }}>
        Loading shop data…
      </div>
    );
  }

  const sectionMeta = SECTIONS.find((s) => s.id === section);

  return (
    <>
    <LanguageTranslator language={language} />
    <div style={{
      minHeight: "100vh", background: ACTIVE_BG || C.bg,
      backgroundSize: ACTIVE_BG ? "cover" : undefined,
      backgroundPosition: ACTIVE_BG ? "center" : undefined,
      backgroundAttachment: ACTIVE_BG ? "fixed" : undefined,
      fontFamily: FONT,
    }}>
      {pullDistance > 0 && (
        <div aria-live="polite" style={{
          position: "fixed", top: 0, left: 0, right: 0, zIndex: 200,
          height: Math.min(86, pullDistance), display: "flex", alignItems: "flex-end",
          justifyContent: "center", paddingBottom: 10, pointerEvents: "none",
          background: `linear-gradient(to bottom, ${C.bg}, transparent)`,
          fontFamily: FONT, color: C.sub, fontSize: 12, fontWeight: 700
        }}>
          <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <RefreshCw size={15} color={C.accent} style={{ transform: `rotate(${Math.min(180, pullDistance * 2.2)}deg)` }} />
            {pullDistance >= 58 ? "Release to refresh" : "Pull to refresh"}
          </span>
        </div>
      )}
      <div style={{ maxWidth: 640, margin: "0 auto", padding: "12px 16px 24px" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, marginBottom: 10, position: "sticky", top: 0, zIndex: 20, padding: "calc(env(safe-area-inset-top, 0px) + 14px) 0 8px", background: C.bg }}>
          {section === "home" ? (
            <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
              <div style={{ width: 32, height: 32, borderRadius: 9, background: C.accent, display: "flex", alignItems: "center", justifyContent: "center" }}>
                <Smartphone size={17} color="#fff" />
              </div>
              <div style={{ fontWeight: 800, fontSize: 15, color: C.ink }}>{settings.shopName}</div>
            </div>
          ) : (
            <button onClick={() => setSection("home")} aria-label="Back to home" style={{
              display: "flex", alignItems: "center", gap: 8, height: 44, borderRadius: 12, border: `1px solid ${C.border}`,
              background: C.primary, color: "#fff", padding: "0 14px 0 10px", cursor: "pointer", boxShadow: "0 2px 8px rgba(0,0,0,.06)",
              fontFamily: FONT, fontWeight: 700, fontSize: 13.5,
            }}>
              <ArrowLeft size={18} color="#fff" style={{ transform: language === "ku" ? "scaleX(-1)" : "none" }} /> Back
            </button>
          )}
          <div style={{ flex: 1 }} />
          {undoCount > 0 && (
            <Button
              size="sm"
              variant="primary"
              icon={History}
              onClick={undoLastChange}
              title="Undo the last change"
              style={{ opacity: 1, color: "#fff", background: C.primary, borderColor: C.primary }}
            >
              Undo ({undoCount})
            </Button>
          )}
        </div>
        {saveError && (
          <div style={{ background: C.dangerSoft, color: C.danger, padding: "8px 14px", borderRadius: 9, fontSize: 13, marginBottom: 14, display: "flex", alignItems: "center", gap: 8 }}>
            <AlertTriangle size={15} /> {saveError}
          </div>
        )}
        {section === "home" && <HomeScreen ctx={ctx} sections={SECTIONS} onOpen={setSection} />}
        {section === "notifications" && <NotificationsPage ctx={ctx} />}
        {section === "dashboard" && <Dashboard ctx={ctx} />}
        {section === "brands" && <Brands ctx={ctx} />}
        {section === "analytics" && <Analytics ctx={ctx} />}
        {section === "dateAnalysis" && <DateAnalysis ctx={ctx} />}
        {section === "purchases" && <Purchases ctx={ctx} />}
        {section === "sales" && <SalesStock ctx={ctx} mode="sales" />}
        {section === "stock" && <SalesStock ctx={ctx} mode="stock" />}
        {section === "returns" && <SupplierReturns ctx={ctx} />}
        {section === "payments" && <SupplierPayments ctx={ctx} />}
        {section === "customerPayments" && <CustomerPayments ctx={ctx} />}
        {section === "personalInfo" && <PersonalInformation ctx={ctx} />}
        {section === "reports" && <Reports ctx={ctx} />}
        {section === "debitAnalysis" && <DebitAnalysis ctx={ctx} />}
        {section === "balanceAnalysis" && <BalanceAnalysis ctx={ctx} />}
        {section === "currencyPnl" && <CurrencyPnL ctx={ctx} />}
        {section === "recycleBin" && <RecycleBin ctx={ctx} />}
        {section === "settings" && <SettingsPage ctx={ctx} />}
      </div>
    </div>
    {globalDetail?.type === "phone" && (
      <PhoneDetailModal ctx={ctx} phoneId={globalDetail.id} onClose={closeDetail} onNavigate={navigateFromDetail} />
    )}
    {globalDetail?.type === "invoice" && (
      <InvoiceDetailModal ctx={ctx} invoiceId={globalDetail.id} onClose={closeDetail} />
    )}
    {globalDetail?.type === "contact" && (
      <ContactDetailModal ctx={ctx} name={globalDetail.id} onClose={closeDetail} onNavigate={navigateFromDetail} />
    )}
    </>
  );
}

/* ---------------------------------- GLOBAL SEARCH ---------------------------------- */
// Single search box on the home screen that looks across phones (by brand/model/IMEI/
// color/sale customer), customers, suppliers and invoices at once, grouped by type.
// Tapping a result opens the section where that record lives.
function GlobalSearchResultGroup({ label, icon: Icon, children }) {
  return (
    <div style={{ padding: "4px 14px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 10.5, fontWeight: 700, letterSpacing: 0.4, textTransform: "uppercase", color: C.faint, margin: "8px 0 2px" }}>
        <Icon size={12} color={C.faint} /> {label}
      </div>
      {children}
    </div>
  );
}

function GlobalSearchResultRow({ title, sub, onClick, isLast }) {
  return (
    <button
      onClick={onClick}
      style={{
        display: "flex", flexDirection: "column", alignItems: "flex-start", width: "100%", textAlign: "left",
        background: "none", border: "none", borderBottom: isLast ? "none" : `1px solid ${C.border}`,
        padding: "8px 2px", cursor: "pointer", fontFamily: FONT,
      }}
    >
      <span style={{ fontSize: 13.5, fontWeight: 600, color: C.ink }}>{title}</span>
      {sub && <span style={{ fontSize: 11.5, color: C.sub, marginTop: 1 }}>{sub}</span>}
    </button>
  );
}

function GlobalSearch({ ctx }) {
  const { phones, invoices, settings, openDetail } = ctx;
  const [q, setQ] = useState("");
  const query = q.trim().toLowerCase();

  const results = useMemo(() => {
    if (!query) return null;
    const phoneMatches = phones.filter((p) =>
      (p.imei || "").toLowerCase().includes(query) ||
      (p.brand || "").toLowerCase().includes(query) ||
      (p.model || "").toLowerCase().includes(query) ||
      (p.color || "").toLowerCase().includes(query) ||
      (p.simType || "").toLowerCase().includes(query) ||
      (p.purchasedFrom || "").toLowerCase().includes(query) ||
      (p.sale?.customer || "").toLowerCase().includes(query)
    ).slice(0, 8);

    const customerMatches = (settings.customers || []).filter((c) => c.toLowerCase().includes(query)).slice(0, 6);
    const supplierMatches = (settings.suppliers || []).filter((s) => s.toLowerCase().includes(query)).slice(0, 6);
    const invoiceMatches = invoices.filter((i) =>
      (i.number || "").toLowerCase().includes(query) || (i.supplier || "").toLowerCase().includes(query)
    ).slice(0, 6);

    return { phoneMatches, customerMatches, supplierMatches, invoiceMatches };
  }, [query, phones, invoices, settings]);

  const hasResults = !!results && (
    results.phoneMatches.length || results.customerMatches.length || results.supplierMatches.length || results.invoiceMatches.length
  );

  return (
    <div style={{ position: "relative", marginBottom: 18 }}>
      <div style={{ position: "relative" }}>
        <Search size={16} color={C.faint} style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", pointerEvents: "none" }} />
        <Input
          value={q}
          onChange={(e) => setQ(e.target.value)}
          placeholder="Search phones, customers, suppliers, invoices…"
          style={{ paddingLeft: 34, paddingRight: q ? 34 : 10 }}
        />
        {q && (
          <button
            onClick={() => setQ("")}
            aria-label="Clear search"
            style={{ position: "absolute", right: 6, top: "50%", transform: "translateY(-50%)", background: "none", border: "none", cursor: "pointer", color: C.faint, padding: 6, display: "flex" }}
          >
            <X size={14} />
          </button>
        )}
      </div>

      {query && (
        <Card style={{ marginTop: 8, padding: hasResults ? "4px 0" : "18px", maxHeight: 360, overflowY: "auto" }}>
          {!hasResults && (
            <div style={{ textAlign: "center", color: C.faint, fontSize: 13 }}>No matches for "{q}"</div>
          )}
          {hasResults && results.phoneMatches.length > 0 && (
            <GlobalSearchResultGroup label="Phones" icon={Smartphone}>
              {results.phoneMatches.map((p, idx) => (
                <GlobalSearchResultRow
                  key={p.id}
                  isLast={idx === results.phoneMatches.length - 1}
                  title={`${p.brand} ${p.model}`}
                  sub={`IMEI ${p.imei} · ${p.status === "sold" ? "Sold" : p.status === "returned" ? "Returned" : "In stock"}`}
                  onClick={() => openDetail("phone", p.id)}
                />
              ))}
            </GlobalSearchResultGroup>
          )}
          {hasResults && results.customerMatches.length > 0 && (
            <GlobalSearchResultGroup label="Customers" icon={Users}>
              {results.customerMatches.map((c, idx) => (
                <GlobalSearchResultRow
                  key={c}
                  isLast={idx === results.customerMatches.length - 1}
                  title={c}
                  sub={settings.customerPhones?.[c] || "Customer"}
                  onClick={() => openDetail("contact", c)}
                />
              ))}
            </GlobalSearchResultGroup>
          )}
          {hasResults && results.supplierMatches.length > 0 && (
            <GlobalSearchResultGroup label="Suppliers" icon={Truck}>
              {results.supplierMatches.map((s, idx) => (
                <GlobalSearchResultRow
                  key={s}
                  isLast={idx === results.supplierMatches.length - 1}
                  title={s}
                  sub={settings.supplierPhones?.[s] || "Supplier"}
                  onClick={() => openDetail("contact", s)}
                />
              ))}
            </GlobalSearchResultGroup>
          )}
          {hasResults && results.invoiceMatches.length > 0 && (
            <GlobalSearchResultGroup label="Invoices" icon={ShoppingBag}>
              {results.invoiceMatches.map((i, idx) => (
                <GlobalSearchResultRow
                  key={i.id}
                  isLast={idx === results.invoiceMatches.length - 1}
                  title={i.number}
                  sub={i.supplier}
                  onClick={() => openDetail("invoice", i.id)}
                />
              ))}
            </GlobalSearchResultGroup>
          )}
        </Card>
      )}
    </div>
  );
}

/* ---------------------------------- SEARCH RESULT DETAIL MODALS ---------------------------------- */
// Lightweight read-only detail views opened directly from global search, so a result
// takes the user straight to the exact record instead of just its section's list.

function DetailField({ label, value }) {
  return (
    <div>
      <div style={{ fontSize: 11, color: C.faint, textTransform: "uppercase", letterSpacing: 0.3, marginBottom: 2 }}>{label}</div>
      <div style={{ fontSize: 13.5, fontWeight: 600, color: C.ink, wordBreak: "break-word" }}>{value ?? "-"}</div>
    </div>
  );
}

function PhoneDetailModal({ ctx, phoneId, onClose, onNavigate }) {
  const { phones, invoices, settings, openDetail } = ctx;
  const p = phones.find((x) => x.id === phoneId);
  if (!p) return null;
  const isSold = p.status === "sold";
  const isReturned = p.status === "returned";
  const isInstallment = isSold && p.sale?.saleType === "installment";
  const invoiceForPhone = p.purchaseType === "debit" && p.invoiceId ? invoices.find((i) => i.id === p.invoiceId) : null;

  return (
    <Modal title={`${p.brand} ${p.model}`} onClose={onClose} width={480}>
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <Badge tone={isSold ? "accent" : isReturned ? "danger" : "success"}>
            {isSold ? "Sold" : isReturned ? "Returned" : "In stock"}
          </Badge>
          <span style={{ fontFamily: MONO, fontSize: 12.5, color: C.sub }}>IMEI {p.imei}</span>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <DetailField label="Brand" value={p.brand} />
          <DetailField label="Model" value={p.model} />
          {p.color && <DetailField label="Color" value={p.color} />}
          {(p.storage || p.ram) && <DetailField label="Specs" value={phoneSpecLabel(p)} />}
          {p.simType && <DetailField label="SIM Type" value={p.simType} />}
          <DetailField label="Purchase type" value={p.purchaseType === "debit" ? "Debit (supplier invoice)" : "Cash purchase"} />
          <DetailField label="Purchase cost" value={fmtMoney(p.purchasePrice, p.purchaseCurrency)} />
          {p.purchasedFrom && <DetailField label="Purchased from" value={p.purchasedFrom} />}
          {p.date && <DetailField label="Purchase date" value={fmtDate(p.date)} />}
        </div>

        {isSold && p.sale && (
          <div style={{ borderTop: `1px solid ${C.border}`, paddingTop: 14 }}>
            <div style={{ fontSize: 11.5, fontWeight: 700, color: C.sub, marginBottom: 10, textTransform: "uppercase", letterSpacing: 0.4 }}>
              Sale details
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <DetailField label="Customer" value={p.sale.customer} />
              <DetailField label="Sale total" value={fmtMoney(p.sale.totalPrice ?? p.sale.price, p.sale.currency)} />
              <DetailField label="Sale type" value={p.sale.saleType === "installment" ? "Installment" : "Cash"} />
              <DetailField label="Profit" value={fmtMoney(saleProfit(p, invoices, settings), p.sale.currency)} />
              {p.sale.date && <DetailField label="Sale date" value={fmtDate(p.sale.date)} />}
            </div>
          </div>
        )}

        <div style={{ display: "flex", flexWrap: "wrap", justifyContent: "flex-end", gap: 8, paddingTop: 4 }}>
          <Button variant="ghost" onClick={onClose}>Close</Button>
          {invoiceForPhone && (
            <Button variant="subtle" onClick={() => openDetail("invoice", invoiceForPhone.id)}>View Invoice</Button>
          )}
          {isInstallment && (
            <Button variant="subtle" onClick={() => onNavigate("customerPayments")}>Customer Payments</Button>
          )}
          <Button onClick={() => onNavigate(isSold ? "sales" : "stock")}>
            {isSold ? "Open in Sales" : "Open in Stock"}
          </Button>
        </div>
      </div>
    </Modal>
  );
}

function ContactDetailModal({ ctx, name, onClose, onNavigate }) {
  const { settings, invoices, invoiceTotals, phones, openDetail } = ctx;

  const isSupplier = (settings.suppliers || []).includes(name) || invoices.some((i) => i.supplier === name);
  const isCustomer = (settings.customers || []).includes(name) || phones.some((p) => p.sale?.customer === name);

  const supplierInvoices = isSupplier ? invoices.filter((i) => i.supplier === name).sort((a, b) => new Date(b.date) - new Date(a.date)) : [];
  const supplierTotals = supplierInvoices.reduce((a, inv) => {
    const t = invoiceTotals[inv.id] || {};
    return {
      totalUSD: a.totalUSD + (t.totalUSD || 0), totalIQD: a.totalIQD + (t.totalIQD || 0),
      remainingUSD: a.remainingUSD + (t.remainingUSD || 0), remainingIQD: a.remainingIQD + (t.remainingIQD || 0),
    };
  }, { totalUSD: 0, totalIQD: 0, remainingUSD: 0, remainingIQD: 0 });
  const supplierOwes = supplierTotals.remainingUSD > 0.01 || supplierTotals.remainingIQD > 1;

  const customerPhonesList = isCustomer
    ? phones.filter((p) => p.status === "sold" && p.sale?.customer === name).sort((a, b) => new Date(b.sale.date) - new Date(a.sale.date))
    : [];
  const customerTotalUSD = customerPhonesList.reduce((s, p) => s + saleValueInCurrency(p, "USD", settings), 0);
  const customerTotalIQD = customerPhonesList.reduce((s, p) => s + saleValueInCurrency(p, "IQD", settings), 0);
  const hasInstallment = customerPhonesList.some((p) => p.sale?.saleType === "installment");

  const phone = settings.supplierPhones?.[name] || settings.customerPhones?.[name] || "";
  const location = settings.supplierLocations?.[name] || settings.customerLocations?.[name] || "";

  return (
    <Modal title={name} onClose={onClose} width={520}>
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          {isSupplier && <Badge tone="gold">Supplier</Badge>}
          {isCustomer && <Badge tone="accent">Customer</Badge>}
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <DetailField label="Phone" value={phone} />
          <DetailField label="Location" value={location} />
        </div>

        {isSupplier && (
          <div style={{ borderTop: `1px solid ${C.border}`, paddingTop: 14 }}>
            <div style={{ fontSize: 11.5, fontWeight: 700, color: C.sub, marginBottom: 10, textTransform: "uppercase", letterSpacing: 0.4 }}>
              Purchases ({supplierInvoices.length} invoice{supplierInvoices.length === 1 ? "" : "s"})
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 10 }}>
              <DetailField label="Total purchased" value={`${fmtMoney(supplierTotals.totalUSD, "USD")} / ${fmtMoney(supplierTotals.totalIQD, "IQD")}`} />
              <DetailField label="Still owed" value={`${fmtMoney(supplierTotals.remainingUSD, "USD")} / ${fmtMoney(supplierTotals.remainingIQD, "IQD")}`} />
            </div>
            {supplierInvoices.slice(0, 5).map((inv) => (
              <button
                key={inv.id}
                onClick={() => openDetail("invoice", inv.id)}
                style={{ display: "flex", justifyContent: "space-between", width: "100%", background: "none", border: "none", padding: "8px 0", borderBottom: `1px solid ${C.border}`, fontSize: 13, cursor: "pointer", fontFamily: FONT, color: C.ink, textAlign: "left" }}
              >
                <span style={{ fontWeight: 600 }}>{inv.number}</span><span style={{ color: C.sub }}>{fmtDate(inv.date)}</span>
              </button>
            ))}
          </div>
        )}

        {isCustomer && (
          <div style={{ borderTop: `1px solid ${C.border}`, paddingTop: 14 }}>
            <div style={{ fontSize: 11.5, fontWeight: 700, color: C.sub, marginBottom: 10, textTransform: "uppercase", letterSpacing: 0.4 }}>
              Purchases from us ({customerPhonesList.length} phone{customerPhonesList.length === 1 ? "" : "s"})
            </div>
            <div style={{ marginBottom: 10 }}>
              <DetailField label="Total bought" value={`${fmtMoney(customerTotalUSD, "USD")} / ${fmtMoney(customerTotalIQD, "IQD")}`} />
            </div>
            {customerPhonesList.slice(0, 5).map((p) => (
              <button
                key={p.id}
                onClick={() => openDetail("phone", p.id)}
                style={{ display: "flex", justifyContent: "space-between", width: "100%", background: "none", border: "none", padding: "8px 0", borderBottom: `1px solid ${C.border}`, fontSize: 13, cursor: "pointer", fontFamily: FONT, color: C.ink, textAlign: "left" }}
              >
                <span style={{ fontWeight: 600 }}>{p.brand} {p.model}</span><span style={{ color: C.sub, fontFamily: MONO }}>{p.imei}</span>
              </button>
            ))}
          </div>
        )}

        <div style={{ display: "flex", flexWrap: "wrap", justifyContent: "flex-end", gap: 8 }}>
          <Button variant="ghost" onClick={onClose}>Close</Button>
          {isSupplier && <Button variant="subtle" onClick={() => onNavigate("purchases")}>Purchases</Button>}
          {isSupplier && supplierOwes && <Button variant="subtle" onClick={() => onNavigate("payments")}>Supplier Payments</Button>}
          {isCustomer && <Button variant="subtle" onClick={() => onNavigate("sales")}>Sales</Button>}
          {isCustomer && hasInstallment && <Button variant="subtle" onClick={() => onNavigate("customerPayments")}>Customer Payments</Button>}
          <Button onClick={() => onNavigate("personalInfo")}>Personal Info</Button>
        </div>
      </div>
    </Modal>
  );
}

/* ---------------------------------- HOME SCREEN ---------------------------------- */
// Phone-style home screen: every section is an app icon in a grid. Tapping one opens
// that section full-screen; the Back button in the top bar (rendered by the parent)
// is the only way back, mirroring how a phone's home screen and apps work.
// Semantic color per section, instead of an arbitrary color-by-index cycle.
// Money coming in = success, money owed out / destructive = danger,
// needs-attention = warning, inventory value = gold, core daily flows = accent/primary,
// low-frequency admin items = neutral (sub).
const SECTION_TONES = {
  notifications: "accent",
  dashboard: "primary",
  purchases: "primary",
  sales: "accent",
  stock: "gold",
  analytics: "accent",
  returns: "warning",
  payments: "danger",
  customerPayments: "success",
  personalInfo: "primary",
  recycleBin: "danger",
  settings: "neutral",
};
function sectionToneColor(id) {
  const tone = SECTION_TONES[id] || "primary";
  if (tone === "neutral") return C.sub;
  return { primary: C.primary, accent: C.accent, success: C.success, warning: C.warning, danger: C.danger, gold: C.gold }[tone];
}

// Home tiles are grouped by what the user actually does with them, rather than
// a flat "primary row + more row" split. Notifications lives in the header as
// a small bell button instead of taking up a grid slot.
const HOME_GROUPS = [
  { label: "Purchase & Sales", ids: ["purchases", "sales", "stock", "returns"] },
  { label: "Payments", ids: ["customerPayments", "payments"] },
  { label: "Analytics", ids: ["dashboard", "brands", "analytics", "personalInfo"] },
  { label: "More", ids: ["settings", "recycleBin"] },
];

function HomeTile({ s, size = "large", onOpen, badge }) {
  const tone = sectionToneColor(s.id);
  const boxSize = size === "large" ? 58 : 46;
  const iconSize = size === "large" ? 26 : 20;
  return (
    <button
      onClick={() => onOpen(s.id)}
      style={{
        display: "flex", flexDirection: "column", alignItems: "center", gap: 8,
        background: "transparent", border: "none", cursor: "pointer", padding: 4, fontFamily: FONT,
      }}
    >
      <div style={{ position: "relative" }}>
        <div style={{
          width: boxSize, height: boxSize, borderRadius: size === "large" ? 17 : 14, background: tone + "1A",
          border: `1px solid ${tone}33`, display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          <s.icon size={iconSize} color={tone} />
        </div>
        {badge > 0 && (
          <span style={{
            position: "absolute", top: -4, right: -4, minWidth: 18, height: 18, padding: "0 4px",
            borderRadius: 999, background: C.danger, color: "#fff", fontSize: 10.5, fontWeight: 800,
            display: "flex", alignItems: "center", justifyContent: "center", border: `2px solid ${C.bg}`,
          }}>
            {badge > 99 ? "99+" : badge}
          </span>
        )}
      </div>
      <span style={{ fontSize: size === "large" ? 11.5 : 10.5, fontWeight: 600, color: C.ink, textAlign: "center", lineHeight: 1.25 }}>{s.label}</span>
    </button>
  );
}

function HomeQuickStats({ ctx }) {
  const { phones } = ctx;
  const today = todayDate();
  const inStockList = phones.filter((p) => p.status === "in_stock");
  const soldTodayList = phones.filter((p) => p.status === "sold" && (p.sale?.date || "").slice(0, 10) === today);
  const soldTodayNames = soldTodayList.map((p) => `${p.brand} ${p.model}`.trim()).filter(Boolean);

  return (
    <div style={{ display: "flex", gap: 10, marginBottom: 14 }}>
      <div style={{ flex: 1, background: C.surface, border: `1px solid ${C.border}`, borderRadius: 14, padding: "10px 14px" }}>
        <div style={{ fontFamily: MONO, fontSize: 20, fontWeight: 800, color: C.gold }}>{inStockList.length}</div>
        <div style={{ fontSize: 11, color: C.sub, marginTop: 2 }}>In stock</div>
      </div>
      <div style={{ flex: 1, background: C.surface, border: `1px solid ${C.border}`, borderRadius: 14, padding: "10px 14px", minWidth: 0 }}>
        <div style={{ fontFamily: MONO, fontSize: 20, fontWeight: 800, color: C.success }}>{soldTodayList.length}</div>
        <div style={{ fontSize: 11, color: C.sub, marginTop: 2 }}>Sold today</div>
        {soldTodayNames.length > 0 && (
          <div style={{ fontSize: 10, color: C.faint, marginTop: 3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
            {soldTodayNames.join(", ")}
          </div>
        )}
      </div>
    </div>
  );
}

// One side (customer or supplier) of the Payments Due card: who it's for, when
// it's due, and how much — colored red if overdue, gold if due soon.
function PaymentsDueSide({ label, name, dueDate, amount, currency, overdue, empty, onClick }) {
  const today = todayDate();
  let dueLabel = "No deadline";
  if (dueDate) {
    const days = Math.round((new Date(dueDate + "T12:00:00") - new Date(today + "T12:00:00")) / 86400000);
    if (overdue) dueLabel = `Overdue by ${Math.abs(days)}d`;
    else if (days === 0) dueLabel = "Due today";
    else if (days === 1) dueLabel = "Due tomorrow";
    else dueLabel = `Due in ${days}d`;
  }
  return (
    <button onClick={onClick} style={{
      flex: 1, textAlign: "left", background: "transparent", border: "none", cursor: onClick ? "pointer" : "default",
      padding: "9px 11px", fontFamily: FONT, minWidth: 0,
    }}>
      <div style={{ fontSize: 10.5, color: C.sub, marginBottom: 2 }}>{label}</div>
      {empty ? (
        <div style={{ fontSize: 12.5, color: C.faint }}>Nothing due</div>
      ) : (
        <>
          <div style={{ fontSize: 13.5, fontWeight: 700, color: C.ink, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{name}</div>
          <div style={{ fontSize: 11, marginTop: 1, color: overdue ? C.danger : C.gold }}>
            {dueLabel} · {fmtMoney(amount, currency)}
          </div>
        </>
      )}
    </button>
  );
}

function HomePaymentsDue({ ctx, onOpen }) {
  const { phones, invoices, invoiceTotals, customerPayments } = ctx;
  const { supplierDeadlines, customerDeadlines } = computeDeadlines({ phones, invoices, invoiceTotals, customerPayments });

  const nextSupplier = supplierDeadlines[0];
  const nextCustomer = customerDeadlines[0];

  return (
    <div style={{ background: C.surface, border: `1px solid ${C.border}`, borderRadius: 14, padding: "12px 4px 4px", marginBottom: 18 }}>
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".04em", textTransform: "uppercase", color: C.faint, margin: "0 10px 8px" }}>
        Payments Due
      </div>
      <div style={{ display: "flex", gap: 1, background: C.border, borderRadius: 10, overflow: "hidden" }}>
        <div style={{ flex: 1, background: C.surface }}>
          <PaymentsDueSide
            label="Customer"
            empty={!nextCustomer}
            name={nextCustomer?.phone?.sale?.customer}
            dueDate={nextCustomer?.item?.dueDate}
            amount={nextCustomer?.remaining}
            currency={nextCustomer?.phone?.sale?.currency}
            overdue={nextCustomer?.overdue}
            onClick={() => onOpen("customerPayments")}
          />
        </div>
        <div style={{ flex: 1, background: C.surface }}>
          <PaymentsDueSide
            label="Supplier"
            empty={!nextSupplier}
            name={nextSupplier?.supplier}
            dueDate={nextSupplier?.dueDate}
            amount={nextSupplier?.t?.remaining}
            currency={nextSupplier?.currency}
            overdue={nextSupplier?.overdue}
            onClick={() => onOpen("payments")}
          />
        </div>
      </div>
    </div>
  );
}

function HomeNotificationButton({ unreadNotifications, onOpen }) {
  const tone = sectionToneColor("notifications");
  return (
    <button
      onClick={() => onOpen("notifications")}
      aria-label="Notifications"
      style={{
        width: 32, height: 32, borderRadius: 9, background: tone + "1A", border: `1px solid ${tone}33`,
        display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", flexShrink: 0, position: "relative",
      }}
    >
      <Bell size={14} color={tone} />
      {unreadNotifications > 0 && (
        <span style={{
          position: "absolute", top: -4, right: -4, minWidth: 16, height: 16, padding: "0 3px",
          borderRadius: 999, background: C.danger, color: "#fff", fontSize: 9.5, fontWeight: 800,
          display: "flex", alignItems: "center", justifyContent: "center", border: `2px solid ${C.bg}`,
        }}>
          {unreadNotifications > 99 ? "99+" : unreadNotifications}
        </span>
      )}
    </button>
  );
}

function HomeScreen({ ctx, sections, onOpen }) {
  const { settings, unreadNotifications } = ctx;
  const byId = Object.fromEntries(sections.map((s) => [s.id, s]));

  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 2px 14px" }}>
        <div style={{ width: 34, height: 34, borderRadius: 10, background: C.accent, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
          <Smartphone size={16} color="#fff" />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 800, fontSize: 15, color: C.ink, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{settings.shopName}</div>
        </div>
        <div style={{ fontSize: 11.5, color: C.sub, whiteSpace: "nowrap" }}>1 USD = {Number(settings.exchangeRate || 0).toLocaleString()} IQD</div>
        <HomeNotificationButton unreadNotifications={unreadNotifications} onOpen={onOpen} />
      </div>
      <GlobalSearch ctx={ctx} />
      <HomeQuickStats ctx={ctx} />
      <HomePaymentsDue ctx={ctx} onOpen={onOpen} />

      {HOME_GROUPS.map((group) => {
        const groupSections = group.ids.map((id) => byId[id]).filter(Boolean);
        if (!groupSections.length) return null;
        return (
          <div key={group.label} style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".04em", textTransform: "uppercase", color: C.faint, margin: "0 4px 10px" }}>
              {group.label}
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(78px, 1fr))", gap: "18px 10px" }}>
              {groupSections.map((s) => <HomeTile key={s.id} s={s} size="large" onOpen={onOpen} badge={0} />)}
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* ---------------------------------- DASHBOARD ---------------------------------- */


function DashboardVisuals({ stock, sold, returned, purchases, sales, profit }) {
  const total = Math.max(1, stock + sold + returned);
  const parts = [
    { label: "In stock", value: stock, color: C.accent },
    { label: "Sold", value: sold, color: C.primary },
    { label: "Returned", value: returned, color: C.danger },
  ];
  const max = Math.max(1, purchases, sales, profit);
  const bars = [
    { label: "Purchases", value: purchases, color: C.primary },
    { label: "Sales", value: sales, color: C.accent },
    { label: "Profit", value: Math.max(0, profit), color: C.success },
  ];

  return (
    <div className="karwan-chart-grid" style={{ display:"grid", gridTemplateColumns:"1fr 1.45fr", gap:16, marginBottom:22 }}>
      <Card style={{ padding:18 }}>
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:14 }}>
          <div>
            <div style={{ fontSize:15, fontWeight:800, color:C.ink }}>Inventory health</div>
            <div style={{ fontSize:11.5, color:C.sub, marginTop:3 }}>Current phone status</div>
          </div>
          <span style={{ fontSize:11, fontWeight:800, color:C.accent, background:C.accentSoft, padding:"5px 8px", borderRadius:999 }}>LIVE</span>
        </div>
        <div style={{ display:"flex", alignItems:"center", gap:20 }}>
          <div style={{ width:142, height:142, borderRadius:"50%", background:`conic-gradient(${C.accent} 0 ${(stock/total)*360}deg, ${C.primary} ${(stock/total)*360}deg ${((stock+sold)/total)*360}deg, ${C.danger} ${((stock+sold)/total)*360}deg 360deg)`, display:"grid", placeItems:"center", flex:"0 0 auto" }}>
            <div style={{ width:92, height:92, borderRadius:"50%", background:C.surface, display:"grid", placeItems:"center", textAlign:"center" }}>
              <div><div style={{ fontFamily:MONO, fontSize:24, fontWeight:800, color:C.ink }}>{stock+sold+returned}</div><div style={{ fontSize:10.5, color:C.sub }}>total phones</div></div>
            </div>
          </div>
          <div style={{ display:"grid", gap:11, minWidth:0 }}>
            {parts.map(p => <div key={p.label} style={{ display:"flex", alignItems:"center", gap:8 }}>
              <span style={{ width:9, height:9, borderRadius:3, background:p.color, flex:"0 0 auto" }} />
              <span style={{ fontSize:12, color:C.sub }}>{p.label}</span>
              <b style={{ marginLeft:"auto", fontFamily:MONO, fontSize:12.5, color:C.ink }}>{p.value}</b>
            </div>)}
          </div>
        </div>
      </Card>

      <Card style={{ padding:18 }}>
        <div style={{ marginBottom:14 }}>
          <div style={{ fontSize:15, fontWeight:800, color:C.ink }}>Financial overview</div>
          <div style={{ fontSize:11.5, color:C.sub, marginTop:3 }}>USD-equivalent performance</div>
        </div>
        <div style={{ display:"grid", gap:14 }}>
          {bars.map(b => <div key={b.label}>
            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:6 }}>
              <span style={{ fontSize:11.5, fontWeight:700, color:C.sub }}>{b.label}</span>
              <span style={{ fontFamily:MONO, fontSize:12, fontWeight:800, color:C.ink }}>{fmtMoney(b.value,"USD")}</span>
            </div>
            <div style={{ height:10, borderRadius:999, background:C.primarySoft, overflow:"hidden" }}>
              <div style={{ height:"100%", width:`${Math.max(2,(b.value/max)*100)}%`, background:b.color, borderRadius:999, transition:"width .4s ease" }} />
            </div>
          </div>)}
        </div>
      </Card>
    </div>
  );
}

function Dashboard({ ctx }) {
  const { phones, invoices, payments, invoiceTotals, activityLog, settings } = ctx;

  const debitPhones = phones.filter((p) => p.purchaseType === "debit");
  const cashPhones = phones.filter((p) => p.purchaseType === "cash");
  const soldPhones = phones.filter((p) => p.status === "sold");
  const stockPhones = phones.filter((p) => p.status === "in_stock");
  const debitStock = debitPhones.filter((p) => p.status === "in_stock").length;
  const cashStock = cashPhones.filter((p) => p.status === "in_stock").length;
  const debitSold = debitPhones.filter((p) => p.status === "sold").length;
  const cashSold = cashPhones.filter((p) => p.status === "sold").length;
  const returnedPhones = phones.filter((p) => p.status === "returned");

  const byCurrency = (list, field) => {
    const out = { USD: 0, IQD: 0 };
    list.forEach((x) => { out[x[field] || "USD"] = (out[x[field] || "USD"] || 0) + (Number(x.amountValue) || 0); });
    return out;
  };

  const invoiceRate = (inv) => (Number(inv.exchangeRate) > 0 ? Number(inv.exchangeRate) : (Number(settings.exchangeRate) || 1));
  const invoiceTotalConverted = { USD: 0, IQD: 0 };
  const paidConverted = { USD: 0, IQD: 0 };
  invoices.forEach((inv) => {
    const t = invoiceTotals[inv.id];
    const r = invoiceRate(inv);
    invoiceTotalConverted.USD += convertCurrency(t.total, inv.currency, "USD", r);
    invoiceTotalConverted.IQD += convertCurrency(t.total, inv.currency, "IQD", r);
    paidConverted.USD += convertCurrency(t.paid, inv.currency, "USD", r);
    paidConverted.IQD += convertCurrency(t.paid, inv.currency, "IQD", r);
  });
  const debtConverted = {
    USD: Math.max(0, invoiceTotalConverted.USD - paidConverted.USD),
    IQD: Math.max(0, invoiceTotalConverted.IQD - paidConverted.IQD),
  };

  const cashPurchaseConverted = { USD: 0, IQD: 0 };
  cashPhones.filter((p) => p.status !== "returned").forEach((p) => {
    cashPurchaseConverted.USD += purchaseCostInCurrency(p, "USD", invoices, settings);
    cashPurchaseConverted.IQD += purchaseCostInCurrency(p, "IQD", invoices, settings);
  });

  const totalPurchasesConverted = { USD: 0, IQD: 0 };
  phones.filter((p) => p.status !== "returned").forEach((p) => {
    totalPurchasesConverted.USD += purchaseCostInCurrency(p, "USD", invoices, settings);
    totalPurchasesConverted.IQD += purchaseCostInCurrency(p, "IQD", invoices, settings);
  });

  const salesTotals = { USD: 0, IQD: 0 };
  const profitTotals = { USD: 0, IQD: 0 };
  soldPhones.forEach((p) => {
    salesTotals.USD += saleValueInCurrency(p, "USD", settings);
    salesTotals.IQD += saleValueInCurrency(p, "IQD", settings);
    profitTotals.USD += saleProfitInCurrency(p, "USD", invoices, settings);
    profitTotals.IQD += saleProfitInCurrency(p, "IQD", invoices, settings);
  });

  const outstandingInvoices = invoices
    .map((inv) => ({ inv, t: invoiceTotals[inv.id] }))
    .filter((x) => x.t.remaining > 0)
    .sort((a, b) => b.t.remaining - a.t.remaining)
    .slice(0, 6);

  const stockValueUSD = stockPhones.reduce((s, p) => s + purchaseCostInCurrency(p, "USD", invoices, settings), 0);
  const stockValueIQD = stockPhones.reduce((s, p) => s + purchaseCostInCurrency(p, "IQD", invoices, settings), 0);

  // -------------------------------------------------------------------------------
  // RAW (non-converted) totals — the actual amount that was paid/received in each
  // currency, exactly as entered, with no exchange-rate math applied. This is kept
  // *in addition to* the converted USD/IQD-equivalent totals above, so a purchase
  // recorded in IQD only counts toward the IQD total here (not toward USD too).
  // -------------------------------------------------------------------------------
  const activePhones = phones.filter((p) => p.status !== "returned");
  const rawPurchases = { USD: 0, IQD: 0 };
  activePhones.forEach((p) => { const c = p.purchaseCurrency || "USD"; rawPurchases[c] = (rawPurchases[c] || 0) + (Number(p.purchasePrice) || 0); });

  const rawStockValue = { USD: 0, IQD: 0 };
  stockPhones.forEach((p) => { const c = p.purchaseCurrency || "USD"; rawStockValue[c] = (rawStockValue[c] || 0) + (Number(p.purchasePrice) || 0); });

  const rawCashPurchases = { USD: 0, IQD: 0 };
  cashPhones.filter((p) => p.status !== "returned").forEach((p) => { const c = p.purchaseCurrency || "USD"; rawCashPurchases[c] = (rawCashPurchases[c] || 0) + (Number(p.purchasePrice) || 0); });

  const rawInvoiceTotal = { USD: 0, IQD: 0 };
  const rawPaid = { USD: 0, IQD: 0 };
  invoices.forEach((inv) => {
    const t = invoiceTotals[inv.id];
    const c = inv.currency || "USD";
    rawInvoiceTotal[c] = (rawInvoiceTotal[c] || 0) + (Number(t.total) || 0);
    rawPaid[c] = (rawPaid[c] || 0) + (Number(t.paid) || 0);
  });
  const rawDebt = { USD: Math.max(0, rawInvoiceTotal.USD - rawPaid.USD), IQD: Math.max(0, rawInvoiceTotal.IQD - rawPaid.IQD) };

  const rawSales = { USD: 0, IQD: 0 };
  const rawProfit = { USD: 0, IQD: 0 };
  soldPhones.forEach((p) => {
    const c = p.sale?.currency || "USD";
    rawSales[c] = (rawSales[c] || 0) + (Number(p.sale?.totalPrice ?? p.sale?.price) || 0);
    rawProfit[c] = (rawProfit[c] || 0) + saleProfit(p, invoices, settings);
  });

  return (
    <div>
      <SectionHeader title="Dashboard" sub="Live overview of purchases, stock, debts and sales — amounts shown in both USD and IQD" />
      <div style={{ marginTop: -8, marginBottom: 16, fontSize: 12, color: C.sub }}>
        Each purchase and sale keeps the exchange rate that was set on the day it happened, so these USD/IQD totals stay accurate even though the dinar's rate moves day to day. Today's rate for new entries: <b>1 USD = {Number(settings.exchangeRate).toLocaleString()} IQD</b>.
      </div>

      <div style={{ marginTop: -8, marginBottom: 10, fontSize: 12, color: C.sub }}>
        The two cards below combine a phone count with its USD/IQD-equivalent value. The breakdown row shows how that count splits, and the dashed line at the bottom is the real "Actual" amount recorded, with no exchange-rate conversion applied.
      </div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 14, marginBottom: 16 }}>
        <CombinedStatCard
          icon={ShoppingBag} tone="primary" label="Total Purchases (All Phones)"
          count={phones.length} countLabel="phones purchased, all-time"
          usd={totalPurchasesConverted.USD} iqd={totalPurchasesConverted.IQD}
          breakdown={[
            { label: "Active", value: phones.length - returnedPhones.length, color: C.ink },
            { label: "Returned", value: returnedPhones.length, color: C.danger },
          ]}
          actualUsd={rawPurchases.USD} actualIqd={rawPurchases.IQD} actualLabel="Actual"
        />
        <CombinedStatCard
          icon={PackageX} tone="gold" label="Remaining in Stock"
          count={stockPhones.length} countLabel="phones currently in stock"
          usd={stockValueUSD} iqd={stockValueIQD}
          breakdown={[
            { label: "Debit", value: debitStock, color: C.ink },
            { label: "Cash", value: cashStock, color: C.ink },
          ]}
          actualUsd={rawStockValue.USD} actualIqd={rawStockValue.IQD} actualLabel="Actual stock value"
        />
        <StatCard icon={Undo2} label="Total Phones Returned" value={returnedPhones.length} sub="Returned to supplier" tone="danger" />
        <StatCard icon={PackageCheck} label="Total Sold" value={soldPhones.length} tone="accent" />
      </div>

      <div style={{ display: "flex", flexWrap: "wrap", gap: 14, marginBottom: 22 }}>
        <StatCard icon={Truck} label="Supplier Invoice Total" value={fmtMoney(invoiceTotalConverted.USD, "USD")} sub={fmtMoney(invoiceTotalConverted.IQD, "IQD")} tone="primary" extra={<ActualLine usd={rawInvoiceTotal.USD} iqd={rawInvoiceTotal.IQD} label="Actual invoice amount" />}  />
        <StatCard icon={CheckCircle2} label="Supplier Payments Made" value={fmtMoney(paidConverted.USD, "USD")} sub={fmtMoney(paidConverted.IQD, "IQD")} tone="success" extra={<ActualLine usd={rawPaid.USD} iqd={rawPaid.IQD} label="Actual paid" paid />}  />
        <StatCard icon={AlertTriangle} label="Supplier Debt Remaining" value={fmtMoney(debtConverted.USD, "USD")} sub={fmtMoney(debtConverted.IQD, "IQD")} tone="danger" extra={<ActualLine usd={rawDebt.USD} iqd={rawDebt.IQD} label="Actual debt remaining" />}  />
        <StatCard icon={Banknote} label="Cash Purchases" value={fmtMoney(cashPurchaseConverted.USD, "USD")} sub={fmtMoney(cashPurchaseConverted.IQD, "IQD")} tone="gold" extra={<ActualLine usd={rawCashPurchases.USD} iqd={rawCashPurchases.IQD} label="Actual purchase amount" />}  />
        <StatCard icon={DollarSign} label="Total Sales" value={fmtMoney(salesTotals.USD, "USD")} sub={fmtMoney(salesTotals.IQD, "IQD")} tone="accent" extra={<ActualLine usd={rawSales.USD} iqd={rawSales.IQD} label="Actual sales amount" />}  />
        <StatCard icon={CircleDollarSign} label="Total Profit" value={fmtMoney(profitTotals.USD, "USD")} sub={fmtMoney(profitTotals.IQD, "IQD")} tone="success" extra={<ActualLine usd={rawProfit.USD} iqd={rawProfit.IQD} label="Actual profit" />}  />
      </div>

      <DashboardVisuals
        stock={stockPhones.length}
        sold={soldPhones.length}
        returned={returnedPhones.length}
        purchases={totalPurchasesConverted.USD}
        sales={salesTotals.USD}
        profit={profitTotals.USD}
      />

      <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 16 }}>
        <Card style={{ padding: 18 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
            <h3 style={{ margin: 0, fontSize: 14.5, fontWeight: 700 }}>Outstanding Supplier Balances</h3>
            <Badge tone="danger">{outstandingInvoices.length} unpaid/partial</Badge>
          </div>
          {outstandingInvoices.length === 0 ? <EmptyState icon={CheckCircle2} text="No outstanding supplier balances." /> : (
            <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
              <thead><tr>{["Invoice", "Supplier", "Total", "Paid", "Remaining", "Status"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
              <tbody>
                {outstandingInvoices.map(({ inv, t }) => (
                  <tr key={inv.id} style={trStyle}>
                    <td style={tdStyle}><span style={{ fontFamily: MONO }}>{inv.number}</span></td>
                    <td style={tdStyle}>{inv.supplier}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(t.totalUSD, "USD")} / {fmtMoney(t.totalIQD, "IQD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(t.paidUSD, "USD")} / {fmtMoney(t.paidIQD, "IQD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700, color: C.danger }}>{fmtMoney(t.remainingUSD, "USD")} / {fmtMoney(t.remainingIQD, "IQD")}</td>
                    <td style={tdStyle}><StatusBadge status={t.status} /></td>
                  </tr>
                ))}
              </tbody>
            </table></div>
          )}
        </Card>

        <Card style={{ padding: 18 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
            <h3 style={{ margin: 0, fontSize: 14.5, fontWeight: 700 }}>Recent Activity</h3>
            <History size={15} color={C.sub} />
          </div>
          {activityLog.length === 0 ? <EmptyState icon={History} text="No activity recorded yet." /> : (
            <div style={{ display: "flex", flexDirection: "column", gap: 10, maxHeight: 320, overflowY: "auto" }}>
              {activityLog.slice(0, 10).map((a) => <ActivityRow key={a.id} a={a} />)}
            </div>
          )}
        </Card>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 16 }}>
        <Card style={{ padding: 18 }}>
          <h3 style={{ margin: "0 0 10px", fontSize: 14.5, fontWeight: 700 }}>Stock by Source</h3>
          <StockSourceRow label="Supplier / Debit" purchased={debitPhones.length} returned={debitPhones.filter(p => p.status === "returned").length} sold={debitSold} remaining={debitStock} />
          <StockSourceRow label="Cash Purchases" purchased={cashPhones.length} returned={cashPhones.filter(p => p.status === "returned").length} sold={cashSold} remaining={cashStock} />
          <StockSourceRow label="Overall" purchased={phones.length} returned={returnedPhones.length} sold={soldPhones.length} remaining={stockPhones.length} bold />
          {returnedPhones.length > 0 && (
            <div style={{ marginTop: 8, fontSize: 12, color: C.sub }}>
              <b style={{ color: C.ink }}>{returnedPhones.length}</b> phone{returnedPhones.length === 1 ? "" : "s"} returned to supplier{" "}
              (still counted in "Purchased" as history, but excluded from "Sold" and "Remaining")
            </div>
          )}
        </Card>
        <Card style={{ padding: 18 }}>
          <h3 style={{ margin: "0 0 10px", fontSize: 14.5, fontWeight: 700 }}>Currency Snapshot</h3>
          <CurrencyRow label="Supplier debt" usd={debtConverted.USD} iqd={debtConverted.IQD} actualUsd={rawDebt.USD} actualIqd={rawDebt.IQD} tone="danger" />
          <CurrencyRow label="Cash purchases" usd={cashPurchaseConverted.USD} iqd={cashPurchaseConverted.IQD} actualUsd={rawCashPurchases.USD} actualIqd={rawCashPurchases.IQD} tone="gold" />
          <CurrencyRow label="Sales" usd={salesTotals.USD} iqd={salesTotals.IQD} actualUsd={rawSales.USD} actualIqd={rawSales.IQD} tone="success" />
          <CurrencyRow label="Profit" usd={profitTotals.USD} iqd={profitTotals.IQD} actualUsd={rawProfit.USD} actualIqd={rawProfit.IQD} tone="success" />
        </Card>
      </div>
    </div>
  );
}

function CombinedMiniStat({ label, value, color }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 2 }}>
      <span style={{ fontSize: 10.5, color: C.sub, textTransform: "uppercase", letterSpacing: 0.3, fontWeight: 600 }}>{label}</span>
      <span style={{ fontFamily: MONO, fontSize: 13, fontWeight: 700, color: color || C.ink }}>{value}</span>
    </div>
  );
}

function CombinedStatCard({ icon: Icon, label, tone = "primary", count, countLabel, breakdown, usd, iqd, actualUsd, actualIqd, actualLabel = "Actual" }) {
  const toneColor = { primary: C.primary, accent: C.accent, success: C.success, warning: C.warning, danger: C.danger, gold: C.gold }[tone];
  return (
    <Card style={{ padding: 18, flex: "1 1 280px", minWidth: 260 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <span style={{ color: C.sub, fontSize: 12.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: 0.4 }}>{label}</span>
        <div style={{ width: 30, height: 30, borderRadius: 9, background: toneColor + "1A", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon size={16} color={toneColor} />
        </div>
      </div>

      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginTop: 12, paddingBottom: 12, borderBottom: `1px solid ${C.border}` }}>
        <div>
          <div style={{ fontFamily: MONO, fontSize: 26, fontWeight: 700, color: C.ink, lineHeight: 1 }}>{count}</div>
          <div style={{ fontSize: 11.5, color: C.sub, marginTop: 4 }}>{countLabel}</div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ fontFamily: MONO, fontSize: 17, fontWeight: 700, color: toneColor, lineHeight: 1.2 }}>{fmtMoney(usd, "USD")}</div>
          <div style={{ fontFamily: MONO, fontSize: 12, color: C.sub, marginTop: 2 }}>{fmtMoney(iqd, "IQD")}</div>
        </div>
      </div>

      {breakdown && breakdown.length > 0 && (
        <div style={{ display: "flex", gap: 18, marginTop: 12 }}>
          {breakdown.map((b) => <CombinedMiniStat key={b.label} {...b} />)}
        </div>
      )}

      <div style={{ marginTop: 10, paddingTop: 10, borderTop: `1px dashed ${C.border}`, fontSize: 11.5, color: C.sub }}>
        <ActualLine usd={actualUsd} iqd={actualIqd} label={actualLabel} />
      </div>
    </Card>
  );
}

function ActualLine({ usd, iqd, label = "Actual", paid = false }) {
  return (
    <span>
      <b style={{ color: C.ink }}>{label}:</b> {fmtMoney(usd, "USD")}{paid ? " paid in USD" : " USD"} · {fmtMoney(iqd, "IQD")}{paid ? " paid in IQD" : " IQD"}
    </span>
  );
}

function StockSourceRow({ label, purchased, returned = 0, sold, remaining, bold }) {
  const ratio = purchased ? sold / purchased : 0;
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "9px 0", borderBottom: `1px solid ${C.border}` }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <SignalBars ratio={ratio} />
        <span style={{ fontSize: 13.5, fontWeight: bold ? 700 : 600 }}>{label}</span>
      </div>
      <div style={{ display: "flex", gap: 14, fontFamily: MONO, fontSize: 12.5 }}>
        <span style={{ color: C.sub }}>Purchased <b style={{ color: C.ink }}>{purchased}</b></span>
        <span style={{ color: C.sub }}>Returned <b style={{ color: C.danger }}>{returned}</b></span>
        <span style={{ color: C.sub }}>Sold <b style={{ color: C.ink }}>{sold}</b></span>
        <span style={{ color: C.sub }}>Remaining <b style={{ color: C.accent }}>{remaining}</b></span>
      </div>
    </div>
  );
}
function CurrencyRow({ label, usd, iqd, actualUsd, actualIqd, tone }) {
  const color = { danger: C.danger, gold: C.gold, success: C.success }[tone];
  return (
    <div style={{ padding: "9px 0", borderBottom: `1px solid ${C.border}` }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <span style={{ fontSize: 13.5, fontWeight: 600 }}>{label}</span>
        <div style={{ display: "flex", gap: 10, fontFamily: MONO, fontSize: 12.5, fontWeight: 700, color }}>
          <span>{fmtMoney(usd, "USD")}</span><span style={{ color: C.faint }}>/</span><span>{fmtMoney(iqd, "IQD")}</span>
        </div>
      </div>
      {(actualUsd !== undefined || actualIqd !== undefined) && (
        <div style={{ fontSize: 11, color: C.faint, marginTop: 2, textAlign: "right" }}>
          Actual: {fmtMoney(actualUsd, "USD")} + {fmtMoney(actualIqd, "IQD")}
        </div>
      )}
    </div>
  );
}

function ActivityRow({ a }) {
  return (
    <div style={{ display: "flex", gap: 10 }}>
      <div style={{ width: 7, height: 7, borderRadius: 4, background: C.accent, marginTop: 5, flexShrink: 0 }} />
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: C.ink }}>{a.action}</div>
        <div style={{ fontSize: 12, color: C.sub, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
          {a.entity} {a.detailText ? `— ${a.detailText}` : ""}
        </div>
        <div style={{ fontSize: 11, color: C.faint }}>{fmtDateTime(a.timestamp)}</div>
      </div>
    </div>
  );
}

function StatusBadge({ status }) {
  if (status === "Paid") return <Badge tone="success"><CheckCircle2 size={11} />Paid</Badge>;
  if (status === "Partially Paid") return <Badge tone="warning"><Clock size={11} />Partial</Badge>;
  return <Badge tone="danger"><AlertTriangle size={11} />Unpaid</Badge>;
}

function SectionHeader({ title, sub, right }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 18, flexWrap: "wrap", gap: 10 }}>
      <div>
        <h1 style={{ margin: 0, fontSize: 22, fontWeight: 800, color: C.ink }}>{title}</h1>
        {sub && <p style={{ margin: "4px 0 0", fontSize: 13, color: C.sub }}>{sub}</p>}
      </div>
      {right}
    </div>
  );
}

const tableStyle = { width: "100%", borderCollapse: "collapse", fontSize: 13 };
const thStyle = { textAlign: "left", padding: "8px 10px", fontSize: 11.5, color: C.sub, textTransform: "uppercase", letterSpacing: 0.3, borderBottom: `1px solid ${C.border}` };
const tdStyle = { padding: "9px 10px", borderBottom: `1px solid ${C.border}`, color: C.ink };
const trStyle = {};

/* ---------------------------------- NOTIFICATIONS ---------------------------------- */

// One row in the notifications feed — a change someone else made on another
// device, tap to mark it read.
function NotificationRow({ n, onOpen }) {
  return (
    <button
      onClick={() => onOpen(n)}
      style={{
        display: "flex", alignItems: "flex-start", gap: 10, width: "100%", textAlign: "left",
        background: n.read ? "transparent" : C.accentSoft, border: "none", borderBottom: `1px solid ${C.border}`,
        padding: "12px 14px", cursor: "pointer", fontFamily: FONT,
      }}
    >
      <div style={{
        width: 34, height: 34, borderRadius: 10, flexShrink: 0, background: n.read ? C.primarySoft : C.accent + "26",
        display: "flex", alignItems: "center", justifyContent: "center", marginTop: 1,
      }}>
        <Bell size={16} color={n.read ? C.sub : C.accent} />
      </div>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ fontSize: 13.5, fontWeight: n.read ? 600 : 800, color: C.ink }}>
          {n.who || "Someone"} • {n.what || "shop data"}
        </div>
        <div style={{ fontSize: 11.5, color: C.sub, marginTop: 2 }}>{n.detail || "Shop data updated"}</div>
        <div style={{ fontSize: 11, color: C.faint, marginTop: 3 }}>{timeAgo(n.when)}</div>
      </div>
      {!n.read && <div style={{ width: 8, height: 8, borderRadius: 4, background: C.accent, marginTop: 6, flexShrink: 0 }} />}
    </button>
  );
}

function NotificationsPage({ ctx }) {
  const { notifications, updateNotifications, unreadNotifications } = ctx;

  const markRead = (n) => {
    if (n.read) return;
    updateNotifications(notifications.map((x) => (x.id === n.id ? { ...x, read: true } : x)));
  };
  const markAllRead = () => {
    updateNotifications(notifications.map((x) => (x.read ? x : { ...x, read: true })));
  };
  const clearAll = () => {
    if (notifications.length && !window.confirm("Clear all notifications? This can't be undone.")) return;
    updateNotifications([]);
  };

  return (
    <div>
      <SectionHeader
        title="Notifications"
        sub="Changes made by other devices on this shop's account — sync happens automatically, this is just the history."
        right={
          notifications.length > 0 ? (
            <div style={{ display: "flex", gap: 8 }}>
              {unreadNotifications > 0 && <Button size="sm" variant="subtle" onClick={markAllRead}>Mark all read</Button>}
              <Button size="sm" variant="ghost" onClick={clearAll}>Clear all</Button>
            </div>
          ) : null
        }
      />
      <NotificationsSettingsCard />
      <Card style={{ overflow: "hidden" }}>
        {notifications.length === 0 ? (
          <EmptyState icon={Bell} text="No notifications yet. You'll see it here whenever someone else on this shop's account makes a change." />
        ) : (
          notifications.map((n) => <NotificationRow key={n.id} n={n} onOpen={markRead} />)
        )}
      </Card>
    </div>
  );
}

/* ---------------------------------- PURCHASES ---------------------------------- */


function RecycleBin({ ctx }) {
  const { recycleBin, setRecycleBin, updatePhones, updateInvoices, updatePayments, updateSupplierReturns, supplierReturns, phones, invoices, payments, logActivity } = ctx;
  const sorted = [...recycleBin].sort((a, b) => new Date(b.deletedAt) - new Date(a.deletedAt));

  const restore = (item) => {
    if (!confirm(`Restore ${item.label}?`)) return;
    if (item.type === "invoice") {
      const inv = item.data.invoice;
      const invPhones = item.data.phones || [];
      const invPayments = item.data.payments || [];
      if (invoices.some(x => x.id === inv.id)) { alert("This invoice already exists and cannot be restored as a duplicate."); return; }
      const phoneIds = new Set(phones.map(p => p.id));
      const paymentIds = new Set(payments.map(p => p.id));
      updateInvoices([inv, ...invoices]);
      updatePhones([...invPhones.filter(p => !phoneIds.has(p.id)), ...phones]);
      updatePayments([...invPayments.filter(p => !paymentIds.has(p.id)), ...payments]);
    } else if (item.type === "phone") {
      const phone = item.data.phone;
      if (phones.some(p => p.id === phone.id)) { alert("This phone already exists and cannot be restored as a duplicate."); return; }
      updatePhones([phone, ...phones]);
    } else if (item.type === "payment") {
      const payment = item.data.payment;
      if (payments.some(p => p.id === payment.id)) { alert("This payment already exists and cannot be restored as a duplicate."); return; }
      updatePayments([payment, ...payments]);
    } else if (item.type === "supplierReturn") {
      const record = item.data.returnRecord;
      if (!record) { alert("This return record is invalid and cannot be restored."); return; }
      if (supplierReturns.some(r => r.id === record.id)) { alert("This supplier return already exists."); return; }
      const phone = phones.find(p => p.id === record.phoneId);
      if (!phone) { alert("The original phone no longer exists, so this return cannot be restored."); return; }
      if (phone.status === "sold") { alert("This phone has been sold, so the return cannot be restored."); return; }
      updatePhones(phones.map(p => p.id === phone.id ? { ...p, status: "returned" } : p));
      updateSupplierReturns([record, ...supplierReturns]);
    }
    const next = recycleBin.filter(x => x.id !== item.id);
    setRecycleBin(next);
    persistRecycleBin(next);
    logActivity("Item restored", "Recycle Bin", { detailText: item.label });
  };

  const permanentlyDelete = (item) => {
    if (!confirm(`Permanently delete ${item.label}? This cannot be undone.`)) return;
    const next = recycleBin.filter(x => x.id !== item.id);
    setRecycleBin(next);
    persistRecycleBin(next);
  };

  const empty = () => {
    if (!recycleBin.length) return;
    if (!confirm("Empty the Recycle Bin? All deleted items will be permanently removed and cannot be restored.")) return;
    setRecycleBin([]);
    persistRecycleBin([]);
  };

  const persistRecycleBin = async (next) => {
    try { await window.storage.set("recycleBin", JSON.stringify(next), false); } catch (e) {}
  };

  return (
    <div>
      <SectionHeader title="Recycle Bin" sub="Deleted invoices, phones and payments stay here until you restore or permanently delete them." />
      <div style={{ display: "flex", justifyContent: "flex-end", marginBottom: 14 }}>
        <Button size="sm" variant="danger" icon={Trash2} onClick={empty} disabled={!recycleBin.length}>Empty Recycle Bin</Button>
      </div>
      {sorted.length === 0 ? <Card><EmptyState icon={Trash2} text="Recycle Bin is empty. Deleted records will appear here." /></Card> : (
        <Card>
          <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
            <thead><tr>{["Type", "Item", "Deleted", "", ""].map((h, i) => <th key={i} style={thStyle}>{h}</th>)}</tr></thead>
            <tbody>
              {sorted.map(item => (
                <tr key={item.id}>
                  <td style={tdStyle}><Badge tone="danger">{item.type === "invoice" ? "Invoice" : item.type === "phone" ? "Phone" : "Payment"}</Badge></td>
                  <td style={tdStyle}>{item.label}</td>
                  <td style={tdStyle}>{fmtDateTime(item.deletedAt)}</td>
                  <td style={tdStyle}><Button size="sm" variant="subtle" icon={History} onClick={() => restore(item)}>Restore</Button></td>
                  <td style={tdStyle}><button title="Permanently delete" onClick={() => permanentlyDelete(item)} style={iconBtn}><Trash2 size={14} color={C.danger} /></button></td>
                </tr>
              ))}
            </tbody>
          </table></div>
        </Card>
      )}
    </div>
  );
}

function Purchases({ ctx }) {
  const [tab, setTab] = useState("debit");
  return (
    <div>
      <SectionHeader title="Purchases" sub="Record supplier/debit invoices and cash purchases" />
      <Tabs value={tab} onChange={setTab} options={[{ id: "debit", label: "Supplier / Debit" }, { id: "cash", label: "Cash Purchases" }]} />
      {tab === "debit" ? <DebitPurchases ctx={ctx} /> : <CashPurchases ctx={ctx} />}
    </div>
  );
}

function Tabs({ value, onChange, options }) {
  return (
    <div style={{ display: "flex", gap: 6, marginBottom: 16, borderBottom: `1px solid ${C.border}` }}>
      {options.map((o) => (
        <button key={o.id} onClick={() => onChange(o.id)} style={{
          padding: "9px 14px", background: "none", border: "none", cursor: "pointer",
          fontFamily: FONT, fontSize: 13.5, fontWeight: 700, color: value === o.id ? C.primary : C.sub,
          borderBottom: value === o.id ? `2px solid ${C.accent}` : "2px solid transparent", marginBottom: -1,
        }}>{o.label}</button>
      ))}
    </div>
  );
}

function DebitPurchases({ ctx }) {
  const { invoices, updateInvoices, phones, settings, logActivity, invoiceTotals } = ctx;
  const [showNew, setShowNew] = useState(false);
  const [openInvoice, setOpenInvoice] = useState(null);
  const [q, setQ] = useState("");

  const filtered = invoices.filter((inv) =>
    !q || inv.number.toLowerCase().includes(q.toLowerCase()) || inv.supplier.toLowerCase().includes(q.toLowerCase())
  ).sort((a, b) => new Date(b.date) - new Date(a.date));

  const createInvoice = (data) => {
    const inv = { id: uid(), number: data.number, supplier: data.supplier, supplierPhone: (data.supplierPhone || "").trim(), supplierLocation: (data.supplierLocation || "").trim(), date: data.date, dueDate: data.dueDate || "", currency: data.currency, exchangeRate: Number(data.exchangeRate) || settings.exchangeRate || 1, notes: data.notes, createdAt: nowISO() };
    updateInvoices([inv, ...invoices]);
    logActivity("Invoice created", "Purchases", { detailText: `${inv.number} — ${inv.supplier}` });
    setShowNew(false);
    setOpenInvoice(inv.id);
  };

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 14, gap: 10, flexWrap: "wrap" }}>
        <div style={{ position: "relative", flex: "1 1 240px", maxWidth: 320 }}>
          <Search size={14} style={{ position: "absolute", left: 10, top: 10, color: C.faint }} />
          <Input placeholder="Search invoice # or supplier" value={q} onChange={(e) => setQ(e.target.value)} style={{ paddingLeft: 30 }} />
        </div>
        <Button icon={Plus} onClick={() => setShowNew(true)}>New Supplier Invoice</Button>
      </div>

      {filtered.length === 0 ? <Card><EmptyState icon={Truck} text="No supplier invoices yet. Create one to start recording debit purchases." /></Card> : (
        <Card>
          <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
            <thead><tr>{["Invoice #", "Supplier", "Date", "Due Date", "Phones", "Total", "Paid", "Remaining", "Status", ""].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
            <tbody>
              {filtered.map((inv) => {
                const t = invoiceTotals[inv.id];
                return (
                  <tr key={inv.id} style={{ cursor: "pointer" }} onClick={() => setOpenInvoice(inv.id)}>
                    <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700 }}>{inv.number}</td>
                    <td style={tdStyle}>{inv.supplier}{inv.supplierPhone && <div style={{ fontSize: 11, color: C.faint, fontFamily: MONO }}>{inv.supplierPhone}</div>}{inv.supplierLocation && <div style={{ fontSize: 11, color: C.faint }}>{inv.supplierLocation}</div>}</td>
                    <td style={tdStyle}>{fmtDate(inv.date)}</td>
                    <td style={{...tdStyle,fontWeight:inv.dueDate && t.remaining>0 && inv.dueDate < todayDate() ? 700 : 400,color:inv.dueDate && t.remaining>0 && inv.dueDate < todayDate() ? C.danger : C.sub}}>{inv.dueDate ? fmtDate(inv.dueDate) : "-"}</td>
                    <td style={tdStyle}>{t.phoneCount}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(t.totalUSD, "USD")} <span style={{ color: C.faint }}>/</span> {fmtMoney(t.totalIQD, "IQD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(t.paidUSD, "USD")} <span style={{ color: C.faint }}>/</span> {fmtMoney(t.paidIQD, "IQD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700 }}>{fmtMoney(t.remainingUSD, "USD")} <span style={{ color: C.faint }}>/</span> {fmtMoney(t.remainingIQD, "IQD")}</td>
                    <td style={tdStyle}><StatusBadge status={t.status} /></td>
                    <td style={tdStyle}><ChevronRight size={15} color={C.faint} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table></div>
        </Card>
      )}

      {showNew && <NewInvoiceModal settings={settings} onClose={() => setShowNew(false)} onCreate={createInvoice} invoices={invoices} />}
      {openInvoice && <InvoiceDetailModal ctx={ctx} invoiceId={openInvoice} onClose={() => setOpenInvoice(null)} />}
    </div>
  );
}

function NewInvoiceModal({ settings, onClose, onCreate, invoices, editingInvoice }) {
  const isEditing = !!editingInvoice;
  const [number, setNumber] = useState(editingInvoice?.number || ("INV-" + String(invoices.length + 1).padStart(4, "0")));
  const [supplier, setSupplier] = useState(editingInvoice?.supplier || settings.suppliers[0] || "");
  const [supplierPhone, setSupplierPhone] = useState(
    editingInvoice?.supplierPhone || (settings.supplierPhones && settings.supplierPhones[supplier]) || ""
  );
  const [supplierLocation, setSupplierLocation] = useState(
    editingInvoice?.supplierLocation || (settings.supplierLocations && settings.supplierLocations[supplier]) || ""
  );
  const [date, setDate] = useState(editingInvoice?.date || todayDate());
  const [dueDate, setDueDate] = useState(editingInvoice?.dueDate || "");
  const [currency, setCurrency] = useState(editingInvoice?.currency || "USD");
  const [exchangeRate, setExchangeRate] = useState(editingInvoice?.exchangeRate || settings.exchangeRate || 1460);
  const [notes, setNotes] = useState(editingInvoice?.notes || "");
  return (
    <Modal title={`${isEditing ? "Edit" : "New"} Supplier Invoice`} onClose={onClose} confirmClose>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <Field label="Invoice Number"><Input value={number} onChange={(e) => setNumber(e.target.value)} /></Field>
        <Field label="Date"><Input type="date" value={date} onChange={(e) => setDate(e.target.value)} /></Field>
        <Field label="Supplier">
          <Select value={supplier} onChange={(e) => {
            const next = e.target.value;
            setSupplier(next);
            setSupplierPhone((settings.supplierPhones && settings.supplierPhones[next]) || "");
            setSupplierLocation((settings.supplierLocations && settings.supplierLocations[next]) || "");
          }}>
            {settings.suppliers.length === 0 && <option value="">Add a supplier in Settings first</option>}
            {settings.suppliers.map((s) => <option key={s} value={s}>{s}</option>)}
          </Select>
        </Field>
        <Field label="Supplier Phone Number (optional)">
          <Input value={supplierPhone} onChange={(e) => setSupplierPhone(e.target.value)} placeholder="e.g. 0770 123 4567" />
        </Field>
        <Field label="Supplier Location / Residence (optional)">
          <Input value={supplierLocation} onChange={(e) => setSupplierLocation(e.target.value)} placeholder="e.g. Sulaymaniyah, Bazaar Street" />
        </Field>
        <Field label="Payment Deadline">
          <Input type="date" value={dueDate} min={date} onChange={(e) => setDueDate(e.target.value)} />
        </Field>
        <Field label="Currency">
          <Select value={currency} onChange={(e) => setCurrency(e.target.value)}>
            <option value="USD">USD</option><option value="IQD">IQD</option>
          </Select>
        </Field>
        <Field label="Exchange Rate for This Invoice (1 USD = IQD)">
          <Input type="number" min="1" value={exchangeRate} onChange={(e) => setExchangeRate(e.target.value)} />
        </Field>
        <div style={{ gridColumn: "1 / -1" }}>
          <Field label="Notes"><TextArea value={notes} onChange={(e) => setNotes(e.target.value)} /></Field>
        </div>
      </div>
      <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 18 }}>
        <Button variant="ghost" onClick={onClose}>Discard</Button>
        <Button disabled={!supplier || !number} onClick={() => onCreate({ number, supplier, supplierPhone, supplierLocation, date, dueDate, currency, exchangeRate, notes })}>{isEditing ? "Save Changes" : "Save Invoice"}</Button>
      </div>
    </Modal>
  );
}

function InvoiceDetailModal({ ctx, invoiceId, onClose }) {
  const { invoices, updateInvoices, phones, updatePhones, payments, updatePayments, logActivity, invoiceTotals, settings, addToRecycleBin, undoLastChange, undoCount } = ctx;
  const inv = invoices.find((i) => i.id === invoiceId);
  const [showAddPhone, setShowAddPhone] = useState(false);
  const [showPay, setShowPay] = useState(false);
  const [editPayment, setEditPayment] = useState(null);
  const [editInvoice, setEditInvoice] = useState(false);
  const [editPhone, setEditPhone] = useState(null);
  const [phoneDeletedForUndo, setPhoneDeletedForUndo] = useState(false);
  if (!inv) return null;
  const t = invoiceTotals[inv.id];
  const invPhones = phones.filter((p) => p.invoiceId === inv.id);
  const invPayments = payments.filter((p) => p.invoiceId === inv.id).sort((a, b) => new Date(b.date) - new Date(a.date));

  const saveInvoice = (data) => {
    const next = invoices.map((x) => x.id === inv.id ? { ...x, ...data, exchangeRate: Number(data.exchangeRate) || settings.exchangeRate || 1 } : x);
    updateInvoices(next);
    logActivity("Invoice edited", "Purchases", { detailText: `${inv.number} → ${data.number}` });
    setEditInvoice(false);
  };
  const savePhone = (phoneData) => {
    const old = phones.find((x) => x.id === editPhone?.id);
    if (!old) return;
    updatePhones(phones.map((x) => x.id === old.id ? { ...x, ...phoneData } : x));
    logActivity("Phone edited", "Purchases", { detailText: `${old.brand} ${old.model} (IMEI ${old.imei})` });
    setEditPhone(null);
  };

  const addPhone = (phoneData) => {
    const phone = {
      id: uid(), purchaseType: "debit", invoiceId: inv.id, purchaseCurrency: inv.currency, purchaseExchangeRate: Number(inv.exchangeRate) || Number(settings.exchangeRate) || 1,
      status: "in_stock", createdAt: nowISO(), ...phoneData,
    };
    updatePhones([phone, ...phones]);
    logActivity("Phone added", "Purchases", { detailText: `${phone.brand} ${phone.model} (IMEI ${phone.imei}) → ${inv.number}` });
    setShowAddPhone(false);
  };
  const removePhone = (phoneId) => {
    const p = phones.find((x) => x.id === phoneId);
    if (!p) return;
    if (p.status === "sold") { alert("This phone has already been sold and cannot be removed."); return; }
    if (!confirm("Remove this phone from the invoice? You can use Undo immediately if this was a mistake.")) return;
    updatePhones(phones.filter((x) => x.id !== phoneId));
    addToRecycleBin({ type: "phone", label: `${p.brand} ${p.model} — IMEI ${p.imei}`, data: { phone: p } });
    logActivity("Purchase deleted", "Purchases", { detailText: `${p.brand} ${p.model} (IMEI ${p.imei})` });
    setPhoneDeletedForUndo(true);
  };
  const addPayment = (data) => {
    const payment = { id: uid(), invoiceId: inv.id, ...data, createdAt: nowISO() };
    updatePayments([payment, ...payments]);
    logActivity("Payment added", "Supplier Payments", { detailText: `${fmtMoney(data.amount, data.currency)} → ${inv.number}` });
    setShowPay(false);
  };
  const savePayment = (data) => {
    const old = payments.find((x) => x.id === editPayment?.id);
    if (!old) return;
    updatePayments(payments.map((x) => x.id === old.id ? { ...x, ...data } : x));
    logActivity("Payment edited", "Supplier Payments", { detailText: `${fmtMoney(old.amount, old.currency)} → ${fmtMoney(data.amount, data.currency)} on ${inv.number}` });
    setEditPayment(null);
  };
  const removePayment = (paymentId) => {
    if (!confirm("Delete this payment record?")) return;
    const p = payments.find((x) => x.id === paymentId);
    updatePayments(payments.filter((x) => x.id !== paymentId));
    if (p) addToRecycleBin({ type: "payment", label: `${fmtMoney(p.amount, p.currency)} — ${inv.number}`, data: { payment: p } });
    logActivity("Payment deleted", "Supplier Payments", { detailText: p ? `${fmtMoney(p.amount, p.currency)} from ${inv.number}` : inv.number });
  };
  const deleteInvoice = () => {
    if (invPhones.some((p) => p.status === "sold")) { alert("This invoice has phones that were already sold and can't be deleted. Remove or reassign those phones first."); return; }
    if (!confirm(`Delete invoice ${inv.number} (${inv.supplier})? This also removes its phones and payment history. You can use Undo immediately after deletion.`)) return;
    addToRecycleBin({ type: "invoice", label: `${inv.number} — ${inv.supplier}`, data: { invoice: inv, phones: invPhones, payments: invPayments } });
    updateInvoices(invoices.filter((x) => x.id !== inv.id));
    updatePhones(phones.filter((p) => p.invoiceId !== inv.id));
    updatePayments(payments.filter((p) => p.invoiceId !== inv.id));
    logActivity("Invoice deleted", "Purchases", { detailText: `${inv.number} — ${inv.supplier}` });
    onClose();
  };

  return (
    <Modal title={`Invoice ${inv.number} — ${inv.supplier}`} onClose={onClose} width={760}>
      <div style={{ display: "flex", gap: 14, flexWrap: "wrap", marginBottom: 16, alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", gap: 14, flexWrap: "wrap", alignItems: "center" }}>
          <MiniStat label="Invoice Total" value={`${fmtMoney(t.totalUSD, "USD")} / ${fmtMoney(t.totalIQD, "IQD")}`} />
          <MiniStat label="Paid" value={`${fmtMoney(t.paidUSD, "USD")} / ${fmtMoney(t.paidIQD, "IQD")}`} tone="success" />
          <MiniStat label="Remaining" value={`${fmtMoney(t.remainingUSD, "USD")} / ${fmtMoney(t.remainingIQD, "IQD")}`} tone="danger" />
          <MiniStat label="Invoice Exchange Rate" value={`1 USD = ${(Number(inv.exchangeRate) || Number(settings.exchangeRate) || 1).toLocaleString()} IQD`} />
          {inv.supplierPhone && <MiniStat label="Supplier Phone" value={inv.supplierPhone} />}
          {inv.supplierLocation && <MiniStat label="Supplier Location" value={inv.supplierLocation} />}
          <MiniStat label="Payment Deadline" value={inv.dueDate ? fmtDate(inv.dueDate) : "Not set"} tone={inv.dueDate && t.remaining > 0 && inv.dueDate < todayDate() ? "danger" : "subtle"} />
          <div style={{ display: "flex", alignItems: "center" }}><StatusBadge status={t.status} /></div>
        </div>
        <div style={{ display: "flex", gap: 7 }}>
          <Button size="sm" variant="subtle" icon={Pencil} onClick={() => setEditInvoice(true)}>Edit Invoice</Button>
          <Button size="sm" variant="danger" icon={Trash2} onClick={deleteInvoice}>Delete Invoice</Button>
          {undoCount > 0 && <Button size="sm" variant="subtle" icon={History} onClick={async () => { await undoLastChange(); setPhoneDeletedForUndo(false); }}>Undo Last Change</Button>}
        </div>
      </div>

      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
        <h4 style={{ margin: 0, fontSize: 13.5 }}>Phones on this invoice ({invPhones.length})</h4>
        <div style={{ display: "flex", gap: 7, alignItems: "center" }}>
          {phoneDeletedForUndo && undoCount > 0 && <Button size="sm" variant="subtle" icon={History} onClick={async () => { await undoLastChange(); setPhoneDeletedForUndo(false); }}>Undo Deleted Phone</Button>}
          <Button size="sm" icon={Plus} variant="subtle" onClick={() => setShowAddPhone(true)}>Add Phone</Button>
        </div>
      </div>
      {invPhones.length === 0 ? <EmptyState icon={Smartphone} text="No phones added to this invoice yet." /> : (
        <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
          <thead><tr>{["IMEI", "Brand / Model", "Storage / RAM", "Color", "SIM Type", "Price", "Status", ""].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
          <tbody>
            {invPhones.map((p) => (
              <tr key={p.id}>
                <td style={{ ...tdStyle, fontFamily: MONO }}>{p.imei}</td>
                <td style={tdStyle}>{p.brand} {p.model}</td>
                <td style={tdStyle}>{phoneSpecLabel(p)}</td>
                <td style={tdStyle}>{p.color || "-"}</td>
                <td style={tdStyle}>{p.simType || "-"}</td>
                <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(p.purchasePrice, p.purchaseCurrency || inv.currency)}</td>
                <td style={tdStyle}>{p.status === "sold" ? <Badge tone="sub">Sold</Badge> : p.status === "returned" ? <Badge tone="danger">Returned</Badge> : <Badge tone="accent">In Stock</Badge>}</td>
                <td style={tdStyle}><div style={{display:"flex",gap:4}}>
                  <button title="Edit phone" onClick={() => setEditPhone(p)} style={iconBtn}><Pencil size={14} color={C.sub} /></button>
                  <button title="Delete phone" onClick={() => removePhone(p.id)} style={iconBtn}><Trash2 size={14} color={C.danger} /></button>
                </div></td>
              </tr>
            ))}
          </tbody>
        </table></div>
      )}

      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "20px 0 8px" }}>
        <h4 style={{ margin: 0, fontSize: 13.5 }}>Payment history</h4>
        <Button size="sm" icon={Plus} variant="subtle" onClick={() => setShowPay(true)}>Add Payment</Button>
      </div>
      {invPayments.length === 0 ? <EmptyState icon={Wallet} text="No payments recorded yet." /> : (
        <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
          <thead><tr>{["Date", "Amount", "Method", "Notes", ""].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
          <tbody>
            {invPayments.map((p) => (
              <tr key={p.id}>
                <td style={tdStyle}>{fmtDate(p.date)}</td>
                <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700, color: C.success }}>{fmtMoney(p.amount, p.currency)}</td>
                <td style={tdStyle}>{p.method}</td>
                <td style={tdStyle}>{p.notes || "-"}</td>
                <td style={tdStyle}><div style={{display:"flex",gap:4}}>
                  <button title="Edit payment" onClick={() => setEditPayment(p)} style={iconBtn}><Pencil size={14} color={C.sub} /></button>
                  <button title="Delete payment" onClick={() => removePayment(p.id)} style={iconBtn}><Trash2 size={14} color={C.danger} /></button>
                </div></td>
              </tr>
            ))}
          </tbody>
        </table></div>
      )}

      {showAddPhone && <AddPhoneModal settings={settings} currency={inv.currency} exchangeRate={inv.exchangeRate || settings.exchangeRate} onClose={() => setShowAddPhone(false)} onAdd={addPhone} />}
      {editPhone && <AddPhoneModal settings={settings} initial={editPhone} currency={inv.currency} exchangeRate={inv.exchangeRate || settings.exchangeRate} editing onClose={() => setEditPhone(null)} onAdd={savePhone} />}
      {showPay && <AddPaymentModal settings={settings} currency={inv.currency} exchangeRate={inv.exchangeRate || settings.exchangeRate} remaining={t.remaining} remainingUSD={t.remainingUSD} remainingIQD={t.remainingIQD} onClose={() => setShowPay(false)} onAdd={addPayment} />}
      {editPayment && <AddPaymentModal settings={settings} currency={inv.currency} exchangeRate={inv.exchangeRate || settings.exchangeRate} editing initial={editPayment} onClose={() => setEditPayment(null)} onAdd={savePayment} />}
      {editInvoice && <NewInvoiceModal settings={settings} invoices={invoices} editingInvoice={inv} onClose={() => setEditInvoice(false)} onCreate={saveInvoice} />}
    </Modal>
  );
}

function MiniStat({ label, value, tone }) {
  const color = tone === "success" ? C.success : tone === "danger" ? C.danger : C.ink;
  return (
    <div>
      <div style={{ fontSize: 11.5, color: C.sub, fontWeight: 600, textTransform: "uppercase" }}>{label}</div>
      <div style={{ fontFamily: MONO, fontSize: 18, fontWeight: 700, color }}>{value}</div>
    </div>
  );
}

const iconBtn = { background: "none", border: "none", cursor: "pointer", padding: 4, display: "inline-flex" };

function AddPhoneModal({ settings, currency, exchangeRate, lockCurrency, onClose, onAdd, cashMode, initial, editing }) {
  const [imei, setImei] = useState(initial?.imei || "");
  const [brand, setBrand] = useState(initial?.brand || settings.brands[0] || "");
  const modelsForBrand = (settings.modelsByBrand && settings.modelsByBrand[brand]) || [];
  const [model, setModel] = useState(initial?.model || modelsForBrand[0] || "");
  const [storage, setStorage] = useState(initial?.storage || "");
  const [ram, setRam] = useState(initial?.ram || "");
  const [color, setColor] = useState(initial?.color || "");
  const [simType, setSimType] = useState(initial?.simType || "");
  const [purchasedFrom, setPurchasedFrom] = useState(initial?.purchasedFrom || "");
  const [purchasedFromPhone, setPurchasedFromPhone] = useState(initial?.purchasedFromPhone || "");
  const [sellerLocation, setSellerLocation] = useState(initial?.sellerLocation || "");
  const [price, setPrice] = useState(initial?.purchasePrice ?? "");
  const [cur, setCur] = useState(initial?.purchaseCurrency || currency || "USD");
  const [rate, setRate] = useState(initial?.purchaseExchangeRate || exchangeRate || settings.exchangeRate || 1460);
  const [date, setDate] = useState(initial?.date || todayDate());
  const [notes, setNotes] = useState(initial?.notes || "");

  const submit = () => {
    if (!imei || !brand || !model || !price) return;
    onAdd({ imei: imei.trim(), brand, model, storage: normalizeCapacity(storage), ram: normalizeCapacity(ram), color, simType, purchasedFrom: purchasedFrom.trim(), purchasedFromPhone: purchasedFromPhone.trim(), sellerLocation: sellerLocation.trim(), purchasePrice: Number(price), purchaseCurrency: cur, purchaseExchangeRate: Number(rate) || Number(settings.exchangeRate) || 1, date, notes });
  };

  return (
    <Modal title={`${editing ? "Edit" : "Add"} Phone`} onClose={onClose} confirmClose>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <div style={{ gridColumn: "1 / -1" }}><Field label="IMEI"><Input value={imei} onChange={(e) => setImei(e.target.value)} style={{ fontFamily: MONO }} placeholder="15-digit IMEI" /></Field></div>
        <Field label="Brand">
          <Select value={brand} onChange={(e) => {
            const nextBrand = e.target.value;
            setBrand(nextBrand);
            const nextModels = (settings.modelsByBrand && settings.modelsByBrand[nextBrand]) || [];
            setModel(nextModels[0] || "");
          }}>
            {settings.brands.map((b) => <option key={b} value={b}>{b}</option>)}
          </Select>
        </Field>
        <Field label="Model">
          <Select value={model} onChange={(e) => setModel(e.target.value)} disabled={modelsForBrand.length === 0}>
            {modelsForBrand.length === 0 && <option value="">No models for this brand yet</option>}
            {modelsForBrand.map((m) => <option key={m} value={m}>{m}</option>)}
          </Select>
        </Field>
        <Field label="Storage (optional)"><Input value={storage} onChange={(e) => setStorage(e.target.value)} placeholder="e.g. 128GB" /></Field>
        <Field label="RAM (optional)"><Input value={ram} onChange={(e) => setRam(e.target.value)} placeholder="e.g. 6GB" /></Field>
        <Field label="Color (optional)"><Input value={color} onChange={(e) => setColor(e.target.value)} placeholder="e.g. Midnight" /></Field>
        <Field label="SIM Type (optional)">
          <Select value={simType} onChange={(e) => setSimType(e.target.value)}>
            <option value="">Not specified</option>
            {SIM_TYPES.map((s) => <option key={s} value={s}>{s}</option>)}
          </Select>
        </Field>
        {cashMode && <Field label="Purchased From (optional)"><Input value={purchasedFrom} onChange={(e) => setPurchasedFrom(e.target.value)} placeholder="e.g. Ali Mobile Shop, Sulaymaniyah market" /></Field>}
        {cashMode && <Field label="Seller Phone Number (optional)"><Input value={purchasedFromPhone} onChange={(e) => setPurchasedFromPhone(e.target.value)} placeholder="e.g. 0770 123 4567" /></Field>}
        {cashMode && <Field label="Seller Location / Residence (optional)"><Input value={sellerLocation} onChange={(e) => setSellerLocation(e.target.value)} placeholder="e.g. Erbil, Shorsh area" /></Field>}
        <Field label="Purchase Price"><Input type="number" value={price} onChange={(e) => setPrice(e.target.value)} /></Field>
        <Field label="Currency">
          <Select value={cur} onChange={(e) => setCur(e.target.value)}>
            <option value="USD">USD</option><option value="IQD">IQD</option>
          </Select>
        </Field>
        <Field label="Exchange Rate (1 USD = IQD)">
          <Input type="number" min="1" value={rate} onChange={(e) => setRate(e.target.value)} />
        </Field>
        <Field label="Date"><Input type="date" value={date} onChange={(e) => setDate(e.target.value)} /></Field>
        <div style={{ gridColumn: "1 / -1" }}><Field label="Notes (optional)"><TextArea value={notes} onChange={(e) => setNotes(e.target.value)} /></Field></div>
      </div>
      <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 18 }}>
        <Button variant="ghost" onClick={onClose}>Discard</Button>
        <Button disabled={!imei || !brand || !model || !price} onClick={submit}>{editing ? "Save Changes" : "Save"}</Button>
      </div>
    </Modal>
  );
}

function AddPaymentModal({ settings, currency, exchangeRate, remaining, remainingUSD, remainingIQD, onClose, onAdd, editing, initial }) {
  const [amount, setAmount] = useState(editing ? initial?.amount ?? "" : (remaining || ""));
  const [cur, setCur] = useState(editing ? (initial?.currency || "USD") : (currency || "USD"));
  const [rate, setRate] = useState(editing ? (initial?.exchangeRate || settings.exchangeRate || 1460) : (exchangeRate || settings.exchangeRate || 1460));
  const [date, setDate] = useState(editing ? (initial?.date || todayDate()) : todayDate());
  const [method, setMethod] = useState(editing ? (initial?.method || settings.paymentMethods[0] || "Cash") : (settings.paymentMethods[0] || "Cash"));
  const [notes, setNotes] = useState(editing ? (initial?.notes || "") : "");
  const submit = () => { if (!amount) return; onAdd({ amount: Number(amount), currency: cur, exchangeRate: Number(rate) || Number(settings.exchangeRate) || 1, date, method, notes }); };
  const remainingInPaymentCurrency = cur === "USD" ? remainingUSD : remainingIQD;
  return (
    <Modal title={editing ? "Edit Supplier Payment" : "Record Supplier Payment"} onClose={onClose} confirmClose>
      <div style={{ fontSize: 12, color: C.sub, marginBottom: 4 }}>
        {editing
          ? "Update this payment's details. Totals and Currency P&L recalculate automatically."
          : `Owed: ${fmtMoney(remainingUSD, "USD")} · ${fmtMoney(remainingIQD, "IQD")}. Pay in whichever currency the cash was actually handed over in.`}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <Field label={`Amount${!editing && remainingInPaymentCurrency != null ? ` · remaining ${fmtMoney(remainingInPaymentCurrency, cur)}` : ""}`}>
          <Input type="number" value={amount} onChange={(e) => setAmount(e.target.value)} />
        </Field>
        <Field label="Currency">
          <Select value={cur} onChange={(e) => setCur(e.target.value)}>
            <option value="USD">USD</option><option value="IQD">IQD</option>
          </Select>
        </Field>
        <Field label="Exchange Rate (1 USD = IQD)"><Input type="number" min="1" value={rate} onChange={(e) => setRate(e.target.value)} /></Field>
        <Field label="Date"><Input type="date" value={date} onChange={(e) => setDate(e.target.value)} /></Field>
        <Field label="Payment Method"><Select value={method} onChange={(e) => setMethod(e.target.value)}>{settings.paymentMethods.map((m) => <option key={m} value={m}>{m}</option>)}</Select></Field>
        <div style={{ gridColumn: "1 / -1" }}><Field label="Notes (optional)"><TextArea value={notes} onChange={(e) => setNotes(e.target.value)} /></Field></div>
      </div>
      <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 18 }}>
        <Button variant="ghost" onClick={onClose}>Discard</Button>
        <Button disabled={!amount} onClick={submit}>{editing ? "Save Changes" : "Save Payment"}</Button>
      </div>
    </Modal>
  );
}

function roundMoney(n, currency) {
  const v = Number(n) || 0;
  return currency === "USD" ? Math.round(v * 100) / 100 : Math.round(v);
}

function SupplierBulkPaymentModal({ ctx, onClose, defaultSupplier }) {
  const { invoices, invoiceTotals, payments, updatePayments, settings, logActivity } = ctx;

  const suppliersWithDebt = useMemo(() => {
    const set = new Set();
    invoices.forEach((inv) => { if (invoiceTotals[inv.id].remaining > 0) set.add(inv.supplier); });
    return Array.from(set);
  }, [invoices, invoiceTotals]);

  const [supplier, setSupplier] = useState(
    defaultSupplier && suppliersWithDebt.includes(defaultSupplier) ? defaultSupplier : (suppliersWithDebt[0] || "")
  );

  const currenciesForSupplier = useMemo(() => {
    const set = new Set();
    invoices.forEach((inv) => { if (inv.supplier === supplier && invoiceTotals[inv.id].remaining > 0) set.add(inv.currency); });
    return Array.from(set);
  }, [invoices, invoiceTotals, supplier]);

  const [currency, setCurrency] = useState(currenciesForSupplier[0] || "USD");
  useEffect(() => {
    if (!currenciesForSupplier.includes(currency)) setCurrency(currenciesForSupplier[0] || "USD");
  }, [supplier]); // eslint-disable-line react-hooks/exhaustive-deps

  const outstanding = useMemo(() => invoices
    .filter((inv) => inv.supplier === supplier && inv.currency === currency && invoiceTotals[inv.id].remaining > 0)
    .map((inv) => ({ inv, t: invoiceTotals[inv.id] }))
    .sort((a, b) => new Date(a.inv.date) - new Date(b.inv.date)),
  [invoices, invoiceTotals, supplier, currency]);

  const [totalAmount, setTotalAmount] = useState("");
  const [allocations, setAllocations] = useState({});
  const [date, setDate] = useState(todayDate());
  const [rate, setRate] = useState(settings.exchangeRate || 1460);
  const [method, setMethod] = useState(settings.paymentMethods[0] || "Cash");
  const [notes, setNotes] = useState("");

  useEffect(() => { setAllocations({}); }, [supplier, currency]);

  const setAlloc = (id, val) => setAllocations((a) => ({ ...a, [id]: val }));

  const autoAllocate = () => {
    let left = Number(totalAmount) || 0;
    const next = {};
    for (const { inv, t } of outstanding) {
      if (left <= 0) { next[inv.id] = ""; continue; }
      const take = Math.min(left, t.remaining);
      next[inv.id] = take > 0 ? String(roundMoney(take, currency)) : "";
      left -= take;
    }
    setAllocations(next);
  };

  const allocatedSum = outstanding.reduce((s, { inv }) => s + (Number(allocations[inv.id]) || 0), 0);
  const totalNum = Number(totalAmount) || 0;
  const overAllocatedInvoice = outstanding.find(({ inv, t }) => (Number(allocations[inv.id]) || 0) > t.remaining + 0.005);
  const mismatch = totalNum > 0 && Math.abs(allocatedSum - totalNum) > 0.01;
  const canSubmit = totalNum > 0 && !overAllocatedInvoice && !mismatch && allocatedSum > 0;

  const submit = () => {
    if (!canSubmit) return;
    const batchId = uid();
    const newPayments = outstanding
      .map(({ inv }) => ({ inv, amount: Number(allocations[inv.id]) || 0 }))
      .filter((x) => x.amount > 0)
      .map(({ inv, amount }) => ({
        id: uid(), invoiceId: inv.id, amount, currency, exchangeRate: Number(rate) || Number(settings.exchangeRate) || 1, date, method,
        notes: notes ? `${notes} (part of bulk payment)` : "Bulk payment split across invoices",
        batchId, createdAt: nowISO(),
      }));
    updatePayments([...newPayments, ...payments]);
    logActivity("Bulk payment added", "Supplier Payments", {
      detailText: `${fmtMoney(totalNum, currency)} → ${supplier} split across ${newPayments.length} invoice${newPayments.length === 1 ? "" : "s"}`,
    });
    onClose();
  };

  if (suppliersWithDebt.length === 0) {
    return (
      <Modal title="Record Supplier Payment" onClose={onClose} confirmClose>
        <EmptyState icon={CheckCircle2} text="No suppliers have an outstanding balance right now." />
      </Modal>
    );
  }

  return (
    <Modal title="Record Supplier Payment" onClose={onClose} width={760} confirmClose>
      <div style={{ fontSize: 12.5, color: C.sub, marginBottom: 14 }}>
        Pay one lump sum toward a supplier and split it across their open invoices — oldest first, or however you choose.
      </div>
      <div style={{ display: "grid", gridTemplateColumns: currenciesForSupplier.length > 1 ? "1fr 1fr" : "1fr", gap: 12, marginBottom: 12 }}>
        <Field label="Supplier">
          <Select value={supplier} onChange={(e) => setSupplier(e.target.value)}>
            {suppliersWithDebt.map((s) => <option key={s} value={s}>{s}</option>)}
          </Select>
        </Field>
        {currenciesForSupplier.length > 1 && (
          <Field label="Currency">
            <Select value={currency} onChange={(e) => setCurrency(e.target.value)}>
              {currenciesForSupplier.map((c) => <option key={c} value={c}>{c}</option>)}
            </Select>
          </Field>
        )}
      </div>

      {outstanding.length === 0 ? (
        <EmptyState icon={CheckCircle2} text={`${supplier} has no outstanding ${currency} invoices.`} />
      ) : (
        <>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: 12, marginBottom: 14 }}>
            <Field label={`Total amount to pay (${currency})`}>
              <Input type="number" value={totalAmount} onChange={(e) => setTotalAmount(e.target.value)} placeholder="e.g. 4000" />
            </Field>
            <Field label="Exchange Rate (1 USD = IQD)"><Input type="number" min="1" value={rate} onChange={(e) => setRate(e.target.value)} /></Field>
            <Field label="Date"><Input type="date" value={date} onChange={(e) => setDate(e.target.value)} /></Field>
            <Field label="Payment Method">
              <Select value={method} onChange={(e) => setMethod(e.target.value)}>{settings.paymentMethods.map((m) => <option key={m} value={m}>{m}</option>)}</Select>
            </Field>
          </div>
          <div style={{ fontSize: 12, color: C.sub, marginTop: -8, marginBottom: 14 }}>
            Record the exchange rate you actually paid at today — this is compared against each invoice's purchase-time rate in Currency P&amp;L.
          </div>

          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
            <h4 style={{ margin: 0, fontSize: 13.5 }}>Split across invoices ({outstanding.length})</h4>
            <Button size="sm" variant="subtle" onClick={autoAllocate} disabled={!totalNum}>Auto-fill oldest first</Button>
          </div>
          <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
            <thead><tr>{["Invoice #", "Date", "Total", "Remaining", `Apply (${currency})`].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
            <tbody>
              {outstanding.map(({ inv, t }) => {
                const val = allocations[inv.id] || "";
                const isOver = Number(val) > t.remaining + 0.005;
                return (
                  <tr key={inv.id}>
                    <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700 }}>{inv.number}</td>
                    <td style={tdStyle}>{fmtDate(inv.date)}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(t.total, currency)}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(t.remaining, currency)}</td>
                    <td style={tdStyle}>
                      <Input type="number" value={val} onChange={(e) => setAlloc(inv.id, e.target.value)}
                        style={{ borderColor: isOver ? C.danger : C.border, maxWidth: 140 }} />
                      {isOver && <div style={{ fontSize: 11, color: C.danger, marginTop: 3 }}>Exceeds remaining</div>}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table></div>

          <div style={{
            display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 12,
            padding: "10px 12px", borderRadius: 10, background: mismatch ? C.dangerSoft : C.successSoft,
          }}>
            <span style={{ fontSize: 12.5, fontWeight: 600, color: mismatch ? C.danger : C.success }}>
              Allocated {fmtMoney(allocatedSum, currency)} of {fmtMoney(totalNum, currency)} entered
            </span>
            {mismatch && <span style={{ fontSize: 11.5, color: C.danger }}>Allocations must add up to the total amount</span>}
          </div>

          <div style={{ marginTop: 12 }}>
            <Field label="Notes (optional)"><TextArea value={notes} onChange={(e) => setNotes(e.target.value)} /></Field>
          </div>
        </>
      )}

      <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 18 }}>
        <Button variant="ghost" onClick={onClose}>Discard</Button>
        <Button disabled={!canSubmit} onClick={submit}>Save Payment</Button>
      </div>
    </Modal>
  );
}

function CashPurchases({ ctx }) {
  const { phones, updatePhones, settings, logActivity, addToRecycleBin } = ctx;
  const [showAdd, setShowAdd] = useState(false);
  const [editPhone, setEditPhone] = useState(null);
  const [q, setQ] = useState("");
  const cashPhones = phones.filter((p) => p.purchaseType === "cash").filter((p) =>
    !q || p.imei.includes(q) || p.brand.toLowerCase().includes(q.toLowerCase()) || p.model.toLowerCase().includes(q.toLowerCase()) || (p.purchasedFrom || "").toLowerCase().includes(q.toLowerCase()) || (p.sellerLocation || "").toLowerCase().includes(q.toLowerCase()) || (p.simType || "").toLowerCase().includes(q.toLowerCase())
  ).sort((a, b) => new Date(b.date) - new Date(a.date));

  const addPhone = (data) => {
    const phone = { id: uid(), purchaseType: "cash", invoiceId: null, status: "in_stock", createdAt: nowISO(), ...data };
    updatePhones([phone, ...phones]);
    logActivity("Phone added", "Cash Purchase", { detailText: `${phone.brand} ${phone.model} (IMEI ${phone.imei})` });
    setShowAdd(false);
  };
  const savePhone = (data) => {
    const old = phones.find(x => x.id === editPhone?.id);
    if (!old) return;
    updatePhones(phones.map(x => x.id === old.id ? { ...x, ...data, purchaseType: "cash", invoiceId: null } : x));
    logActivity("Purchase edited", "Cash Purchase", { detailText: `${old.brand} ${old.model} (IMEI ${old.imei})` });
    setEditPhone(null);
  };
  const removePhone = (id) => {
    const p = phones.find((x) => x.id === id);
    if (!p) return;
    if (p.status === "sold") { alert("This phone has already been sold and cannot be removed."); return; }
    if (!confirm("Remove this cash purchase? You can use Undo immediately if this was a mistake.")) return;
    updatePhones(phones.filter((x) => x.id !== id));
    addToRecycleBin({ type: "phone", label: `${p.brand} ${p.model} — IMEI ${p.imei}`, data: { phone: p } });
    logActivity("Purchase deleted", "Cash Purchase", { detailText: `${p.brand} ${p.model} (IMEI ${p.imei})` });
  };

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 14, gap: 10, flexWrap: "wrap" }}>
        <div style={{ position: "relative", flex: "1 1 240px", maxWidth: 320 }}>
          <Search size={14} style={{ position: "absolute", left: 10, top: 10, color: C.faint }} />
          <Input placeholder="Search IMEI, brand, model, or source" value={q} onChange={(e) => setQ(e.target.value)} style={{ paddingLeft: 30 }} />
        </div>
        <Button icon={Plus} onClick={() => setShowAdd(true)}>Add Cash Purchase</Button>
      </div>
      {cashPhones.length === 0 ? <Card><EmptyState icon={Banknote} text="No cash purchases recorded yet." /></Card> : (
        <Card>
          <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
            <thead><tr>{["IMEI", "Brand / Model", "Storage / RAM", "Color", "SIM Type", "Purchased From", "Phone", "Price", "Date", "Status", ""].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
            <tbody>
              {cashPhones.map((p) => (
                <tr key={p.id}>
                  <td style={{ ...tdStyle, fontFamily: MONO }}>{p.imei}</td>
                  <td style={tdStyle}>{p.brand} {p.model}</td>
                  <td style={tdStyle}>{phoneSpecLabel(p)}</td>
                  <td style={tdStyle}>{p.color || "-"}</td>
                  <td style={tdStyle}>{p.simType || "-"}</td>
                  <td style={tdStyle}>{p.purchasedFrom || "-"}{p.sellerLocation && <div style={{ fontSize: 11, color: C.faint }}>{p.sellerLocation}</div>}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO }}>{p.purchasedFromPhone || "-"}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(p.purchasePrice, p.purchaseCurrency)}</td>
                  <td style={tdStyle}>{fmtDate(p.date)}</td>
                  <td style={tdStyle}>{p.status === "sold" ? <Badge tone="sub">Sold</Badge> : p.status === "returned" ? <Badge tone="danger">Returned</Badge> : <Badge tone="accent">In Stock</Badge>}</td>
                  <td style={tdStyle}><div style={{display:"flex",gap:4}}>
                    <button title="Edit phone" onClick={() => setEditPhone(p)} style={iconBtn}><Pencil size={14} color={C.sub} /></button>
                    <button title="Delete phone" onClick={() => removePhone(p.id)} style={iconBtn}><Trash2 size={14} color={C.danger} /></button>
                  </div></td>
                </tr>
              ))}
            </tbody>
          </table></div>
        </Card>
      )}
      {showAdd && <AddPhoneModal settings={settings} currency="USD" exchangeRate={settings.exchangeRate} onClose={() => setShowAdd(false)} onAdd={addPhone} cashMode />}
      {editPhone && <AddPhoneModal settings={settings} initial={editPhone} currency={editPhone.purchaseCurrency || "USD"} exchangeRate={editPhone.purchaseExchangeRate || settings.exchangeRate} onClose={() => setEditPhone(null)} onAdd={savePhone} editing cashMode />}
    </div>
  );
}

/* ---------------------------------- SALES & STOCK ---------------------------------- */

// Consistent color per brand, cycling through a small distinct palette so any
// number of brands (default 5, or however many the user configures) still reads clearly.
const BRAND_PALETTE = ["#0E8E8E", "#5B6FE6", "#B4650A", "#B3261E", "#7A4FBF", "#177B45", "#A6790A", "#3E7CB1"];
function brandColor(brand, brands) {
  const idx = Math.max(0, (brands || []).indexOf(brand));
  return BRAND_PALETTE[idx % BRAND_PALETTE.length];
}

function BrandBreakdown({ phones, brands, activeBrand, onSelectBrand }) {
  const total = phones.length;
  const counts = brands.map((b) => ({ brand: b, count: phones.filter((p) => (p.brand || "") === b).length, color: brandColor(b, brands) }))
    .filter((x) => x.count > 0 || x.brand === activeBrand);
  const otherCount = total - counts.reduce((s, x) => s + x.count, 0);

  // Build a simple SVG donut from the counts (no chart library needed).
  const size = 84, stroke = 14, r = (size - stroke) / 2, cx = size / 2, cy = size / 2, circ = 2 * Math.PI * r;
  let offset = 0;
  const segments = counts.filter((x) => x.count > 0).map((x) => {
    const frac = total ? x.count / total : 0;
    const seg = { ...x, dash: `${circ * frac} ${circ * (1 - frac)}`, dashoffset: -offset * circ };
    offset += frac;
    return seg;
  });

  return (
    <Card style={{ padding: 16, marginBottom: 16 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <h3 style={{ margin: 0, fontSize: 14.5, fontWeight: 700 }}>By Brand</h3>
        <span style={{ fontSize: 11.5, color: C.faint }}>Tap a brand to filter</span>
      </div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 18, alignItems: "center" }}>
        <div style={{ position: "relative", width: size, height: size, flexShrink: 0 }}>
          <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: "rotate(-90deg)" }}>
            <circle cx={cx} cy={cy} r={r} fill="none" stroke={C.border} strokeWidth={stroke} />
            {segments.map((s) => (
              <circle key={s.brand} cx={cx} cy={cy} r={r} fill="none" stroke={s.color} strokeWidth={stroke}
                strokeDasharray={s.dash} strokeDashoffset={s.dashoffset} strokeLinecap="butt"
                style={{ cursor: "pointer", opacity: activeBrand && activeBrand !== s.brand ? 0.35 : 1, transition: "opacity 0.15s" }}
                onClick={() => onSelectBrand(activeBrand === s.brand ? null : s.brand)} />
            ))}
          </svg>
          <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
            <div style={{ fontFamily: MONO, fontSize: 18, fontWeight: 800, color: C.ink, lineHeight: 1 }}>{total}</div>
            <div style={{ fontSize: 9, color: C.sub, textTransform: "uppercase", letterSpacing: 0.3 }}>Total</div>
          </div>
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8, flex: 1, minWidth: 200 }}>
          {counts.map((x) => (
            <button key={x.brand} onClick={() => onSelectBrand(activeBrand === x.brand ? null : x.brand)}
              style={{
                display: "flex", alignItems: "center", gap: 7, padding: "6px 12px", borderRadius: 999,
                border: `1px solid ${activeBrand === x.brand ? x.color : C.border}`,
                background: activeBrand === x.brand ? x.color + "1A" : C.surface, cursor: "pointer",
                opacity: activeBrand && activeBrand !== x.brand ? 0.5 : 1,
              }}>
              <span style={{ width: 9, height: 9, borderRadius: 5, background: x.color, flexShrink: 0 }} />
              <span style={{ fontSize: 12.5, fontWeight: 600, color: C.ink }}>{x.brand}</span>
              <span style={{ fontFamily: MONO, fontSize: 12, fontWeight: 700, color: x.color }}>{x.count}</span>
            </button>
          ))}
          {otherCount > 0 && (
            <div style={{ display: "flex", alignItems: "center", gap: 7, padding: "6px 12px", borderRadius: 999, border: `1px solid ${C.border}` }}>
              <span style={{ width: 9, height: 9, borderRadius: 5, background: C.faint, flexShrink: 0 }} />
              <span style={{ fontSize: 12.5, fontWeight: 600, color: C.sub }}>Other</span>
              <span style={{ fontFamily: MONO, fontSize: 12, fontWeight: 700, color: C.sub }}>{otherCount}</span>
            </div>
          )}
        </div>
      </div>
    </Card>
  );
}

function SalesStock({ ctx, mode = "sales" }) {
  const { phones, updatePhones, settings, logActivity, customerPayments, updateCustomerPayments, addToRecycleBin } = ctx;
  const [filter, setFilter] = useState(mode === "stock" ? "in_stock" : "sold");
  const [saleTab, setSaleTab] = useState("cash");
  const [q, setQ] = useState("");
  const [activeBrand, setActiveBrand] = useState(null);
  const [sellPhone, setSellPhone] = useState(null);
  const [showNewSale, setShowNewSale] = useState(false);
  const [editSale, setEditSale] = useState(null);
  const [editPhone, setEditPhone] = useState(null);

  const list = phones.filter((p) => filter === "all" || p.status === filter)
    .filter((p) => !activeBrand || p.brand === activeBrand)
    .filter((p) => !q || String(p.imei || "").includes(q) || String(p.brand || "").toLowerCase().includes(q.toLowerCase()) ||
      String(p.model || "").toLowerCase().includes(q.toLowerCase()) || String(p.sale?.customer || "").toLowerCase().includes(q.toLowerCase()) || String(p.simType || "").toLowerCase().includes(q.toLowerCase()))
    .sort((a, b) => new Date(b.createdAt || b.date) - new Date(a.createdAt || a.date));

  const sold = phones.filter(p => p.status === "sold");
  const cashSales = sold.filter(p => (p.sale?.saleType || "cash") === "cash");
  const installmentSales = sold.filter(p => p.sale?.saleType === "installment");
  const debitCount = phones.filter((p) => p.purchaseType === "debit");
  const cashCount = phones.filter((p) => p.purchaseType === "cash");

  const paymentsForPhone = (phoneId) => customerPayments.filter(x => x.phoneId === phoneId);
  const paidForPhone = (p) => {
    if (!p.sale) return 0;
    if (p.sale.saleType === "cash") return Number(p.sale.price) || 0;
    return paymentsForPhone(p.id).reduce((s, x) => s + (Number(x.amount) || 0), 0);
  };

  const saveStockPhone = (data) => {
    const old = phones.find(x => x.id === editPhone?.id);
    if (!old) return;
    updatePhones(phones.map(x => x.id === old.id ? { ...x, ...data } : x));
    logActivity("Phone edited", "Stock", { detailText: `${old.brand} ${old.model} (IMEI ${old.imei})` });
    setEditPhone(null);
  };

  const recordSale = (phoneId, saleData) => {
    const p = phones.find((x) => x.id === phoneId);
    const next = phones.map((x) => x.id === phoneId ? { ...x, status: "sold", sale: saleData } : x);
    updatePhones(next);
    // Down payment is a real customer payment for installment sales.
    if (saleData.saleType === "installment" && Number(saleData.downPayment) > 0) {
      const payment = {
        id: uid(), phoneId, customer: saleData.customer, date: saleData.date,
        amount: Number(saleData.downPayment), currency: saleData.currency,
        method: saleData.paymentMethod || "Cash", notes: "Down payment"
      };
      updateCustomerPayments([payment, ...customerPayments]);
    }
    logActivity("Phone sold", "Sales", {
      detailText: `${p.brand} ${p.model} (IMEI ${p.imei}) → ${saleData.customer} · ${saleData.saleType === "installment" ? "Installment" : "Cash"} · ${fmtMoney(saleData.totalPrice, saleData.currency)}`
    });
    setSellPhone(null);
  };

  const updateSale = (phoneId, saleData) => {
    const old = phones.find(x => x.id === phoneId);
    const next = phones.map((p) => p.id === phoneId ? { ...p, sale: saleData } : p);
    updatePhones(next);
    // Keep historical customer payments; the sale record itself can be edited safely.
    logActivity("Sale edited", "Sales", { detailText: `IMEI ${old?.imei}` });
    setEditSale(null);
  };

  const undoSale = (phoneId) => {
    if (!confirm("Undo this sale and return the phone to stock? Existing customer payments for this phone will also be removed.")) return;
    const p = phones.find((x) => x.id === phoneId);
    updatePhones(phones.map((x) => x.id === phoneId ? { ...x, status: "in_stock", sale: null } : x));
    updateCustomerPayments(customerPayments.filter(x => x.phoneId !== phoneId));
    logActivity("Sale deleted", "Sales", { detailText: p ? `IMEI ${p.imei} returned to stock` : "" });
  };

  const shownSales = sold.filter(p => saleTab === "cash" ? (p.sale?.saleType || "cash") === "cash" : p.sale?.saleType === "installment");

  return (
    <div>
      <SectionHeader title={mode === "stock" ? "Stock" : "Sales"} sub={mode === "stock" ? "Phones currently available in inventory — sold phones are kept separate from stock." : "Record cash and 14-month installment sales separately from stock."} />
      <div style={{ display: "flex", flexWrap: "wrap", gap: 14, marginBottom: 16 }}>
        <StatCard icon={Truck} label="Supplier Stock Remaining" value={debitCount.filter((p) => p.status === "in_stock").length} sub={`of ${debitCount.length} purchased`} tone="primary" />
        <StatCard icon={Banknote} label="Cash Stock Remaining" value={cashCount.filter((p) => p.status === "in_stock").length} sub={`of ${cashCount.length} purchased`} tone="gold" />
        <StatCard icon={PackageX} label="Total Remaining" value={phones.filter((p) => p.status === "in_stock").length} tone="accent" />
        <StatCard icon={PackageCheck} label="Total Sold" value={sold.length} sub={`${cashSales.length} cash · ${installmentSales.length} installment`} tone="success" />
      </div>

      {mode === "stock" && filter === "in_stock" && (
        <BrandBreakdown
          phones={phones.filter((p) => p.status === "in_stock")}
          brands={settings.brands || []}
          activeBrand={activeBrand}
          onSelectBrand={setActiveBrand}
        />
      )}

      <Card style={{ padding: 14, marginBottom: 14 }}>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
          {mode === "sales" ? <Button icon={Plus} onClick={() => setShowNewSale(true)}>New Sale</Button> : null}
          {mode === "stock" ? <>
            <FilterPill active={filter === "in_stock"} onClick={() => setFilter("in_stock")} label="In Stock" />
          </> : <>
            <FilterPill active={saleTab === "cash"} onClick={() => setSaleTab("cash")} label="Cash Sales" />
            <FilterPill active={saleTab === "installment"} onClick={() => setSaleTab("installment")} label="Installment Sales" />
          </>}
          <div style={{ flex: 1 }} />
          {mode === "sales" ? <FilterPill active={filter === "sold"} onClick={() => setFilter("sold")} label="Sold Sales" /> : null}
        </div>
        <div style={{ marginTop: 12, position: "relative", maxWidth: 420 }}>
          <Search size={14} style={{ position: "absolute", left: 10, top: 10, color: C.faint }} />
          <Input placeholder="Search IMEI, brand, model, customer" value={q} onChange={(e) => setQ(e.target.value)} style={{ paddingLeft: 30 }} />
        </div>
      </Card>

      {filter === "in_stock" ? (
        <Card>
          {list.length === 0 ? <EmptyState icon={Smartphone} text="No phones match this view." /> : (
            <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
              <thead><tr>{["IMEI", "Brand / Model", "Source", "Cost", "Status", "Action"].map(h => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
              <tbody>{list.map(p => (
                <tr key={p.id}>
                  <td style={{...tdStyle,fontFamily:MONO}}>{p.imei}</td>
                  <td style={tdStyle}>
                    <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 4, background: brandColor(p.brand, settings.brands || []), marginRight: 7 }} />
                    {p.brand} {p.model}{(p.storage || p.ram || p.simType) ? ` · ${phoneFullSpecLabel(p)}` : ""}
                  </td>
                  <td style={tdStyle}>{p.purchaseType === "debit" ? <Badge tone="accent">Debit</Badge> : <Badge tone="gold">Cash</Badge>}</td>
                  <td style={{...tdStyle,fontFamily:MONO}}>{fmtMoney(p.purchasePrice,p.purchaseCurrency)}</td>
                  <td style={tdStyle}><Badge tone="success">In Stock</Badge></td>
                  <td style={tdStyle}><div style={{display:"flex",gap:5,alignItems:"center"}}>
                    <button title="Edit phone" onClick={() => setEditPhone(p)} style={iconBtn}><Pencil size={14} color={C.sub} /></button>
                    <Button size="sm" variant="subtle" onClick={() => setSellPhone(p)}>Sell</Button>
                  </div></td>
                </tr>
              ))}</tbody>
            </table></div>
          )}
        </Card>
      ) : (
        <Card>
          {shownSales.length === 0 ? <EmptyState icon={saleTab === "cash" ? Banknote : Clock} text={`No ${saleTab} sales yet.`} /> : (
            <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
              <thead><tr>{["IMEI","Brand / Model","Customer","Sale Total","Cost","Profit","Paid","Remaining","Date",""].map(h=><th key={h} style={thStyle}>{h}</th>)}</tr></thead>
              <tbody>{shownSales.map(p => {
                const total = Number(p.sale?.totalPrice ?? p.sale?.price) || 0;
                const paid = paidForPhone(p);
                const rem = Math.max(0,total-paid);
                const cost = purchaseCostInCurrency(p, p.sale.currency, ctx.invoices, settings);
                const profit = total - cost;
                return <tr key={p.id}>
                  <td style={{...tdStyle,fontFamily:MONO}}>{p.imei}</td>
                  <td style={tdStyle}>{p.brand} {p.model}</td>
                  <td style={tdStyle}>{p.sale?.customer}{p.sale?.customerPhone && <div style={{ fontSize: 11, color: C.faint, fontFamily: MONO }}>{p.sale.customerPhone}</div>}{p.sale?.customerLocation && <div style={{ fontSize: 11, color: C.faint }}>{p.sale.customerLocation}</div>}</td>
                  <td style={{...tdStyle,fontFamily:MONO}}>{fmtMoney(total,p.sale.currency)}</td>
                  <td style={{...tdStyle,fontFamily:MONO}}>{fmtMoney(cost,p.sale.currency)}</td>
                  <td style={{...tdStyle,fontFamily:MONO,fontWeight:700,color:profit>=0?C.success:C.danger}}>{fmtMoney(profit,p.sale.currency)}</td>
                  <td style={{...tdStyle,fontFamily:MONO}}>{fmtMoney(paid,p.sale.currency)}</td>
                  <td style={{...tdStyle,fontFamily:MONO,fontWeight:700,color:rem?C.danger:C.success}}>{fmtMoney(rem,p.sale.currency)}</td>
                  <td style={tdStyle}>{fmtDate(p.sale.date)}</td>
                  <td style={tdStyle}><div style={{display:"flex",gap:6}}>
                    <button style={iconBtn} onClick={() => setEditSale(p)}><Pencil size={14} color={C.sub}/></button>
                    {p.sale?.saleType === "installment" && <button style={iconBtn} title="Add payment" onClick={() => { setEditSale({...p,__addPayment:true}); }}><Plus size={14} color={C.success}/></button>}
                    <button style={iconBtn} onClick={() => undoSale(p.id)}><Trash2 size={14} color={C.danger}/></button>
                  </div></td>
                </tr>
              })}</tbody>
            </table></div>
          )}
        </Card>
      )}

      {sellPhone && <SaleModal phone={sellPhone} settings={settings} onClose={()=>setSellPhone(null)} onSave={(data)=>recordSale(sellPhone.id,data)} />}
      {editPhone && <AddPhoneModal settings={settings} initial={editPhone} currency={editPhone.purchaseCurrency || "USD"} exchangeRate={editPhone.purchaseExchangeRate || settings.exchangeRate} onClose={() => setEditPhone(null)} onAdd={saveStockPhone} editing />}
      {showNewSale && <SalePhonePicker phones={phones.filter(p => p.status === "in_stock")} onClose={() => setShowNewSale(false)} onSelect={(p) => { setShowNewSale(false); setSellPhone(p); }} />}
      {editSale && <SaleModal phone={editSale} settings={settings} editing onClose={()=>setEditSale(null)}
        onSave={(data)=>updateSale(editSale.id,data)}
        addPayment={editSale.__addPayment}
        customerPayments={customerPayments}
        updateCustomerPayments={updateCustomerPayments} />}
    </div>
  );
}

function SalePhonePicker({ phones, onClose, onSelect }) {
  const [q, setQ] = useState("");
  const list = phones.filter(p => !q || String(p.imei || "").includes(q) || String(p.brand || "").toLowerCase().includes(q.toLowerCase()) || String(p.model || "").toLowerCase().includes(q.toLowerCase()) || String(p.simType || "").toLowerCase().includes(q.toLowerCase()));
  return (
    <Modal title="New Sale — Select Phone" onClose={onClose}>
      <div style={{ color: C.sub, fontSize: 13, marginBottom: 12 }}>Select an <b>in-stock</b> phone to record its sale. The phone will automatically move from stock to Sold.</div>
      <div style={{ position: "relative", marginBottom: 12 }}>
        <Search size={14} style={{ position: "absolute", left: 10, top: 10, color: C.faint }} />
        <Input autoFocus placeholder="Search IMEI, brand or model" value={q} onChange={e => setQ(e.target.value)} style={{ paddingLeft: 30 }} />
      </div>
      {list.length === 0 ? <EmptyState icon={Smartphone} text={phones.length ? "No in-stock phone matches your search." : "No phones are currently in stock. Add a phone in Purchases first."} /> : (
        <div style={{ maxHeight: 420, overflowY: "auto" }}>
          {list.map(p => (
            <button key={p.id} onClick={() => onSelect(p)} style={{ width: "100%", textAlign: "left", border: `1px solid ${C.border}`, background: C.surface, borderRadius: 10, padding: 12, marginBottom: 8, cursor: "pointer", fontFamily: FONT }}>
              <div style={{ fontWeight: 700, color: C.ink }}>{p.brand} {p.model}{(p.storage || p.ram || p.simType) ? ` · ${phoneFullSpecLabel(p)}` : ""}</div>
              <div style={{ fontSize: 12, color: C.sub, marginTop: 4, fontFamily: MONO }}>IMEI {p.imei} · Cost {fmtMoney(p.purchasePrice, p.purchaseCurrency)}</div>
            </button>
          ))}
        </div>
      )}
      <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 12 }}><Button variant="ghost" onClick={onClose}>Cancel</Button></div>
    </Modal>
  );
}

function FilterPill({ active, onClick, label }) {
  return (
    <button onClick={onClick} style={{
      padding: "7px 13px", borderRadius: 999, border: `1px solid ${active ? C.primary : C.border}`,
      background: active ? C.primary : C.surface, color: active ? "#fff" : C.ink, fontFamily: FONT,
      fontSize: 12.5, fontWeight: 600, cursor: "pointer",
    }}>{label}</button>
  );
}

/* ---------------------------------- SUPPLIER RETURNS ---------------------------------- */
// Records phones sent back to a supplier (defective, wrong item, etc.). Returning a phone
// takes it out of active stock (status "returned") without deleting its purchase history —
// it stays out of "Remaining in Stock" and "Est. Stock Value" but the record is kept here
// so you can see what went back, when, why, and what refund/credit you got for it.

function ReturnPhonePicker({ phones, invoiceMap, onClose, onSelect }) {
  const [q, setQ] = useState("");
  const list = phones.filter(p => !q || String(p.imei || "").includes(q) || String(p.brand || "").toLowerCase().includes(q.toLowerCase()) || String(p.model || "").toLowerCase().includes(q.toLowerCase()) || String(p.simType || "").toLowerCase().includes(q.toLowerCase()));
  return (
    <Modal title="Return a Phone — Select Phone" onClose={onClose}>
      <div style={{ color: C.sub, fontSize: 13, marginBottom: 12 }}>Select an <b>in-stock</b> phone to send back to its supplier. It will be removed from active stock and logged here.</div>
      <div style={{ position: "relative", marginBottom: 12 }}>
        <Search size={14} style={{ position: "absolute", left: 10, top: 10, color: C.faint }} />
        <Input autoFocus placeholder="Search IMEI, brand or model" value={q} onChange={e => setQ(e.target.value)} style={{ paddingLeft: 30 }} />
      </div>
      {list.length === 0 ? <EmptyState icon={Undo2} text={phones.length ? "No in-stock phone matches your search." : "No phones are currently in stock to return."} /> : (
        <div style={{ maxHeight: 420, overflowY: "auto" }}>
          {list.map(p => {
            const inv = invoiceMap[p.invoiceId];
            return (
              <button key={p.id} onClick={() => onSelect(p)} style={{ width: "100%", textAlign: "left", border: `1px solid ${C.border}`, background: C.surface, borderRadius: 10, padding: 12, marginBottom: 8, cursor: "pointer", fontFamily: FONT }}>
                <div style={{ fontWeight: 700, color: C.ink }}>{p.brand} {p.model}{(p.storage || p.ram || p.simType) ? ` · ${phoneFullSpecLabel(p)}` : ""}</div>
                <div style={{ fontSize: 12, color: C.sub, marginTop: 4, fontFamily: MONO }}>IMEI {p.imei} · Cost {fmtMoney(p.purchasePrice, p.purchaseCurrency)}{inv ? ` · Supplier: ${inv.supplier}` : ""}</div>
              </button>
            );
          })}
        </div>
      )}
      <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 12 }}><Button variant="ghost" onClick={onClose}>Cancel</Button></div>
    </Modal>
  );
}

function ReturnDetailsModal({ phone, invoice, initialRecord = null, onClose, onSave }) {
  const [reason, setReason] = useState(initialRecord?.reason || "");
  const [date, setDate] = useState(initialRecord?.date || todayDate());
  const [refundAmount, setRefundAmount] = useState(initialRecord?.refundAmount == null ? "" : String(initialRecord.refundAmount));
  const [refundCurrency, setRefundCurrency] = useState(initialRecord?.refundCurrency || phone.purchaseCurrency || "USD");
  const [notes, setNotes] = useState(initialRecord?.notes || "");

  const submit = () => {
    if (!reason.trim()) return;
    onSave({ reason: reason.trim(), date, refundAmount: refundAmount === "" ? null : Number(refundAmount), refundCurrency, notes: notes.trim() });
  };

  return (
    <Modal title={`${initialRecord ? "Edit Return" : "Return"} — ${phone.brand} ${phone.model}`} onClose={onClose} confirmClose>
      <div style={{ color: C.sub, fontSize: 12.5, marginBottom: 14, fontFamily: MONO }}>
        IMEI {phone.imei}{invoice ? ` · Supplier: ${invoice.supplier} (Invoice ${invoice.number || ""})` : initialRecord?.supplier ? ` · Supplier: ${initialRecord.supplier}` : ""}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <div style={{ gridColumn: "1 / -1" }}>
          <Field label="Reason for Return"><Input value={reason} onChange={(e) => setReason(e.target.value)} placeholder="e.g. Defective screen, wrong model shipped" /></Field>
        </div>
        <Field label="Return Date"><Input type="date" value={date} onChange={(e) => setDate(e.target.value)} /></Field>
        <Field label="Refund / Credit Currency">
          <Select value={refundCurrency} onChange={(e) => setRefundCurrency(e.target.value)}>
            <option value="USD">USD</option><option value="IQD">IQD</option>
          </Select>
        </Field>
        <div style={{ gridColumn: "1 / -1" }}>
          <Field label="Refund / Credit Amount (optional)"><Input type="number" min="0" value={refundAmount} onChange={(e) => setRefundAmount(e.target.value)} placeholder="Leave blank if not yet settled with supplier" /></Field>
        </div>
        <div style={{ gridColumn: "1 / -1" }}>
          <Field label="Notes (optional)"><TextArea value={notes} onChange={(e) => setNotes(e.target.value)} /></Field>
        </div>
      </div>
      <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 18 }}>
        <Button variant="ghost" onClick={onClose}>Discard</Button>
        <Button disabled={!reason.trim()} onClick={submit}>{initialRecord ? "Save Changes" : "Save Return"}</Button>
      </div>
    </Modal>
  );
}
function SupplierReturns({ ctx }) {
  const { phones, updatePhones, invoices, invoiceMap, supplierReturns, updateSupplierReturns, logActivity, addToRecycleBin } = ctx;
  const [showPicker, setShowPicker] = useState(false);
  const [pickedPhone, setPickedPhone] = useState(null);
  const [editingReturn, setEditingReturn] = useState(null);
  const [q, setQ] = useState("");

  const inStockPhones = phones.filter(p => p.status === "in_stock");

  const confirmReturn = (details) => {
    const p = pickedPhone;
    if (!p) return;
    updatePhones(phones.map(x => x.id === p.id ? { ...x, status: "returned" } : x));
    const record = {
      id: uid(), phoneId: p.id, imei: p.imei, brand: p.brand, model: p.model,
      storage: p.storage, ram: p.ram, invoiceId: p.invoiceId,
      supplier: (invoiceMap[p.invoiceId] && invoiceMap[p.invoiceId].supplier) || "-",
      purchasePrice: p.purchasePrice, purchaseCurrency: p.purchaseCurrency,
      ...details, createdAt: nowISO(),
    };
    updateSupplierReturns([record, ...supplierReturns]);
    logActivity("Phone returned to supplier", "Returns", { detailText: `${p.brand} ${p.model} (IMEI ${p.imei}) → ${record.supplier}: ${details.reason}` });
    setPickedPhone(null);
  };

  const saveEditedReturn = (details) => {
    const record = editingReturn;
    if (!record) return;
    const nextRecord = { ...record, ...details, updatedAt: nowISO() };
    updateSupplierReturns(supplierReturns.map(r => r.id === record.id ? nextRecord : r));
    logActivity("Supplier return edited", "Returns", { detailText: `${record.brand} ${record.model} (IMEI ${record.imei})` });
    setEditingReturn(null);
  };

  const deleteReturn = (record) => {
    if (!confirm(`Delete the supplier return for ${record.brand} ${record.model} (IMEI ${record.imei})? The phone will be put back into stock. The deleted return can be restored from Recycle Bin.`)) return;
    const phone = phones.find(p => p.id === record.phoneId);
    if (phone?.status === "sold") {
      alert("This phone has been sold, so its supplier return cannot be deleted.");
      return;
    }
    updatePhones(phones.map(p => p.id === record.phoneId ? { ...p, status: "in_stock" } : p));
    updateSupplierReturns(supplierReturns.filter(r => r.id !== record.id));
    addToRecycleBin({
      type: "supplierReturn",
      label: `Supplier return — ${record.brand} ${record.model} (IMEI ${record.imei})`,
      data: { returnRecord: record },
    });
    logActivity("Supplier return deleted", "Returns", { detailText: `${record.brand} ${record.model} (IMEI ${record.imei}) restored to stock` });
  };

  const list = supplierReturns.filter(r => !q ||
    String(r.imei || "").includes(q) ||
    String(r.brand || "").toLowerCase().includes(q.toLowerCase()) ||
    String(r.model || "").toLowerCase().includes(q.toLowerCase()) ||
    String(r.supplier || "").toLowerCase().includes(q.toLowerCase())
  );

  const totalsByCurrency = { USD: 0, IQD: 0 };
  supplierReturns.forEach(r => { if (r.refundAmount) totalsByCurrency[r.refundCurrency || "USD"] += Number(r.refundAmount) || 0; });

  const editPhone = editingReturn ? (phones.find(p => p.id === editingReturn.phoneId) || editingReturn) : null;
  const editInvoice = editingReturn ? invoiceMap[editingReturn.invoiceId] : null;

  return (
    <div>
      <SectionHeader
        title="Supplier Returns"
        sub="Phones sent back to suppliers — defective, wrong item, or otherwise rejected"
        right={<Button icon={Undo2} onClick={() => setShowPicker(true)}>Return a Phone</Button>}
      />

      <div style={{ display: "flex", flexWrap: "wrap", gap: 14, marginBottom: 18 }}>
        <StatCard icon={Undo2} label="Total Returned" value={supplierReturns.length} tone="danger" />
        <StatCard icon={CircleDollarSign} label="Refunds Received" value={fmtMoney(totalsByCurrency.USD, "USD")} sub={fmtMoney(totalsByCurrency.IQD, "IQD")} tone="success" />
        <StatCard icon={PackageCheck} label="Currently In Stock" value={inStockPhones.length} tone="accent" />
      </div>

      <div style={{ position: "relative", marginBottom: 14, maxWidth: 360 }}>
        <Search size={14} style={{ position: "absolute", left: 10, top: 10, color: C.faint }} />
        <Input placeholder="Search IMEI, brand, model or supplier" value={q} onChange={e => setQ(e.target.value)} style={{ paddingLeft: 30 }} />
      </div>

      {list.length === 0 ? (
        <EmptyState icon={Undo2} text={supplierReturns.length ? "No return matches your search." : "No phones have been returned to a supplier yet."} />
      ) : (
        <Card style={{ padding: 0, overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
            <thead>
              <tr>
                <th style={thStyle}>Date</th>
                <th style={thStyle}>IMEI</th>
                <th style={thStyle}>Brand / Model</th>
                <th style={thStyle}>Supplier</th>
                <th style={thStyle}>Reason</th>
                <th style={thStyle}>Refund</th>
                <th style={thStyle}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {list.map(r => (
                <tr key={r.id}>
                  <td style={tdStyle}>{fmtDate(r.date)}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO }}>{r.imei}</td>
                  <td style={tdStyle}>{r.brand} {r.model}{(r.storage || r.ram || r.simType) ? ` · ${phoneFullSpecLabel(r)}` : ""}</td>
                  <td style={tdStyle}>{r.supplier}</td>
                  <td style={tdStyle}>{r.reason}{r.notes ? <div style={{ fontSize: 11.5, color: C.sub, marginTop: 2 }}>{r.notes}</div> : null}</td>
                  <td style={tdStyle}>{r.refundAmount != null ? fmtMoney(r.refundAmount, r.refundCurrency) : <span style={{ color: C.sub }}>Not settled</span>}</td>
                  <td style={{ ...tdStyle, whiteSpace: "nowrap" }}>
                    <div style={{ display: "flex", gap: 6 }}>
                      <Button size="sm" variant="subtle" icon={Pencil} onClick={() => setEditingReturn(r)}>Edit</Button>
                      <Button size="sm" variant="subtle" icon={Trash2} onClick={() => deleteReturn(r)}>Delete</Button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {showPicker && (
        <ReturnPhonePicker
          phones={inStockPhones}
          invoiceMap={invoiceMap}
          onClose={() => setShowPicker(false)}
          onSelect={(p) => { setShowPicker(false); setPickedPhone(p); }}
        />
      )}
      {pickedPhone && (
        <ReturnDetailsModal
          phone={pickedPhone}
          invoice={invoiceMap[pickedPhone.invoiceId]}
          onClose={() => setPickedPhone(null)}
          onSave={confirmReturn}
        />
      )}
      {editingReturn && editPhone && (
        <ReturnDetailsModal
          phone={editPhone}
          invoice={editInvoice}
          initialRecord={editingReturn}
          onClose={() => setEditingReturn(null)}
          onSave={saveEditedReturn}
        />
      )}
    </div>
  );
}
function SaleModal({ phone, settings, onClose, onSave, editing, addPayment, customerPayments = [], updateCustomerPayments }) {
  const s = phone.sale || {};
  const [customer, setCustomer] = useState(s.customer || settings.customers[0] || "");
  const [customerPhone, setCustomerPhone] = useState(s.customerPhone || (settings.customerPhones && settings.customerPhones[s.customer || settings.customers[0]]) || "");
  const [customerLocation, setCustomerLocation] = useState(s.customerLocation || (settings.customerLocations && settings.customerLocations[s.customer || settings.customers[0]]) || "");
  const [date, setDate] = useState(s.date || todayDate());
  const [saleType, setSaleType] = useState(s.saleType || "cash");
  const [price, setPrice] = useState(s.totalPrice ?? s.price ?? "");
  const [currency, setCurrency] = useState(s.currency || "USD");
  const [saleRate, setSaleRate] = useState(s.exchangeRate || settings.exchangeRate || 1460);
  const [downPayment, setDownPayment] = useState(s.downPayment ?? (s.paymentType === "Cash" ? s.price : "") ?? "");
  const [months, setMonths] = useState(14);
  const [plannedMonthly, setPlannedMonthly] = useState(s.plannedMonthlyPayment ?? "");
  const [paymentMethod, setPaymentMethod] = useState(s.paymentMethod || settings.paymentMethods[0] || "Cash");
  const [notes, setNotes] = useState(s.notes || "");

  const total = Number(price) || 0;
  const existingPaid = customerPayments.filter(x=>x.phoneId===phone.id).reduce((a,x)=>a+(Number(x.amount)||0),0);
  const submit = () => {
    if (!customer || !price || total <= 0) return;
    if (saleType === "installment" && Number(downPayment) > total) return;
    const dp = saleType === "installment" ? Number(downPayment || 0) : total;
    const remaining = Math.max(0, total - dp);
    const monthly = saleType === "installment" ? (Number(plannedMonthly) > 0 ? Number(plannedMonthly) : remaining / 14) : 0;
    const schedule = saleType === "installment" ? Array.from({length:14}, (_, i) => {
      const d = new Date(date + "T12:00:00");
      d.setMonth(d.getMonth() + i + 1);
      const planned = i === 13 ? Math.max(0, remaining - monthly * 13) : monthly;
      return { no:i+1, dueDate:d.toISOString().slice(0,10), amount: planned, paid:0, paidDate:"", notes:"", status:"Unpaid" };
    }) : [];
    onSave({
      customer, customerPhone: (customerPhone || "").trim(), customerLocation: (customerLocation || "").trim(), date, totalPrice: total, price: total, currency, saleType,
      exchangeRate: Number(saleRate) || Number(settings.exchangeRate) || 1,
      downPayment: dp, installmentMonths: saleType === "installment" ? 14 : 0,
      plannedMonthlyPayment: saleType === "installment" ? monthly : 0,
      installmentSchedule: saleType === "installment" ? (s.installmentSchedule?.length === 14 ? s.installmentSchedule : schedule) : [],
      paymentMethod, notes
    });
  };

  const [newPaymentAmount, setNewPaymentAmount] = useState("");
  const [newPaymentDate, setNewPaymentDate] = useState(todayDate());
  const [newPaymentMethod, setNewPaymentMethod] = useState(settings.paymentMethods[0] || "Cash");
  const [newPaymentNotes, setNewPaymentNotes] = useState("");

  const addInstallmentPayment = () => {
    if (!updateCustomerPayments) return;
    const remaining = Math.max(0,total-existingPaid);
    const amount = Number(newPaymentAmount || 0);
    const pdate = newPaymentDate || todayDate();
    if (!amount || amount > remaining) return;
    const method = newPaymentMethod || settings.paymentMethods[0];
    updateCustomerPayments([{id:uid(),phoneId:phone.id,customer:customer,date:pdate,amount,currency,method,notes:newPaymentNotes || "Installment payment"},...customerPayments]);
    alert(`Payment of ${fmtMoney(amount,currency)} recorded.`);
    onClose();
  };

  if (addPayment) return (
    <Modal title={`Add Installment Payment — ${phone.brand} ${phone.model}`} onClose={onClose}>
      <div style={{marginBottom:12,color:C.sub}}>Customer: <b>{customer}</b>{customerPhone && <> · Phone: <b>{customerPhone}</b></>}{customerLocation && <> · Location: <b>{customerLocation}</b></>} · Total: <b>{fmtMoney(total,currency)}</b> · Paid: <b>{fmtMoney(existingPaid,currency)}</b> · Remaining: <b style={{color:C.danger}}>{fmtMoney(Math.max(0,total-existingPaid),currency)}</b></div>
      <Field label="Payment Amount"><Input type="number" min="0" value={newPaymentAmount} onChange={e=>setNewPaymentAmount(e.target.value)} /></Field>
      <Field label="Payment Date"><Input type="date" value={newPaymentDate} onChange={e=>setNewPaymentDate(e.target.value)} /></Field>
      <Field label="Payment Method"><Select value={newPaymentMethod} onChange={e=>setNewPaymentMethod(e.target.value)}>{settings.paymentMethods.map(m=><option key={m} value={m}>{m}</option>)}</Select></Field>
      <Field label="Notes"><TextArea value={newPaymentNotes} onChange={e=>setNewPaymentNotes(e.target.value)} placeholder="Optional note about this payment" /></Field>
      <div style={{display:"flex",justifyContent:"flex-end",gap:8,marginTop:18}}><Button variant="ghost" onClick={onClose}>Cancel</Button><Button onClick={addInstallmentPayment}>Record Payment</Button></div>
    </Modal>
  );

  return (
    <Modal confirmClose title={`${editing ? "Edit Sale" : "Record Sale"} — ${phone.brand} ${phone.model}`} onClose={onClose}>
      <div style={{fontSize:12.5,color:C.sub,marginBottom:12,fontFamily:MONO}}>IMEI {phone.imei}</div>
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12}}>
        <Field label="Sale Type">
          <Select value={saleType} onChange={e=>setSaleType(e.target.value)}>
            <option value="cash">Cash Sale</option><option value="installment">Installment Sale</option>
          </Select>
        </Field>
        <Field label="Customer">
          <Input list="customers-list" value={customer} onChange={e=>{
            const next = e.target.value;
            setCustomer(next);
            const known = settings.customerPhones && settings.customerPhones[next];
            if (known) setCustomerPhone(known);
            const knownLoc = settings.customerLocations && settings.customerLocations[next];
            if (knownLoc) setCustomerLocation(knownLoc);
          }} />
          <datalist id="customers-list">{settings.customers.map(c=><option key={c} value={c}/>)}</datalist>
        </Field>
        <Field label="Customer Phone Number (optional)"><Input value={customerPhone} onChange={e=>setCustomerPhone(e.target.value)} placeholder="e.g. 0770 123 4567" /></Field>
        <Field label="Customer Location / Residence (optional)"><Input value={customerLocation} onChange={e=>setCustomerLocation(e.target.value)} placeholder="e.g. Duhok, Nwroz street" /></Field>
        <Field label="Sale Date"><Input type="date" value={date} onChange={e=>setDate(e.target.value)} /></Field>
        <Field label={saleType==="installment" ? "Installment Total Price" : "Cash Sale Price"}><Input type="number" min="0" value={price} onChange={e=>setPrice(e.target.value)} /></Field>
        <Field label="Currency"><Select value={currency} onChange={e=>setCurrency(e.target.value)}><option value="USD">USD</option><option value="IQD">IQD</option></Select></Field>
        <Field label="Exchange Rate (1 USD = IQD)"><Input type="number" min="1" value={saleRate} onChange={e=>setSaleRate(e.target.value)} /></Field>
        {saleType==="installment" && <>
          <Field label="Down Payment"><Input type="number" min="0" value={downPayment} onChange={e=>setDownPayment(e.target.value)} /></Field>
          <Field label="Installment Duration"><Input value="14 months" readOnly /></Field>
          <Field label="Planned Monthly Payment"><Input type="number" min="0" value={plannedMonthly} onChange={e=>setPlannedMonthly(e.target.value)} placeholder="Optional — e.g. 100000" /></Field>
          <Field label="Payment Method"><Select value={paymentMethod} onChange={e=>setPaymentMethod(e.target.value)}>{settings.paymentMethods.map(m=><option key={m} value={m}>{m}</option>)}</Select></Field>
        </>}
        {saleType==="cash" && <Field label="Payment Method"><Select value={paymentMethod} onChange={e=>setPaymentMethod(e.target.value)}>{settings.paymentMethods.map(m=><option key={m} value={m}>{m}</option>)}</Select></Field>}
        <div style={{gridColumn:"1 / -1"}}><Field label="Notes (optional)"><TextArea value={notes} onChange={e=>setNotes(e.target.value)} /></Field></div>
      </div>
      {saleType==="installment" && <div style={{marginTop:12,padding:12,borderRadius:10,background:C.bg}}>
        <b>Remaining after down payment:</b> {fmtMoney(Math.max(0,total-(Number(downPayment)||0)),currency)}
        <div style={{fontSize:12,color:C.sub,marginTop:4}}>Planned monthly amount: {fmtMoney(Number(plannedMonthly)||Math.max(0,total-(Number(downPayment)||0))/14,currency)}</div>
      </div>}
      <div style={{display:"flex",justifyContent:"flex-end",gap:8,marginTop:18}}><Button variant="ghost" onClick={onClose}>Discard</Button><Button disabled={!customer || !price} onClick={submit}>{editing ? "Save Changes" : "Save Sale"}</Button></div>
    </Modal>
  );
}

/* ---------------------------------- CUSTOMER PAYMENTS ---------------------------------- */

function CustomerPayments({ ctx }) {
  const { phones, customerPayments, updateCustomerPayments, updatePhones, settings, logActivity } = ctx;
  const sold = phones.filter(p => p.status === "sold" && p.sale?.saleType === "installment");
  const [filter, setFilter] = useState("");
  const [open, setOpen] = useState(null);
  const rows = sold.filter(p => !filter || String(p.sale.customer).toLowerCase().includes(filter.toLowerCase()) || String(p.imei).includes(filter));

  const totals = (p) => {
    const total = Number(p.sale.totalPrice ?? p.sale.price) || 0;
    const paid = customerPayments.filter(x=>x.phoneId===p.id).reduce((s,x)=>s+(Number(x.amount)||0),0);
    return {total,paid,remaining:Math.max(0,total-paid)};
  };

  const scheduleFor = (p) => {
    const existing = Array.isArray(p.sale.installmentSchedule) && p.sale.installmentSchedule.length === 14 ? p.sale.installmentSchedule : Array.from({length:14}, (_,i)=>{
      const d = new Date((p.sale.date || todayDate()) + "T12:00:00"); d.setMonth(d.getMonth()+i+1);
      const rem = Math.max(0, (Number(p.sale.totalPrice)||0)-(Number(p.sale.downPayment)||0));
      const monthly = Number(p.sale.plannedMonthlyPayment) > 0 ? Number(p.sale.plannedMonthlyPayment) : rem/14;
      return {no:i+1,dueDate:d.toISOString().slice(0,10),amount:i===13?Math.max(0,rem-monthly*13):monthly,paid:0,paidDate:"",notes:"",status:"Unpaid"};
    });
    return existing.map(item => {
      const paidRows = customerPayments.filter(x=>x.phoneId===p.id && Number(x.installmentNo)===Number(item.no));
      const paid = paidRows.reduce((s,x)=>s+(Number(x.amount)||0),0);
      const last = paidRows[0];
      const remaining = Math.max(0, Number(item.amount||0)-paid);
      return {...item, paid, remaining, paidDate:last?.date||item.paidDate||"", notes:last?.notes||item.notes||"", status:remaining<=0?"Paid":paid>0?"Partially Paid":"Unpaid", payments: paidRows};
    });
  };

  const saveSchedule = (p, schedule) => {
    updatePhones(phones.map(x => x.id===p.id ? {...x, sale:{...x.sale, installmentSchedule:schedule}} : x));
  };

  const addPayment = (p, item, amount, date, method, notes) => {
    const schedule = scheduleFor(p);
    const remaining = Number(item.remaining||0);
    if (!amount || amount > remaining) return;
    updateCustomerPayments([{id:uid(),phoneId:p.id,customer:p.sale.customer,date,amount:Number(amount),currency:p.sale.currency,method,notes,installmentNo:item.no},...customerPayments]);
    const next = schedule.map(x => x.no===item.no ? {...x, paid: Number(x.paid||0) + Number(amount), paidDate:date, notes, status:(Number(x.paid||0)+Number(amount)) >= Number(x.amount||0) ? "Paid" : "Partially Paid"} : x);
    saveSchedule(p,next);
    logActivity("Installment payment", "Customer Payments", {detailText:`${p.sale.customer} · Payment ${item.no}/14 · ${fmtMoney(amount,p.sale.currency)}`});
  };

  // Corrects a specific already-recorded payment (e.g. a typo like 100 instead
  // of 100,000) instead of adding a new payment on top of the mistake.
  const editPayment = (p, paymentId, patch) => {
    const original = customerPayments.find(x => x.id === paymentId);
    if (!original) return;
    const nextAmount = patch.amount !== undefined ? Number(patch.amount) : Number(original.amount);
    const nextPayments = customerPayments.map(x => x.id === paymentId ? { ...x, ...patch, amount: nextAmount } : x);
    updateCustomerPayments(nextPayments);

    const installmentNo = original.installmentNo;
    const schedule = scheduleFor(p);
    const paidRows = nextPayments.filter(x => x.phoneId === p.id && Number(x.installmentNo) === Number(installmentNo));
    const paidTotal = paidRows.reduce((s, x) => s + (Number(x.amount) || 0), 0);
    const last = paidRows[0];
    const next = schedule.map(x => x.no === installmentNo ? {
      ...x, paid: paidTotal, paidDate: last?.date || x.paidDate, notes: last?.notes || x.notes,
      status: paidTotal >= Number(x.amount || 0) ? "Paid" : paidTotal > 0 ? "Partially Paid" : "Unpaid",
    } : x);
    saveSchedule(p, next);
    logActivity("Payment corrected", "Customer Payments", {
      detailText: `${p.sale.customer} · Installment ${installmentNo}/14 corrected from ${fmtMoney(original.amount, p.sale.currency)} to ${fmtMoney(nextAmount, p.sale.currency)}`,
    });
  };

  return <div>
    <SectionHeader title="Customer Payments" sub="14-month installment schedule — planned amount is separate from the actual amount the customer can pay" />
    <div style={{display:"flex",gap:10,marginBottom:14}}><Input placeholder="Search customer or IMEI" value={filter} onChange={e=>setFilter(e.target.value)}/></div>
    <Card>
      {rows.length===0 ? <EmptyState icon={Wallet} text="No installment sales yet."/> :
      <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}><thead><tr>{["Customer","IMEI","Phone","Total","Paid","Remaining","Term","Schedule"].map(h=><th key={h} style={thStyle}>{h}</th>)}</tr></thead>
      <tbody>{rows.map(p=>{const t=totals(p);return <React.Fragment key={p.id}>
        <tr>
          <td style={tdStyle}>{p.sale.customer}{p.sale.customerLocation && <div style={{ fontSize: 11, color: C.faint }}>{p.sale.customerLocation}</div>}</td><td style={{...tdStyle,fontFamily:MONO}}>{p.imei}</td><td style={tdStyle}>{p.brand} {p.model}</td>
          <td style={{...tdStyle,fontFamily:MONO}}>{fmtMoney(t.total,p.sale.currency)}</td><td style={{...tdStyle,fontFamily:MONO}}>{fmtMoney(t.paid,p.sale.currency)}</td>
          <td style={{...tdStyle,fontFamily:MONO,fontWeight:700,color:t.remaining?C.danger:C.success}}>{fmtMoney(t.remaining,p.sale.currency)}</td>
          <td style={tdStyle}>14 months</td>
          <td style={tdStyle}><Button size="sm" variant="subtle" onClick={()=>setOpen(open===p.id?null:p.id)}>{open===p.id?"Hide":"View 14 Payments"}</Button></td>
        </tr>
        {open===p.id && <tr><td colSpan="8" style={{padding:0}}>
          <div style={{padding:14,background:C.bg}}>
            <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}>
              <table style={{...tableStyle,background:C.surface}}><thead><tr>{["#","Due Date","Planned","Actual Paid","Remaining","Paid Date","Status","Notes",""].map(h=><th key={h} style={thStyle}>{h}</th>)}</tr></thead>
              <tbody>{scheduleFor(p).map(item=><InstallmentRow key={item.no} phone={p} item={item} settings={settings} onPay={(amount,date,method,notes)=>addPayment(p,item,amount,date,method,notes)} onEditPayment={(paymentId,patch)=>editPayment(p,paymentId,patch)}/>)}</tbody></table>
            </div>
          </div>
        </td></tr>}
      </React.Fragment>})}</tbody></table></div>}
    </Card>
  </div>;
}

/* ---------------------------------- PERSONAL INFORMATION ---------------------------------- */

// A single searchable directory of every person the shop deals with: suppliers and
// cash-purchase sellers on one side, customers (cash + installment buyers) on the
// other. Pulls name/phone/location from the settings address book first, falling
// back to whatever was entered directly on an invoice, cash purchase, or sale.
function PersonalInformation({ ctx }) {
  const { settings, invoices, invoiceTotals, phones, customerPayments } = ctx;
  const [q, setQ] = useState("");
  const [roleFilter, setRoleFilter] = useState("all");

  // ---- Sellers: suppliers you buy from on debit/invoice ----
  const supplierNames = Array.from(new Set([...(settings.suppliers || []), ...invoices.map((i) => i.supplier)])).filter(Boolean);
  const supplierRows = supplierNames.map((name) => {
    const invs = invoices.filter((i) => i.supplier === name);
    const totals = invs.reduce((a, inv) => {
      const t = invoiceTotals[inv.id] || {};
      return {
        totalUSD: a.totalUSD + (t.totalUSD || 0), totalIQD: a.totalIQD + (t.totalIQD || 0),
        paidUSD: a.paidUSD + (t.paidUSD || 0), paidIQD: a.paidIQD + (t.paidIQD || 0),
        remainingUSD: a.remainingUSD + (t.remainingUSD || 0), remainingIQD: a.remainingIQD + (t.remainingIQD || 0),
      };
    }, { totalUSD: 0, totalIQD: 0, paidUSD: 0, paidIQD: 0, remainingUSD: 0, remainingIQD: 0 });
    const itemCount = phones.filter((p) => p.invoiceId && invs.some((i) => i.id === p.invoiceId) && p.status !== "returned").length;
    const latestInv = invs.slice().sort((a, b) => new Date(b.date) - new Date(a.date))[0];
    const phone = (settings.supplierPhones && settings.supplierPhones[name]) || latestInv?.supplierPhone || "";
    const location = (settings.supplierLocations && settings.supplierLocations[name]) || latestInv?.supplierLocation || "";
    return {
      key: "supplier:" + name, name, phone, location, role: "Seller (Supplier)", dealLabel: "purchased",
      itemCount, dealUSD: totals.totalUSD, dealIQD: totals.totalIQD,
      paidUSD: totals.paidUSD, paidIQD: totals.paidIQD, remainingUSD: totals.remainingUSD, remainingIQD: totals.remainingIQD,
    };
  }).filter((r) => r.itemCount > 0 || r.dealUSD > 0 || (settings.suppliers || []).includes(r.name));

  // ---- Sellers: one-off people you bought phones from with cash ----
  const cashSellerNames = Array.from(new Set(phones.filter((p) => p.purchaseType === "cash" && p.purchasedFrom).map((p) => p.purchasedFrom)));
  const cashSellerRows = cashSellerNames.map((name) => {
    const list = phones.filter((p) => p.purchaseType === "cash" && p.purchasedFrom === name && p.status !== "returned");
    const dealUSD = list.reduce((s, p) => s + purchaseCostInCurrency(p, "USD", invoices, settings), 0);
    const dealIQD = list.reduce((s, p) => s + purchaseCostInCurrency(p, "IQD", invoices, settings), 0);
    const latest = list.slice().sort((a, b) => new Date(b.date) - new Date(a.date))[0];
    return {
      key: "cashSeller:" + name, name, phone: latest?.purchasedFromPhone || "", location: latest?.sellerLocation || "",
      role: "Seller (Cash Purchase)", dealLabel: "purchased", itemCount: list.length,
      dealUSD, dealIQD, paidUSD: dealUSD, paidIQD: dealIQD, remainingUSD: 0, remainingIQD: 0,
    };
  });

  // ---- Buyers: customers you sold phones to, cash or installment ----
  const customerNames = Array.from(new Set([...(settings.customers || []), ...phones.filter((p) => p.sale?.customer).map((p) => p.sale.customer)])).filter(Boolean);
  const customerRows = customerNames.map((name) => {
    const list = phones.filter((p) => p.status === "sold" && p.sale?.customer === name);
    const dealUSD = list.reduce((s, p) => s + saleValueInCurrency(p, "USD", settings), 0);
    const dealIQD = list.reduce((s, p) => s + saleValueInCurrency(p, "IQD", settings), 0);
    let paidUSD = 0, paidIQD = 0, remainingUSD = 0, remainingIQD = 0;
    list.forEach((p) => {
      const cur = p.sale?.currency || "USD";
      const rate = getSaleRate(p, settings);
      const total = Number(p.sale?.totalPrice ?? p.sale?.price) || 0;
      if ((p.sale?.saleType || "cash") === "cash") {
        paidUSD += convertCurrency(total, cur, "USD", rate);
        paidIQD += convertCurrency(total, cur, "IQD", rate);
      } else {
        const paid = customerPayments.filter((x) => x.phoneId === p.id).reduce((s, x) => s + (Number(x.amount) || 0), 0);
        const remaining = Math.max(0, total - paid);
        paidUSD += convertCurrency(paid, cur, "USD", rate);
        paidIQD += convertCurrency(paid, cur, "IQD", rate);
        remainingUSD += convertCurrency(remaining, cur, "USD", rate);
        remainingIQD += convertCurrency(remaining, cur, "IQD", rate);
      }
    });
    const latest = list.slice().sort((a, b) => new Date(b.sale.date) - new Date(a.sale.date))[0];
    const phone = (settings.customerPhones && settings.customerPhones[name]) || latest?.sale?.customerPhone || "";
    const location = (settings.customerLocations && settings.customerLocations[name]) || latest?.sale?.customerLocation || "";
    return {
      key: "customer:" + name, name, phone, location, role: "Buyer (Customer)", dealLabel: "bought",
      itemCount: list.length, dealUSD, dealIQD, paidUSD, paidIQD, remainingUSD, remainingIQD,
    };
  }).filter((r) => r.itemCount > 0 || (settings.customers || []).includes(r.name));

  const allRows = [...supplierRows, ...cashSellerRows, ...customerRows];

  const filtered = allRows
    .filter((r) => (roleFilter === "all" || (roleFilter === "seller" && r.role.startsWith("Seller")) || (roleFilter === "buyer" && r.role.startsWith("Buyer"))))
    .filter((r) => {
      if (!q) return true;
      const s = q.toLowerCase();
      return r.name.toLowerCase().includes(s) || (r.location || "").toLowerCase().includes(s) || (r.phone || "").toLowerCase().includes(s);
    })
    .sort((a, b) => a.name.localeCompare(b.name));

  return (
    <div>
      <SectionHeader title="Personal Information" sub="Every seller and buyer in one searchable directory — where they live, how to reach them, and what they still owe or are owed" />
      <div style={{ display: "flex", gap: 10, marginBottom: 14, flexWrap: "wrap", alignItems: "center" }}>
        <div style={{ position: "relative", flex: "1 1 260px" }}>
          <Search size={14} style={{ position: "absolute", left: 10, top: 10, color: C.faint }} />
          <Input placeholder="Search by name, location, or phone number" value={q} onChange={(e) => setQ(e.target.value)} style={{ paddingLeft: 30 }} />
        </div>
        <Tabs value={roleFilter} onChange={setRoleFilter} options={[{ id: "all", label: "All" }, { id: "seller", label: "Sellers" }, { id: "buyer", label: "Buyers" }]} />
      </div>
      <Card>
        {filtered.length === 0 ? <EmptyState icon={Users} text="No matching contacts." /> : (
          <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}>
            <table style={tableStyle}>
              <thead><tr>{["Name", "Location / Residence", "Phone", "Role", "Items", "Total (Bought/Sold)", "Paid", "Remaining"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
              <tbody>
                {filtered.map((r) => (
                  <tr key={r.key}>
                    <td style={tdStyle}><b>{r.name}</b></td>
                    <td style={tdStyle}>{r.location || "-"}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{r.phone || "-"}</td>
                    <td style={tdStyle}><Badge tone={r.role.startsWith("Seller") ? "gold" : "accent"}>{r.role}</Badge></td>
                    <td style={tdStyle}>{r.itemCount} {r.dealLabel}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(r.dealUSD, "USD")} / {fmtMoney(r.dealIQD, "IQD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO, color: C.success }}>{fmtMoney(r.paidUSD, "USD")} / {fmtMoney(r.paidIQD, "IQD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700, color: (r.remainingUSD > 0.01 || r.remainingIQD > 1) ? C.danger : C.success }}>{fmtMoney(r.remainingUSD, "USD")} / {fmtMoney(r.remainingIQD, "IQD")}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </div>
  );
}

// A single already-recorded payment within an installment's history, editable
// in place — e.g. fixing 100 typed instead of 100,000.
function EditablePaymentEntry({ payment, currency, settings, onSave }) {
  const [editing, setEditing] = useState(false);
  const [amount, setAmount] = useState(payment.amount);
  const [date, setDate] = useState(payment.date || todayDate());
  const [method, setMethod] = useState(payment.method || settings.paymentMethods[0] || "Cash");
  const [notes, setNotes] = useState(payment.notes || "");

  if (!editing) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "7px 0", borderBottom: `1px solid ${C.border}` }}>
        <div style={{ flex: 1, fontSize: 12.5, color: C.ink }}>
          {fmtMoney(payment.amount, currency)} <span style={{ color: C.sub }}>· {fmtDate(payment.date)}{payment.method ? ` · ${payment.method}` : ""}</span>
          {payment.notes && <div style={{ fontSize: 11, color: C.faint }}>{payment.notes}</div>}
        </div>
        <Button size="sm" variant="subtle" onClick={() => setEditing(true)}>Edit</Button>
      </div>
    );
  }

  return (
    <div style={{ padding: "10px 0", borderBottom: `1px solid ${C.border}`, display: "flex", flexDirection: "column", gap: 8, maxWidth: 340 }}>
      <Field label="Amount Paid"><Input type="number" min="0" value={amount} onChange={(e) => setAmount(e.target.value)} /></Field>
      <Field label="Payment Date"><Input type="date" value={date} onChange={(e) => setDate(e.target.value)} /></Field>
      <Field label="Payment Method"><Select value={method} onChange={(e) => setMethod(e.target.value)}>{settings.paymentMethods.map((m) => <option key={m}>{m}</option>)}</Select></Field>
      <Field label="Notes"><TextArea value={notes} onChange={(e) => setNotes(e.target.value)} /></Field>
      <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
        <Button size="sm" variant="ghost" onClick={() => setEditing(false)}>Cancel</Button>
        <Button size="sm" disabled={!amount || Number(amount) <= 0} onClick={() => { onSave({ amount: Number(amount), date, method, notes }); setEditing(false); }}>Save</Button>
      </div>
    </div>
  );
}

function InstallmentRow({phone,item,settings,onPay,onEditPayment}) {
  const [editing,setEditing]=useState(false);
  const [showHistory,setShowHistory]=useState(false);
  const [amount,setAmount]=useState("");
  const [date,setDate]=useState(item.dueDate||todayDate());
  const [notes,setNotes]=useState(item.notes||"");
  const [method,setMethod]=useState(settings.paymentMethods[0]||"Cash");
  const paymentCount = (item.payments || []).length;
  return <>
  <tr>
    <td style={{...tdStyle,fontFamily:MONO,fontWeight:700}}>{item.no}/14</td>
    <td style={tdStyle}>{fmtDate(item.dueDate)}</td>
    <td style={{...tdStyle,fontFamily:MONO}}>{fmtMoney(item.amount,phone.sale.currency)}</td>
    <td style={{...tdStyle,fontFamily:MONO}}>{fmtMoney(item.paid,phone.sale.currency)}</td>
    <td style={{...tdStyle,fontFamily:MONO,color:item.remaining?C.danger:C.success}}>{fmtMoney(item.remaining,phone.sale.currency)}</td>
    <td style={tdStyle}>{item.paidDate ? fmtDate(item.paidDate) : "-"}</td>
    <td style={tdStyle}><Badge tone={item.status==="Paid"?"success":item.status==="Partially Paid"?"warning":"sub"}>{item.status}</Badge></td>
    <td style={tdStyle}>{item.notes||"-"}</td>
    <td style={tdStyle}>
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
        <Button size="sm" variant="subtle" disabled={!item.remaining} onClick={()=>setEditing(!editing)}>{editing?"Cancel":"Record Payment"}</Button>
        {paymentCount > 0 && <Button size="sm" variant="ghost" onClick={()=>setShowHistory(!showHistory)}>{showHistory?"Hide":`Edit (${paymentCount})`}</Button>}
      </div>
    </td>
  </tr>
  {editing && <tr>
    <td colSpan="9" style={{padding:0,background:C.bg}}>
      <div style={{padding:14,display:"flex",flexDirection:"column",gap:8,maxWidth:340}}>
        <div style={{fontSize:12,color:C.sub}}>Planned: <b>{fmtMoney(item.amount,phone.sale.currency)}</b> · Remaining for this installment: <b>{fmtMoney(item.remaining,phone.sale.currency)}</b></div>
        <Field label="Actual Amount Paid"><Input type="number" min="0" max={item.remaining} value={amount} onChange={e=>setAmount(e.target.value)} placeholder="Actual amount customer paid"/></Field>
        <Field label="Payment Date"><Input type="date" value={date} onChange={e=>setDate(e.target.value)}/></Field>
        <Field label="Payment Method"><Select value={method} onChange={e=>setMethod(e.target.value)}>{settings.paymentMethods.map(m=><option key={m}>{m}</option>)}</Select></Field>
        <Field label="Notes"><TextArea value={notes} onChange={e=>setNotes(e.target.value)} placeholder="Notes"/></Field>
        <div style={{display:"flex",gap:8,justifyContent:"flex-end"}}>
          <Button size="sm" variant="ghost" onClick={()=>setEditing(false)}>Cancel</Button>
          <Button size="sm" disabled={!amount||Number(amount)<=0||Number(amount)>item.remaining} onClick={()=>{onPay(Number(amount),date,method,notes);setEditing(false)}}>Record Payment</Button>
        </div>
      </div>
    </td>
  </tr>}
  {showHistory && <tr>
    <td colSpan="9" style={{padding:0,background:C.bg}}>
      <div style={{padding:14}}>
        <div style={{fontSize:12,fontWeight:700,color:C.ink,marginBottom:4}}>Recorded payments for this installment</div>
        <div style={{fontSize:11.5,color:C.sub,marginBottom:6}}>Fix a mistaken amount here instead of adding another payment on top of it.</div>
        {(item.payments || []).map((pay) => (
          <EditablePaymentEntry key={pay.id} payment={pay} currency={phone.sale.currency} settings={settings} onSave={(patch) => onEditPayment(pay.id, patch)} />
        ))}
      </div>
    </td>
  </tr>}
  </>;
}

/* ---------------------------------- SUPPLIER PAYMENTS ---------------------------------- */


function SupplierPayments({ ctx }) {
  const { invoices, invoiceTotals, payments, settings } = ctx;
  const [payFor, setPayFor] = useState(null);
  const [bulkPay, setBulkPay] = useState(false);
  const [statusFilter, setStatusFilter] = useState("all");

  const rows = invoices.map((inv) => ({ inv, t: invoiceTotals[inv.id] }))
    .filter((r) => statusFilter === "all" || r.t.status === statusFilter)
    .sort((a, b) => b.t.remaining - a.t.remaining);

  return (
    <div>
      <SectionHeader title="Supplier Payments" sub="Pay against invoice totals — never against individual phones"
        right={<Button icon={Plus} onClick={() => setBulkPay(true)}>Record Payment</Button>} />
      <div style={{ display: "flex", gap: 8, marginBottom: 14, flexWrap: "wrap" }}>
        {["all", "Unpaid", "Partially Paid", "Paid"].map((s) => (
          <FilterPill key={s} active={statusFilter === s} onClick={() => setStatusFilter(s)} label={s === "all" ? "All" : s} />
        ))}
      </div>
      {rows.length === 0 ? <Card><EmptyState icon={Wallet} text="No invoices match this filter." /></Card> : (
        <Card>
          <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
            <thead><tr>{["Invoice #", "Supplier", "Date", "Total", "Paid", "Remaining", "Status", ""].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
            <tbody>
              {rows.map(({ inv, t }) => (
                <tr key={inv.id}>
                  <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700 }}>{inv.number}</td>
                  <td style={tdStyle}>{inv.supplier}</td>
                  <td style={tdStyle}>{fmtDate(inv.date)}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(t.totalUSD, "USD")} / {fmtMoney(t.totalIQD, "IQD")}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(t.paidUSD, "USD")} / {fmtMoney(t.paidIQD, "IQD")}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700 }}>{fmtMoney(t.remainingUSD, "USD")} / {fmtMoney(t.remainingIQD, "IQD")}</td>
                  <td style={tdStyle}><StatusBadge status={t.status} /></td>
                  <td style={tdStyle}>{t.remaining > 0 ? <Button size="sm" variant="subtle" onClick={() => setPayFor(inv)}>Pay</Button> : <Button size="sm" variant="subtle" icon={Pencil} onClick={() => setPayFor(inv)}>Edit</Button>}</td>
                </tr>
              ))}
            </tbody>
          </table></div>
        </Card>
      )}
      {payFor && (
        <InvoiceDetailModal ctx={ctx} invoiceId={payFor.id} onClose={() => setPayFor(null)} />
      )}
      {bulkPay && (
        <SupplierBulkPaymentModal ctx={ctx} onClose={() => setBulkPay(false)} />
      )}
    </div>
  );
}

/* ---------------------------------- ANALYTICS ---------------------------------- */


function DateAnalysis({ ctx }) {
  const { phones, invoices, supplierReturns, payments, customerPayments } = ctx;
  const [fromDate, setFromDate] = useState("");
  const [toDate, setToDate] = useState("");
  const [type, setType] = useState("all");
  const [source, setSource] = useState("all");
  const [query, setQuery] = useState("");

  const events = useMemo(() => {
    const out = [];
    const invoiceById = Object.fromEntries(invoices.map(i => [i.id, i]));

    invoices.forEach(inv => out.push({
      id: `invoice-${inv.id}`, date: inv.date, type: "purchase", label: "Purchase Invoice",
      supplier: inv.supplier || "-", reference: inv.number || "-", brand: "", model: "", imei: "",
      amount: Number(inv.total) || 0, currency: inv.currency || "USD",
      detail: `${inv.number || "-"} · ${inv.supplier || "-"}`, source: inv.supplier || "Unknown supplier"
    }));

    phones.forEach(p => {
      const inv = p.invoiceId ? invoiceById[p.invoiceId] : null;
      const purchaseDate = p.purchaseType === "debit" ? (inv?.date || p.date || p.createdAt) : (p.date || p.createdAt);
      out.push({
        id: `phone-purchase-${p.id}`, date: purchaseDate, type: "purchase", label: "Phone Purchased",
        supplier: inv?.supplier || p.purchasedFrom || "-", reference: inv?.number || "-",
        brand: p.brand || "", model: p.model || "", imei: p.imei || "",
        amount: Number(p.purchasePrice) || 0, currency: p.purchaseCurrency || "USD",
        detail: `${p.brand || ""} ${p.model || ""} · IMEI ${p.imei || "-"}`,
        source: inv?.supplier || p.purchasedFrom || "Unknown source"
      });
      if (p.sale) out.push({
        id: `sale-${p.id}`, date: p.sale.date || p.sale.createdAt || p.createdAt, type: "sale", label: "Sale",
        supplier: "", reference: p.sale.customer || "-", brand: p.brand || "", model: p.model || "", imei: p.imei || "",
        amount: Number(p.sale.totalPrice ?? p.sale.price) || 0, currency: p.sale.currency || "USD",
        detail: `${p.brand || ""} ${p.model || ""} · ${p.sale.customer || "Customer"} · ${p.sale.saleType === "installment" ? "Installment" : "Cash"}`,
        source: p.sale.customer || "Customer"
      });
    });

    supplierReturns.forEach(r => out.push({
      id: `return-${r.id}`, date: r.date || r.createdAt, type: "return", label: "Supplier Return",
      supplier: r.supplier || "-", reference: r.imei || "-", brand: r.brand || "", model: r.model || "", imei: r.imei || "",
      amount: Number(r.refundAmount) || 0, currency: r.refundCurrency || r.purchaseCurrency || "USD",
      detail: `${r.brand || ""} ${r.model || ""} · IMEI ${r.imei || "-"} · ${r.reason || "Return"}`,
      source: r.supplier || "Supplier"
    }));

    payments.forEach(p => {
      const inv = invoiceById[p.invoiceId];
      out.push({
        id: `supplier-payment-${p.id}`, date: p.date || p.createdAt, type: "supplierPayment", label: "Supplier Payment",
        supplier: inv?.supplier || "-", reference: inv?.number || "-", brand: "", model: "", imei: "",
        amount: Number(p.amount) || 0, currency: p.currency || inv?.currency || "USD",
        detail: `${fmtMoney(p.amount, p.currency || inv?.currency || "USD")} · ${inv?.supplier || "Supplier"}`,
        source: inv?.supplier || "Supplier"
      });
    });

    customerPayments.forEach(p => {
      const phone = phones.find(x => x.id === p.phoneId);
      out.push({
        id: `customer-payment-${p.id}`, date: p.date || p.createdAt, type: "customerPayment", label: "Customer Payment",
        supplier: "", reference: p.customer || "-", brand: phone?.brand || "", model: phone?.model || "", imei: phone?.imei || "",
        amount: Number(p.amount) || 0, currency: p.currency || phone?.sale?.currency || "USD",
        detail: `${fmtMoney(p.amount, p.currency || phone?.sale?.currency || "USD")} · ${p.customer || phone?.sale?.customer || "Customer"}`,
        source: p.customer || "Customer"
      });
    });
    return out.filter(e => e.date).sort((a,b) => new Date(a.date) - new Date(b.date));
  }, [phones, invoices, supplierReturns, payments, customerPayments]);

  const sources = useMemo(() => [...new Set(events.map(e => e.source).filter(Boolean))].sort(), [events]);
  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return events.filter(e => {
      const d = String(e.date).slice(0,10);
      if (fromDate && d < fromDate) return false;
      if (toDate && d > toDate) return false;
      if (type !== "all" && e.type !== type) return false;
      if (source !== "all" && e.source !== source) return false;
      if (q && ![e.label,e.detail,e.source,e.reference,e.imei,e.brand,e.model].join(" ").toLowerCase().includes(q)) return false;
      return true;
    });
  }, [events, fromDate, toDate, type, source, query]);

  const stats = useMemo(() => {
    const s = {
      invoiceCount: 0, phonePurchases: 0, sales: 0, returns: 0, supplierPayments: 0, customerPayments: 0,
      purchaseValue: {}, salesValue: {}, returnValue: {}, supplierPaid: {}, customerReceived: {}
    };
    const add = (obj, e) => { obj[e.currency] = (obj[e.currency] || 0) + (Number(e.amount) || 0); };
    filtered.forEach(e => {
      if (e.label === "Purchase Invoice") s.invoiceCount++;
      if (e.label === "Phone Purchased") { s.phonePurchases++; add(s.purchaseValue, e); }
      if (e.type === "sale") { s.sales++; add(s.salesValue, e); }
      if (e.type === "return") { s.returns++; add(s.returnValue, e); }
      if (e.type === "supplierPayment") { s.supplierPayments++; add(s.supplierPaid, e); }
      if (e.type === "customerPayment") { s.customerPayments++; add(s.customerReceived, e); }
    });
    return s;
  }, [filtered]);

  const first = filtered[0], last = filtered[filtered.length - 1];
  const spanDays = first && last ? Math.max(0, Math.ceil((new Date(String(last.date).slice(0,10)) - new Date(String(first.date).slice(0,10))) / 86400000)) : 0;
  const currencies = useMemo(() => [...new Set(filtered.map(e => e.currency).filter(Boolean))].sort(), [filtered]);
  const moneyLines = (obj) => currencies.map(cur => obj[cur] ? `${fmtMoney(obj[cur], cur)}` : null).filter(Boolean).join("  ·  ") || "—";
  const eventTone = { purchase: "primary", sale: "success", return: "danger", supplierPayment: "warning", customerPayment: "accent" };

  const purchaseBySource = useMemo(() => {
    const m = {};
    filtered.filter(e => e.label === "Phone Purchased").forEach(e => {
      const key = e.source || "Unknown source";
      if (!m[key]) m[key] = { count: 0, values: {} };
      m[key].count++; m[key].values[e.currency] = (m[key].values[e.currency] || 0) + e.amount;
    });
    return Object.entries(m).sort((a,b) => b[1].count - a[1].count);
  }, [filtered]);

  const dailyActivity = useMemo(() => {
    const m = {};
    filtered.forEach(e => { const d = String(e.date).slice(0,10); m[d] = (m[d] || 0) + 1; });
    return Object.entries(m).sort((a,b) => b[0].localeCompare(a[0])).slice(0, 7);
  }, [filtered]);

  const clearFilters = () => { setFromDate(""); setToDate(""); setType("all"); setSource("all"); setQuery(""); };
  const MiniMetric = ({ label, value, tone = "primary", icon: Icon }) => {
    const color = { primary:C.primary, success:C.success, danger:C.danger, warning:C.warning, accent:C.accent, gold:C.gold }[tone];
    return <div style={{display:"flex",alignItems:"center",gap:9,padding:"9px 10px",borderRadius:11,background:color+"0F",border:`1px solid ${color}25`}}>
      <div style={{width:28,height:28,borderRadius:8,background:color+"18",display:"flex",alignItems:"center",justifyContent:"center"}}><Icon size={14} color={color}/></div>
      <div><div style={{fontSize:10.5,color:C.sub,fontWeight:700,textTransform:"uppercase",letterSpacing:.35}}>{label}</div><div style={{fontSize:13,fontWeight:800,color:C.ink,marginTop:1}}>{value}</div></div>
    </div>;
  };
  const AnalysisCard = ({ icon: Icon, label, value, sub, tone="primary", children }) => {
    const color={primary:C.primary,success:C.success,danger:C.danger,warning:C.warning,accent:C.accent,gold:C.gold}[tone];
    return <Card style={{padding:16,minHeight:132,position:"relative",overflow:"hidden"}}>
      <div style={{position:"absolute",right:-20,top:-24,width:78,height:78,borderRadius:"50%",background:color+"0B"}} />
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",position:"relative"}}>
        <div style={{fontSize:11.5,color:C.sub,fontWeight:800,textTransform:"uppercase",letterSpacing:.45}}>{label}</div>
        <div style={{width:34,height:34,borderRadius:10,background:color+"16",display:"flex",alignItems:"center",justifyContent:"center"}}><Icon size={17} color={color}/></div>
      </div>
      <div style={{fontFamily:MONO,fontSize:22,fontWeight:800,color:C.ink,marginTop:10,position:"relative"}}>{value}</div>
      {sub && <div style={{fontSize:11.5,color:C.sub,marginTop:4,lineHeight:1.45,position:"relative"}}>{sub}</div>}
      {children}
    </Card>;
  };

  return <div>
    <SectionHeader title="Date Analysis" sub="Professional timeline and financial activity analysis across your existing purchases, sales, returns and payments." />

    <Card style={{padding:16,marginBottom:14,background:`linear-gradient(135deg, ${C.surface}, ${C.primarySoft})`}}>
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap",marginBottom:12}}>
        <div><div style={{fontSize:15,fontWeight:800,color:C.ink}}>Analysis Period</div><div style={{fontSize:11.5,color:C.sub,marginTop:2}}>Filter the complete transaction history without changing any stored data.</div></div>
        <Badge tone="sub">{filtered.length.toLocaleString()} records</Badge>
      </div>
      <div style={{display:"grid",gridTemplateColumns:"repeat(2,minmax(0,1fr))",gap:10}}>
        <Field label="From"><Input type="date" value={fromDate} onChange={e=>setFromDate(e.target.value)} /></Field>
        <Field label="To"><Input type="date" value={toDate} onChange={e=>setToDate(e.target.value)} /></Field>
        <Field label="Record Type"><Select value={type} onChange={e=>setType(e.target.value)}><option value="all">All Records</option><option value="purchase">Purchases</option><option value="sale">Sales</option><option value="return">Returns</option><option value="supplierPayment">Supplier Payments</option><option value="customerPayment">Customer Payments</option></Select></Field>
        <Field label="Purchased From / Source"><Select value={source} onChange={e=>setSource(e.target.value)}><option value="all">All Sources</option>{sources.map(x=><option key={x} value={x}>{x}</option>)}</Select></Field>
      </div>
      <div style={{display:"flex",gap:10,marginTop:10,alignItems:"center"}}><div style={{flex:1}}><Input value={query} onChange={e=>setQuery(e.target.value)} placeholder="Search IMEI, model, supplier, customer, invoice..." /></div><Button variant="ghost" size="sm" onClick={clearFilters}>Clear</Button></div>
    </Card>

    <div style={{display:"grid",gridTemplateColumns:"repeat(2,minmax(0,1fr))",gap:10,marginBottom:14}}>
      <AnalysisCard icon={History} label="Records Analyzed" value={filtered.length.toLocaleString()} sub={first&&last?`${fmtDate(first.date)} → ${fmtDate(last.date)}`:"No matching records"} tone="primary" />
      <AnalysisCard icon={Clock} label="Activity Span" value={`${spanDays} days`} sub={first&&last?`${spanDays===0?"Same-day activity":"From first recorded event to latest event"}`:"Select a period to begin"} tone="accent" />
      <AnalysisCard icon={ShoppingBag} label="Purchasing Activity" value={stats.phonePurchases.toLocaleString()} sub={`${stats.invoiceCount} purchase invoices · ${moneyLines(stats.purchaseValue)}`} tone="gold" />
      <AnalysisCard icon={Smartphone} label="Sales Activity" value={stats.sales.toLocaleString()} sub={moneyLines(stats.salesValue)} tone="success" />
      <AnalysisCard icon={Undo2} label="Returns" value={stats.returns.toLocaleString()} sub={moneyLines(stats.returnValue)} tone="danger" />
      <AnalysisCard icon={Wallet} label="Payment Activity" value={(stats.supplierPayments+stats.customerPayments).toLocaleString()} sub={`${stats.supplierPayments} supplier · ${stats.customerPayments} customer`} tone="warning" />
    </div>

    <Card style={{padding:16,marginBottom:14}}>
      <div style={{fontSize:14,fontWeight:800,marginBottom:10}}>Financial Activity Overview</div>
      <div style={{display:"grid",gridTemplateColumns:"repeat(2,minmax(0,1fr))",gap:9}}>
        <MiniMetric icon={ShoppingBag} label="Purchased Value" value={moneyLines(stats.purchaseValue)} tone="gold" />
        <MiniMetric icon={TrendUp} label="Sales Value" value={moneyLines(stats.salesValue)} tone="success" />
        <MiniMetric icon={Undo2} label="Returned Value" value={moneyLines(stats.returnValue)} tone="danger" />
        <MiniMetric icon={Banknote} label="Supplier Paid" value={moneyLines(stats.supplierPaid)} tone="warning" />
        <MiniMetric icon={Wallet} label="Customer Received" value={moneyLines(stats.customerReceived)} tone="accent" />
        <MiniMetric icon={History} label="Total Activity" value={`${filtered.length} records`} tone="primary" />
      </div>
    </Card>

    {purchaseBySource.length > 0 && <Card style={{padding:16,marginBottom:14}}>
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12}}><div><div style={{fontSize:14,fontWeight:800}}>Purchased From — Source Performance</div><div style={{fontSize:11.5,color:C.sub}}>Who supplied your phones and how many units came from each source.</div></div><Badge tone="sub">{purchaseBySource.length} sources</Badge></div>
      <div style={{display:"grid",gap:8}}>{purchaseBySource.map(([name,v],idx)=><div key={name} style={{display:"grid",gridTemplateColumns:"30px 1fr auto",gap:10,alignItems:"center",padding:"10px 0",borderTop:idx?`1px solid ${C.border}`:"none"}}>
        <div style={{width:28,height:28,borderRadius:8,background:C.primarySoft,color:C.primary,display:"flex",alignItems:"center",justifyContent:"center",fontWeight:800,fontSize:12}}>{idx+1}</div>
        <div><div style={{fontWeight:750,fontSize:13}}>{name}</div><div style={{fontSize:11.5,color:C.sub,marginTop:2}}>{v.count} phone{v.count===1?"":"s"} purchased</div></div>
        <div style={{textAlign:"right",fontFamily:MONO,fontSize:12.5,fontWeight:700}}>{Object.entries(v.values).map(([cur,val])=><div key={cur}>{fmtMoney(val,cur)}</div>)}</div>
      </div>)}</div>
    </Card>}

    <Card style={{padding:16,marginBottom:14}}>
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12}}><div><div style={{fontSize:14,fontWeight:800}}>Recent Activity Density</div><div style={{fontSize:11.5,color:C.sub}}>Number of records created on each of the latest active dates.</div></div><Badge tone="sub">Latest 7 active dates</Badge></div>
      {dailyActivity.length ? <div style={{display:"grid",gap:8}}>{dailyActivity.map(([date,count])=><div key={date} style={{display:"grid",gridTemplateColumns:"90px 1fr 42px",gap:10,alignItems:"center"}}><div style={{fontFamily:MONO,fontSize:11.5,color:C.sub}}>{fmtDate(date)}</div><div style={{height:8,borderRadius:99,background:C.border,overflow:"hidden"}}><div style={{height:"100%",width:`${Math.max(8,(count/Math.max(...dailyActivity.map(x=>x[1])))*100)}%`,background:C.primary,borderRadius:99}} /></div><div style={{fontFamily:MONO,fontSize:12,fontWeight:800,textAlign:"right"}}>{count}</div></div>)}</div> : <EmptyState icon={History} text="No activity in the selected period." />}
    </Card>

    <Card style={{padding:16}}>
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12,gap:8}}><div><div style={{fontSize:14,fontWeight:800}}>Complete Chronological Record</div><div style={{fontSize:11.5,color:C.sub}}>Every matching purchase, sale, return and payment from first → last.</div></div><Badge tone="sub">{filtered.length} records</Badge></div>
      {filtered.length===0 ? <EmptyState icon={History} text="No records match the selected dates or filters." /> : <div style={{display:"grid",gap:0}}>{filtered.map((e,i)=><div key={`${e.id}-${i}`} style={{display:"grid",gridTemplateColumns:"86px 30px 1fr auto",gap:9,alignItems:"start",padding:"11px 0",borderTop:i?`1px solid ${C.border}`:"none"}}>
        <div style={{fontFamily:MONO,fontSize:11,color:C.sub,paddingTop:4}}>{fmtDate(e.date)}</div>
        <div style={{width:26,height:26,borderRadius:8,background:(eventTone[e.type]==="success"?C.successSoft:eventTone[e.type]==="danger"?C.dangerSoft:eventTone[e.type]==="warning"?C.warningSoft:C.primarySoft),display:"flex",alignItems:"center",justifyContent:"center"}}><Glyph name={e.type==="sale"?"trendUp":e.type==="return"?"returnArrow":e.type.includes("Payment")?"wallet":"cart"} size={13} color={eventTone[e.type]==="success"?C.success:eventTone[e.type]==="danger"?C.danger:eventTone[e.type]==="warning"?C.warning:C.primary}/></div>
        <div><div style={{display:"flex",gap:7,alignItems:"center",flexWrap:"wrap"}}><Badge tone={eventTone[e.type]||"sub"}>{e.label}</Badge><span style={{fontWeight:700,fontSize:12.5}}>{e.detail}</span></div>{e.source&&e.type!=="sale"&&e.type!=="customerPayment"?<div style={{fontSize:11.5,color:C.sub,marginTop:3}}>Source: {e.source}</div>:null}</div>
        <div style={{fontFamily:MONO,fontSize:12,fontWeight:800,textAlign:"right",whiteSpace:"nowrap"}}>{e.amount?fmtMoney(e.amount,e.currency):""}</div>
      </div>)}</div>}
    </Card>
  </div>;
}

function AnalyticsOverview({ ctx }) {
  const { phones, settings } = ctx;
  const brands = settings.brands || [];
  const [focusBrand, setFocusBrand] = useState(null);

  const byBrand = brands.map((brand) => {
    const set = phones.filter((p) => (p.brand || "") === brand);
    const purchased = set.length;
    const sold = set.filter((p) => p.status === "sold").length;
    const remaining = set.filter((p) => p.status === "in_stock").length;
    const returned = set.filter((p) => p.status === "returned").length;
    // Purchase value has to stay split by currency — USD and IQD totals can't be blended.
    const valueByCurrency = {};
    set.filter((p) => p.status !== "returned").forEach((p) => {
      const cur = p.purchaseCurrency || "USD";
      valueByCurrency[cur] = (valueByCurrency[cur] || 0) + (Number(p.purchasePrice) || 0);
    });
    const activeCount = set.filter((p) => p.status !== "returned").length;
    const avgByCurrency = {};
    Object.entries(valueByCurrency).forEach(([cur, total]) => {
      const countInCur = set.filter((p) => p.status !== "returned" && (p.purchaseCurrency || "USD") === cur).length;
      avgByCurrency[cur] = countInCur ? total / countInCur : 0;
    });
    return { brand, purchased, sold, remaining, returned, valueByCurrency, avgByCurrency, color: brandColor(brand, brands) };
  }).filter((x) => x.purchased > 0 || x.brand === focusBrand);

  const totals = byBrand.reduce((acc, x) => ({
    purchased: acc.purchased + x.purchased, sold: acc.sold + x.sold,
    remaining: acc.remaining + x.remaining, returned: acc.returned + x.returned,
  }), { purchased: 0, sold: 0, remaining: 0, returned: 0 });

  const rows = focusBrand ? byBrand.filter((x) => x.brand === focusBrand) : byBrand;

  return (
    <div>
      <h2 style={{ fontSize: 20, fontWeight: 800, marginBottom: 4 }}>Analytics</h2>
      <div style={{ color: C.sub, fontSize: 13, marginBottom: 16 }}>Devices by brand — purchased, sold, remaining, returned, and price breakdown.</div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 16 }}>
        <StatCard icon={ShoppingBag} label="Total Purchased" value={totals.purchased} tone="primary" />
        <StatCard icon={Smartphone} label="Total Sold" value={totals.sold} tone="accent" />
        <StatCard icon={PackageCheck} label="Total Remaining" value={totals.remaining} tone="gold" />
        <StatCard icon={Undo2} label="Total Returned" value={totals.returned} tone="danger" />
      </div>

      <Card style={{ padding: 14, marginBottom: 16 }}>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
          <FilterPill active={!focusBrand} onClick={() => setFocusBrand(null)} label="All Brands" />
          {brands.map((b) => (
            <FilterPill key={b} active={focusBrand === b} onClick={() => setFocusBrand(focusBrand === b ? null : b)} label={b} />
          ))}
        </div>
      </Card>

      {rows.map((r) => (
        <Card key={r.brand} style={{ padding: 16, marginBottom: 14, borderLeft: `4px solid ${r.color}` }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
            <span style={{ width: 10, height: 10, borderRadius: 5, background: r.color }} />
            <h3 style={{ margin: 0, fontSize: 16, fontWeight: 800 }}>{r.brand}</h3>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10, marginBottom: 14 }}>
            <MiniStat label="Purchased" value={r.purchased} />
            <MiniStat label="Sold" value={r.sold} />
            <MiniStat label="Remaining" value={r.remaining} />
            <MiniStat label="Returned" value={r.returned} />
          </div>

          <div style={{ fontSize: 11.5, fontWeight: 700, color: C.sub, textTransform: "uppercase", letterSpacing: 0.3, marginBottom: 6 }}>
            Purchase value ({r.brand} — active devices, excl. returns)
          </div>
          {Object.keys(r.valueByCurrency).length === 0 ? (
            <div style={{ fontSize: 13, color: C.faint }}>No purchase data.</div>
          ) : (
            <div style={{ display: "flex", flexWrap: "wrap", gap: 20 }}>
              {Object.entries(r.valueByCurrency).map(([cur, total]) => (
                <div key={cur}>
                  <div style={{ fontFamily: MONO, fontSize: 18, fontWeight: 800, color: C.ink }}>{fmtMoney(total, cur)}</div>
                  <div style={{ fontSize: 11.5, color: C.sub }}>Total ({cur}) · Avg {fmtMoney(r.avgByCurrency[cur], cur)}/device</div>
                </div>
              ))}
            </div>
          )}
        </Card>
      ))}
    </div>
  );
}

function Analytics({ ctx }) {
  const [tool, setTool] = useState("overview");

  const tools = [
    { id: "overview", label: "Overview", icon: FileBarChart },
    { id: "dateAnalysis", label: "Date Analysis", icon: History },
    { id: "reports", label: "Reports & Activity", icon: FileBarChart },
    { id: "debitAnalysis", label: "Debit Analysis", icon: Wallet },
    { id: "balanceAnalysis", label: "Balance Analysis", icon: Banknote },
    { id: "currencyPnl", label: "Currency P&L", icon: Scale },
  ];

  return (
    <div>
      <div style={{ marginBottom: 14 }}>
        <h2 style={{ fontSize: 20, fontWeight: 800, margin: 0, color: C.ink }}>Analytics</h2>
        <div style={{ color: C.sub, fontSize: 13, marginTop: 4 }}>
          All analysis, reports and financial tools in one place.
        </div>
      </div>

      <div style={{
        display: "grid",
        gridTemplateColumns: "repeat(2, minmax(0, 1fr))",
        gap: 8,
        marginBottom: 18,
      }}>
        {tools.map((item) => {
          const Icon = item.icon;
          const active = tool === item.id;
          return (
            <button
              key={item.id}
              onClick={() => setTool(item.id)}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 9,
                minHeight: 48,
                padding: "8px 11px",
                borderRadius: 13,
                border: `1px solid ${active ? C.accent : C.border}`,
                background: active ? C.accentSoft : C.surface,
                color: active ? C.accent : C.ink,
                cursor: "pointer",
                fontFamily: FONT,
                fontSize: 11.5,
                fontWeight: 700,
                textAlign: "left",
                boxShadow: active ? `0 2px 8px ${C.accent}18` : "none",
              }}
            >
              <span style={{
                width: 30,
                height: 30,
                borderRadius: 9,
                display: "grid",
                placeItems: "center",
                flex: "0 0 auto",
                background: active ? C.surface : C.primarySoft,
              }}>
                <Icon size={17} color={active ? C.accent : C.primary} />
              </span>
              <span>{item.label}</span>
            </button>
          );
        })}
      </div>

      {tool === "overview" && <AnalyticsOverview ctx={ctx} />}
      {tool === "dateAnalysis" && <DateAnalysis ctx={ctx} />}
      {tool === "reports" && <Reports ctx={ctx} />}
      {tool === "debitAnalysis" && <DebitAnalysis ctx={ctx} />}
      {tool === "balanceAnalysis" && <BalanceAnalysis ctx={ctx} />}
      {tool === "currencyPnl" && <CurrencyPnL ctx={ctx} />}
    </div>
  );
}

// Shared deadline computation used by both Reports → Payment Deadlines and the
// Home screen's "Payments Due" card, so the two never drift out of sync.
function computeDeadlines({ phones, invoices, invoiceTotals, customerPayments }) {
  const today = todayDate();

  const supplierDeadlines = invoices
    .filter((inv) => inv.dueDate && invoiceTotals[inv.id].remaining > 0)
    .map((inv) => {
      const t = invoiceTotals[inv.id];
      const overdue = inv.dueDate < today;
      const daysOverdue = overdue ? Math.max(1, Math.floor((new Date(today + "T12:00:00") - new Date(inv.dueDate + "T12:00:00")) / 86400000)) : 0;
      return { ...inv, t, overdue, daysOverdue };
    })
    .sort((a, b) => String(a.dueDate).localeCompare(String(b.dueDate)));

  const customerDeadlines = [];
  phones.filter((p) => p.status === "sold" && p.sale?.saleType === "installment").forEach((p) => {
    const total = Number(p.sale.totalPrice ?? p.sale.price) || 0;
    const downPayment = Number(p.sale.downPayment) || 0;
    const remAfterDown = Math.max(0, total - downPayment);
    const monthly = Number(p.sale.plannedMonthlyPayment) > 0 ? Number(p.sale.plannedMonthlyPayment) : remAfterDown / 14;
    const existing = Array.isArray(p.sale.installmentSchedule) && p.sale.installmentSchedule.length === 14 ? p.sale.installmentSchedule : Array.from({length:14}, (_,i) => {
      const d = new Date((p.sale.date || todayDate()) + "T12:00:00"); d.setMonth(d.getMonth()+i+1);
      const amount = i === 13 ? Math.max(0, remAfterDown - monthly * 13) : monthly;
      return { no:i+1, dueDate:d.toISOString().slice(0,10), amount };
    });
    existing.forEach((item) => {
      const paid = customerPayments.filter(x => x.phoneId === p.id && Number(x.installmentNo) === Number(item.no)).reduce((s,x) => s + (Number(x.amount)||0), 0);
      const remaining = Math.max(0, Number(item.amount || 0) - paid);
      if (!item.dueDate || remaining <= 0) return;
      const overdue = item.dueDate < today;
      const daysOverdue = overdue ? Math.max(1, Math.floor((new Date(today + "T12:00:00") - new Date(item.dueDate + "T12:00:00")) / 86400000)) : 0;
      customerDeadlines.push({ phone:p, item, paid, remaining, overdue, daysOverdue });
    });
  });
  customerDeadlines.sort((a,b) => String(a.item.dueDate).localeCompare(String(b.item.dueDate)));

  return { supplierDeadlines, customerDeadlines };
}

function Reports({ ctx }) {
  const { phones, invoices, payments, customerPayments, invoiceTotals, activityLog } = ctx;
  const [tab, setTab] = useState("purchases");

  const returnedPhones = phones.filter((p) => p.status === "returned");
  const soldPhones = phones.filter((p) => p.status === "sold");
  const stockPhones = phones.filter((p) => p.status === "in_stock");
  const debitPhones = phones.filter((p) => p.purchaseType === "debit");
  const cashPhones = phones.filter((p) => p.purchaseType === "cash");
  const today = todayDate();

  const supplierBalances = {};
  invoices.forEach((inv) => {
    const t = invoiceTotals[inv.id];
    if (!supplierBalances[inv.supplier]) supplierBalances[inv.supplier] = { USD: { total: 0, paid: 0 }, IQD: { total: 0, paid: 0 } };
    supplierBalances[inv.supplier].USD.total += t.totalUSD;
    supplierBalances[inv.supplier].USD.paid += t.paidUSD;
    supplierBalances[inv.supplier].IQD.total += t.totalIQD;
    supplierBalances[inv.supplier].IQD.paid += t.paidIQD;
  });

  const { supplierDeadlines, customerDeadlines } = computeDeadlines({ phones, invoices, invoiceTotals, customerPayments });

  const overdueSupplierCount = supplierDeadlines.filter(x => x.overdue).length;
  const overdueCustomerCount = customerDeadlines.filter(x => x.overdue).length;

  const DeadlineStatus = ({ overdue, paid=false }) => {
    if (paid) return <Badge tone="success">Paid</Badge>;
    if (overdue) return <Badge tone="danger">Overdue</Badge>;
    return <Badge tone="accent">Upcoming</Badge>;
  };

  return (
    <div>
      <SectionHeader title="Reports & Activity" sub="Understand the business at a glance" />
      <Tabs value={tab} onChange={setTab} options={[
        { id: "purchases", label: "Purchases" },
        { id: "sales", label: "Sales" },
        { id: "stock", label: "Stock" },
        { id: "invoices", label: "Invoices" },
        { id: "suppliers", label: "Supplier Balances" },
        { id: "deadlines", label: "Payment Deadlines" },
        { id: "activity", label: "Activity Log" },
      ]} />

      {tab === "purchases" && (
        <Card style={{ padding: 16 }}>
          <div style={{ display: "flex", gap: 14, marginBottom: 14, flexWrap: "wrap" }}>
            <MiniStat label="Debit Purchases" value={debitPhones.length} />
            <MiniStat label="Cash Purchases" value={cashPhones.length} />
            <MiniStat label="Total Purchased" value={phones.length} />
            <MiniStat label="Total Returned" value={returnedPhones.length} />
            <MiniStat label="Active Purchased" value={phones.length - returnedPhones.length} />
          </div>
          <ReportTable rows={phones} columns={[
            { h: "IMEI", k: (p) => p.imei, mono: true },
            { h: "Brand / Model", k: (p) => `${p.brand} ${p.model}` },
            { h: "Type", k: (p) => p.purchaseType === "debit" ? "Debit" : "Cash" },
            { h: "Status", k: (p) => p.status === "returned" ? "Returned" : p.status === "sold" ? "Sold" : "In Stock" },
            { h: "Price (actual)", k: (p) => fmtMoney(p.purchasePrice, p.purchaseCurrency), mono: true },
            { h: "≈ USD", k: (p) => fmtMoney(purchaseCostInCurrency(p, "USD", invoices, ctx.settings), "USD"), mono: true },
            { h: "≈ IQD", k: (p) => fmtMoney(purchaseCostInCurrency(p, "IQD", invoices, ctx.settings), "IQD"), mono: true },
            { h: "Date", k: (p) => fmtDate(p.date) },
          ]} empty="No purchases recorded." />
        </Card>
      )}

      {tab === "sales" && (
        <Card style={{ padding: 16 }}>
          <ReportTable rows={soldPhones} columns={[
            { h: "IMEI", k: (p) => p.imei, mono: true },
            { h: "Brand / Model", k: (p) => `${p.brand} ${p.model}` },
            { h: "Customer", k: (p) => p.sale.customer },
            { h: "Sale Price (actual)", k: (p) => fmtMoney(p.sale.totalPrice ?? p.sale.price, p.sale.currency), mono: true },
            { h: "Sale ≈ USD", k: (p) => fmtMoney(saleValueInCurrency(p, "USD", ctx.settings), "USD"), mono: true },
            { h: "Sale ≈ IQD", k: (p) => fmtMoney(saleValueInCurrency(p, "IQD", ctx.settings), "IQD"), mono: true },
            { h: "Cost", k: (p) => fmtMoney(purchaseCostInCurrency(p, p.sale.currency, invoices, ctx.settings), p.sale.currency), mono: true },
            { h: "Profit (actual)", k: (p) => fmtMoney(saleProfit(p, invoices, ctx.settings), p.sale.currency), mono: true },
            { h: "Sale Date", k: (p) => fmtDate(p.sale.date) },
            { h: "Payment", k: (p) => p.sale.saleType === "installment" ? "Installment" : "Cash" },
          ]} empty="No sales yet." />
        </Card>
      )}

      {tab === "stock" && (
        <Card style={{ padding: 16 }}>
          <ReportTable rows={stockPhones} columns={[
            { h: "IMEI", k: (p) => p.imei, mono: true },
            { h: "Brand / Model", k: (p) => `${p.brand} ${p.model}` },
            { h: "Source", k: (p) => p.purchaseType === "debit" ? "Debit" : "Cash" },
            { h: "Status", k: (p) => p.status === "returned" ? "Returned" : p.status === "sold" ? "Sold" : "In Stock" },
            { h: "Cost (actual)", k: (p) => fmtMoney(p.purchasePrice, p.purchaseCurrency), mono: true },
            { h: "≈ USD", k: (p) => fmtMoney(purchaseCostInCurrency(p, "USD", invoices, ctx.settings), "USD"), mono: true },
            { h: "≈ IQD", k: (p) => fmtMoney(purchaseCostInCurrency(p, "IQD", invoices, ctx.settings), "IQD"), mono: true },
            { h: "Purchased", k: (p) => fmtDate(p.date) },
          ]} empty="No remaining stock." />
        </Card>
      )}

      {tab === "invoices" && (
        <Card style={{ padding: 16 }}>
          <ReportTable rows={invoices} columns={[
            { h: "Invoice #", k: (i) => i.number, mono: true },
            { h: "Supplier", k: (i) => i.supplier },
            { h: "Total", k: (i) => `${fmtMoney(invoiceTotals[i.id].totalUSD, "USD")} / ${fmtMoney(invoiceTotals[i.id].totalIQD, "IQD")}`, mono: true },
            { h: "Paid", k: (i) => `${fmtMoney(invoiceTotals[i.id].paidUSD, "USD")} / ${fmtMoney(invoiceTotals[i.id].paidIQD, "IQD")}`, mono: true },
            { h: "Remaining", k: (i) => `${fmtMoney(invoiceTotals[i.id].remainingUSD, "USD")} / ${fmtMoney(invoiceTotals[i.id].remainingIQD, "IQD")}`, mono: true },
            { h: "Due Date", k: (i) => i.dueDate ? fmtDate(i.dueDate) : "-" },
            { h: "Status", k: (i) => invoiceTotals[i.id].status },
          ]} empty="No invoices yet." />
        </Card>
      )}

      {tab === "suppliers" && (
        <Card style={{ padding: 16 }}>
          {Object.keys(supplierBalances).length === 0 ? <EmptyState icon={Truck} text="No supplier data yet." /> : (
            <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
              <thead><tr>{["Supplier", "Total (USD)", "Paid (USD)", "Balance (USD)", "Total (IQD)", "Paid (IQD)", "Balance (IQD)"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
              <tbody>
                {Object.entries(supplierBalances).map(([sup, v]) => (
                  <tr key={sup}>
                    <td style={tdStyle}>{sup}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(v.USD.total, "USD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(v.USD.paid, "USD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700, color: v.USD.total - v.USD.paid > 0 ? C.danger : C.success }}>{fmtMoney(v.USD.total - v.USD.paid, "USD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(v.IQD.total, "IQD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(v.IQD.paid, "IQD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700, color: v.IQD.total - v.IQD.paid > 0 ? C.danger : C.success }}>{fmtMoney(v.IQD.total - v.IQD.paid, "IQD")}</td>
                  </tr>
                ))}
              </tbody>
            </table></div>
          )}
        </Card>
      )}

      {tab === "deadlines" && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(320px,1fr))", gap: 14 }}>
          <Card style={{ padding: 16 }}>
            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", gap:10, marginBottom:12 }}>
              <div><h3 style={{margin:0,fontSize:16}}>Supplier Payment Deadlines</h3><div style={{fontSize:12,color:C.sub,marginTop:4}}>Invoices that still have a balance and have a recorded payment deadline.</div></div>
              <MiniStat label="Overdue" value={overdueSupplierCount} tone={overdueSupplierCount ? "danger" : "success"} />
            </div>
            {supplierDeadlines.length === 0 ? <EmptyState icon={CheckCircle2} text="No supplier deadlines recorded." /> : (
              <div style={{display:"grid",gap:8}}>{supplierDeadlines.map(inv => (
                <div key={inv.id} style={{padding:11,borderRadius:12,border:`1px solid ${inv.overdue ? C.danger : C.border}`,background:inv.overdue ? C.dangerSoft : C.surface}}>
                  <div style={{display:"flex",justifyContent:"space-between",gap:8,alignItems:"center"}}><b>{inv.supplier}</b><DeadlineStatus overdue={inv.overdue}/></div>
                  <div style={{fontSize:12,color:C.sub,marginTop:5}}>Invoice {inv.number} · Deadline: <b style={{color:inv.overdue?C.danger:C.ink}}>{fmtDate(inv.dueDate)}</b></div>
                  <div style={{fontFamily:MONO,fontSize:13,marginTop:6}}>Remaining: {fmtMoney(inv.t.remainingUSD,"USD")} / {fmtMoney(inv.t.remainingIQD,"IQD")}</div>
                  {inv.overdue && <div style={{fontSize:12,fontWeight:700,color:C.danger,marginTop:4}}>{inv.daysOverdue} day{inv.daysOverdue===1?"":"s"} overdue</div>}
                </div>
              ))}</div>
            )}
          </Card>

          <Card style={{ padding: 16 }}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",gap:10,marginBottom:12}}>
              <div><h3 style={{margin:0,fontSize:16}}>Customer Payment Deadlines</h3><div style={{fontSize:12,color:C.sub,marginTop:4}}>Installments that are still unpaid or partially paid.</div></div>
              <MiniStat label="Overdue" value={overdueCustomerCount} tone={overdueCustomerCount ? "danger" : "success"} />
            </div>
            {customerDeadlines.length === 0 ? <EmptyState icon={CheckCircle2} text="No customer installment deadlines recorded." /> : (
              <div style={{display:"grid",gap:8}}>{customerDeadlines.map(({phone,item,remaining,overdue,daysOverdue}) => (
                <div key={`${phone.id}-${item.no}`} style={{padding:11,borderRadius:12,border:`1px solid ${overdue ? C.danger : C.border}`,background:overdue ? C.dangerSoft : C.surface}}>
                  <div style={{display:"flex",justifyContent:"space-between",gap:8,alignItems:"center"}}><b>{phone.sale.customer}</b><DeadlineStatus overdue={overdue}/></div>
                  <div style={{fontSize:12,color:C.sub,marginTop:5}}>{phone.brand} {phone.model} · Installment {item.no}/14 · Deadline: <b style={{color:overdue?C.danger:C.ink}}>{fmtDate(item.dueDate)}</b></div>
                  <div style={{fontFamily:MONO,fontSize:13,marginTop:6}}>Remaining: {fmtMoney(remaining,phone.sale.currency)}</div>
                  {overdue && <div style={{fontSize:12,fontWeight:700,color:C.danger,marginTop:4}}>{daysOverdue} day{daysOverdue===1?"":"s"} overdue</div>}
                </div>
              ))}</div>
            )}
          </Card>
        </div>
      )}

      {tab === "activity" && (
        <Card style={{ padding: 16 }}>
          {activityLog.length === 0 ? <EmptyState icon={History} text="No activity recorded yet." /> : (
            <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
              <thead><tr>{["When", "Action", "Entity", "Details"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
              <tbody>
                {activityLog.map((a) => (
                  <tr key={a.id}>
                    <td style={tdStyle}>{fmtDateTime(a.timestamp)}</td>
                    <td style={tdStyle}><Badge tone="accent">{a.action}</Badge></td>
                    <td style={tdStyle}>{a.entity}</td>
                    <td style={tdStyle}>{a.detailText || "-"}</td>
                  </tr>
                ))}
              </tbody>
            </table></div>
          )}
        </Card>
      )}
    </div>
  );
}

function ReportTable({ rows, columns, empty }) {
  if (rows.length === 0) return <EmptyState icon={ListChecks} text={empty} />;
  return (
    <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
      <thead><tr>{columns.map((c) => <th key={c.h} style={thStyle}>{c.h}</th>)}</tr></thead>
      <tbody>
        {rows.map((r, idx) => (
          <tr key={r.id || idx}>
            {columns.map((c) => <td key={c.h} style={{ ...tdStyle, fontFamily: c.mono ? MONO : FONT }}>{c.k(r)}</td>)}
          </tr>
        ))}
      </tbody>
    </table></div>
  );
}

/* ---------------------------------- DEBIT ANALYSIS ---------------------------------- */
// Reports each supplier's debit (what they invoiced us) and how much of it we've paid
// back, side by side — plus cash purchases and combined cash+debit totals, so the
// whole purchasing picture (who we owe, who's paid off, and cash spend) is in one place.
function DebitAnalysis({ ctx }) {
  const { phones, invoices, invoiceTotals, settings } = ctx;

  const cashPhonesActive = phones.filter((p) => p.purchaseType === "cash" && p.status !== "returned");

  // One row per supplier, built up from every invoice raised in their name.
  const supplierMap = {};
  invoices.forEach((inv) => {
    const t = invoiceTotals[inv.id];
    if (!t) return;
    if (!supplierMap[inv.supplier]) {
      supplierMap[inv.supplier] = { supplier: inv.supplier, invoiceCount: 0, totalUSD: 0, totalIQD: 0, paidUSD: 0, paidIQD: 0, remainingUSD: 0, remainingIQD: 0 };
    }
    const s = supplierMap[inv.supplier];
    s.invoiceCount += 1;
    s.totalUSD += t.totalUSD; s.totalIQD += t.totalIQD;
    s.paidUSD += t.paidUSD; s.paidIQD += t.paidIQD;
    s.remainingUSD += t.remainingUSD; s.remainingIQD += t.remainingIQD;
  });
  const supplierRows = Object.values(supplierMap).sort((a, b) => b.totalUSD - a.totalUSD);

  const cashTotals = { USD: 0, IQD: 0 };
  cashPhonesActive.forEach((p) => {
    cashTotals.USD += purchaseCostInCurrency(p, "USD", invoices, settings);
    cashTotals.IQD += purchaseCostInCurrency(p, "IQD", invoices, settings);
  });

  const debitTotals = supplierRows.reduce((a, s) => ({ USD: a.USD + s.totalUSD, IQD: a.IQD + s.totalIQD }), { USD: 0, IQD: 0 });
  const debitPaidTotals = supplierRows.reduce((a, s) => ({ USD: a.USD + s.paidUSD, IQD: a.IQD + s.paidIQD }), { USD: 0, IQD: 0 });
  const debitRemainingTotals = supplierRows.reduce((a, s) => ({ USD: a.USD + s.remainingUSD, IQD: a.IQD + s.remainingIQD }), { USD: 0, IQD: 0 });

  // Cash purchases are settled the moment they're recorded, so the cash amount counts
  // as both a purchase and a payment; debit purchases only count as "paid" once money
  // has actually gone back to the supplier.
  const totalPurchases = { USD: cashTotals.USD + debitTotals.USD, IQD: cashTotals.IQD + debitTotals.IQD };
  const totalPayments = { USD: cashTotals.USD + debitPaidTotals.USD, IQD: cashTotals.IQD + debitPaidTotals.IQD };

  const Row = ({ label, usd, iqd, bold, color }) => (
    <tr style={bold ? { background: C.primarySoft } : undefined}>
      <td style={{ ...tdStyle, fontWeight: bold ? 800 : 500 }}>{label}</td>
      <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: bold ? 800 : 500, color: color || C.ink }}>{fmtMoney(usd, "USD")}</td>
      <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: bold ? 800 : 500, color: color || C.ink }}>{fmtMoney(iqd, "IQD")}</td>
    </tr>
  );

  return (
    <div>
      <SectionHeader title="Debit Analysis" sub="Each supplier's debit and what's been paid back to them, plus cash purchase totals" />

      <div style={{ display: "flex", gap: 14, marginBottom: 16, flexWrap: "wrap" }}>
        <StatCard icon={Truck} label="Total Debit (All Suppliers)" value={fmtMoney(debitTotals.USD, "USD")} sub={fmtMoney(debitTotals.IQD, "IQD")} tone="primary" />
        <StatCard icon={Wallet} label="Total Paid to Suppliers" value={fmtMoney(debitPaidTotals.USD, "USD")} sub={fmtMoney(debitPaidTotals.IQD, "IQD")} tone="success" />
        <StatCard icon={AlertTriangle} label="Remaining Supplier Debt" value={fmtMoney(debitRemainingTotals.USD, "USD")} sub={fmtMoney(debitRemainingTotals.IQD, "IQD")} tone="danger" />
        <StatCard icon={Banknote} label="Cash Purchases" value={fmtMoney(cashTotals.USD, "USD")} sub={fmtMoney(cashTotals.IQD, "IQD")} tone="gold" />
        <StatCard icon={ShoppingBag} label="Total Purchases (Cash + Debit)" value={fmtMoney(totalPurchases.USD, "USD")} sub={fmtMoney(totalPurchases.IQD, "IQD")} tone="accent" />
        <StatCard icon={DollarSign} label="Total Payments (Cash + Debit)" value={fmtMoney(totalPayments.USD, "USD")} sub={fmtMoney(totalPayments.IQD, "IQD")} tone="primary" />
      </div>

      <Card style={{ padding: 16, marginBottom: 16 }}>
        <h3 style={{ marginTop: 0, marginBottom: 12, fontSize: 15 }}>Debit by Supplier</h3>
        {supplierRows.length === 0 ? <EmptyState icon={Truck} text="No supplier debit recorded yet." /> : (
          <div style={{ overflowX: "auto" }}>
            <table style={tableStyle}>
              <thead>
                <tr>{["Supplier", "Invoices", "Debit (USD)", "Paid (USD)", "Remaining (USD)", "Debit (IQD)", "Paid (IQD)", "Remaining (IQD)"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr>
              </thead>
              <tbody>
                {supplierRows.map((s) => (
                  <tr key={s.supplier}>
                    <td style={tdStyle}><b>{s.supplier}</b></td>
                    <td style={tdStyle}>{s.invoiceCount}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(s.totalUSD, "USD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO, color: C.success }}>{fmtMoney(s.paidUSD, "USD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700, color: s.remainingUSD > 0 ? C.danger : C.success }}>{fmtMoney(s.remainingUSD, "USD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(s.totalIQD, "IQD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO, color: C.success }}>{fmtMoney(s.paidIQD, "IQD")}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700, color: s.remainingIQD > 0 ? C.danger : C.success }}>{fmtMoney(s.remainingIQD, "IQD")}</td>
                  </tr>
                ))}
                <tr style={{ background: C.primarySoft }}>
                  <td style={{ ...tdStyle, fontWeight: 800 }}>Total</td>
                  <td style={tdStyle}></td>
                  <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 800 }}>{fmtMoney(debitTotals.USD, "USD")}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 800 }}>{fmtMoney(debitPaidTotals.USD, "USD")}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 800 }}>{fmtMoney(debitRemainingTotals.USD, "USD")}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 800 }}>{fmtMoney(debitTotals.IQD, "IQD")}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 800 }}>{fmtMoney(debitPaidTotals.IQD, "IQD")}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 800 }}>{fmtMoney(debitRemainingTotals.IQD, "IQD")}</td>
                </tr>
              </tbody>
            </table>
          </div>
        )}
      </Card>

      <Card style={{ padding: 16 }}>
        <h3 style={{ marginTop: 0, marginBottom: 12, fontSize: 15 }}>Cash vs Debit — Purchases &amp; Payments</h3>
        <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
          <thead><tr>{["", "USD", "IQD"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
          <tbody>
            <Row label="Cash Purchases" usd={cashTotals.USD} iqd={cashTotals.IQD} />
            <Row label="Debit Purchases (Invoiced by Suppliers)" usd={debitTotals.USD} iqd={debitTotals.IQD} />
            <Row label="Total Purchases (Cash + Debit)" usd={totalPurchases.USD} iqd={totalPurchases.IQD} bold />
            <Row label="Cash Payments (settled at time of purchase)" usd={cashTotals.USD} iqd={cashTotals.IQD} />
            <Row label="Debit Payments (paid back to suppliers)" usd={debitPaidTotals.USD} iqd={debitPaidTotals.IQD} />
            <Row label="Total Payments (Cash + Debit)" usd={totalPayments.USD} iqd={totalPayments.IQD} bold />
          </tbody>
        </table></div>
      </Card>
    </div>
  );
}

/* ---------------------------------- BALANCE ANALYSIS ---------------------------------- */

// A single, all-in-one financial snapshot: how much is tied up in stock, how much is
// owed (both to suppliers and by customers), how much has been sold in each channel,
// and — most importantly — how much cash is actually in the owner's pocket right now.
// "Pocket balance" is split the same way every other number in this app is split:
// the cash-only cycle (cash sales minus cash purchases) versus the credit/debit cycle
// (money collected from installment customers minus money paid out to suppliers).
function BalanceAnalysis({ ctx }) {
  const { phones, invoices, customerPayments, invoiceTotals, settings } = ctx;

  const activePhones = phones.filter((p) => p.status !== "returned");
  const cashPhones = activePhones.filter((p) => p.purchaseType === "cash");
  const debitPhones = activePhones.filter((p) => p.purchaseType === "debit");
  const stockPhones = activePhones.filter((p) => p.status === "in_stock");
  const soldPhones = activePhones.filter((p) => p.status === "sold");
  const stockCashPhones = stockPhones.filter((p) => p.purchaseType === "cash");
  const stockDebitPhones = stockPhones.filter((p) => p.purchaseType === "debit");
  const cashSalePhones = soldPhones.filter((p) => (p.sale?.saleType || "cash") === "cash");
  const installmentSalePhones = soldPhones.filter((p) => p.sale?.saleType === "installment");

  const sumPurchase = (list, cur) => list.reduce((s, p) => s + purchaseCostInCurrency(p, cur, invoices, settings), 0);
  const sumSale = (list, cur) => list.reduce((s, p) => s + saleValueInCurrency(p, cur, settings), 0);
  const add = (a, b) => ({ USD: a.USD + b.USD, IQD: a.IQD + b.IQD });
  const sub = (a, b) => ({ USD: a.USD - b.USD, IQD: a.IQD - b.IQD });

  // Purchases — how much was bought with cash vs bought on supplier debit.
  const purchasedCash = { USD: sumPurchase(cashPhones, "USD"), IQD: sumPurchase(cashPhones, "IQD") };
  const purchasedDebit = { USD: sumPurchase(debitPhones, "USD"), IQD: sumPurchase(debitPhones, "IQD") };
  const totalPurchased = add(purchasedCash, purchasedDebit);

  // Stock remaining — split by how it was originally purchased.
  const stockCashValue = { USD: sumPurchase(stockCashPhones, "USD"), IQD: sumPurchase(stockCashPhones, "IQD") };
  const stockDebitValue = { USD: sumPurchase(stockDebitPhones, "USD"), IQD: sumPurchase(stockDebitPhones, "IQD") };
  const totalStockValue = add(stockCashValue, stockDebitValue);

  // Sold — split by how the customer paid.
  const soldCash = { USD: sumSale(cashSalePhones, "USD"), IQD: sumSale(cashSalePhones, "IQD") };
  const soldInstallment = { USD: sumSale(installmentSalePhones, "USD"), IQD: sumSale(installmentSalePhones, "IQD") };
  const totalSold = add(soldCash, soldInstallment);

  // Supplier side: what's still owed, and what's already been paid back.
  const supplierDebt = invoices.reduce((a, inv) => {
    const t = invoiceTotals[inv.id];
    return { USD: a.USD + (t?.remainingUSD || 0), IQD: a.IQD + (t?.remainingIQD || 0) };
  }, { USD: 0, IQD: 0 });
  const supplierPaid = invoices.reduce((a, inv) => {
    const t = invoiceTotals[inv.id];
    return { USD: a.USD + (t?.paidUSD || 0), IQD: a.IQD + (t?.paidIQD || 0) };
  }, { USD: 0, IQD: 0 });

  // Customer side: installment money already collected vs still owed to you.
  const customerReceivable = { USD: 0, IQD: 0 };
  const customerCollected = { USD: 0, IQD: 0 };
  installmentSalePhones.forEach((p) => {
    const total = Number(p.sale?.totalPrice ?? p.sale?.price) || 0;
    const cur = p.sale?.currency || "USD";
    const paid = customerPayments.filter((x) => x.phoneId === p.id).reduce((s, x) => s + (Number(x.amount) || 0), 0);
    const remaining = Math.max(0, total - paid);
    const rate = getSaleRate(p, settings);
    customerReceivable.USD += convertCurrency(remaining, cur, "USD", rate);
    customerReceivable.IQD += convertCurrency(remaining, cur, "IQD", rate);
    customerCollected.USD += convertCurrency(paid, cur, "USD", rate);
    customerCollected.IQD += convertCurrency(paid, cur, "IQD", rate);
  });

  // Pocket balance = cash actually on hand right now.
  // Cash cycle: cash collected from cash sales, minus cash spent on cash purchases.
  // Debit/credit cycle: installment money collected from customers, minus what's been paid back to suppliers.
  const pocketCash = sub(soldCash, purchasedCash);
  const pocketDebt = sub(customerCollected, supplierPaid);
  const pocketTotal = add(pocketCash, pocketDebt);

  // Money actually received in hand from sales: full amount for cash sales, plus only the
  // down payment / installment payments that have actually been recorded for installment
  // sales. If no down payment was ever recorded, that sale contributes $0 here — its full
  // value instead sits in "Still Owed to You" below, not in collected cash.
  const moneyCollected = add(soldCash, customerCollected);

  const Row = ({ label, usd, iqd, bold, color, indent }) => (
    <tr style={bold ? { background: C.primarySoft } : undefined}>
      <td style={{ ...tdStyle, fontWeight: bold ? 800 : 500, paddingLeft: indent ? 26 : undefined }}>{label}</td>
      <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: bold ? 800 : 500, color: color || C.ink }}>{fmtMoney(usd, "USD")}</td>
      <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: bold ? 800 : 500, color: color || C.ink }}>{fmtMoney(iqd, "IQD")}</td>
    </tr>
  );

  return (
    <div>
      <SectionHeader title="Balance Analysis" sub="One place for every balance: debt, stock, sales, and how much cash is really in your pocket" />

      <div style={{ display: "flex", gap: 14, marginBottom: 16, flexWrap: "wrap" }}>
        <StatCard icon={AlertTriangle} label="Total Debt (Owed to Suppliers)" value={fmtMoney(supplierDebt.USD, "USD")} sub={fmtMoney(supplierDebt.IQD, "IQD")} tone="danger" />
        <StatCard icon={DollarSign} label="Total Sold — Contract Value (Cash + Installment)" value={fmtMoney(totalSold.USD, "USD")} sub={fmtMoney(totalSold.IQD, "IQD")} tone="accent" />
        <StatCard icon={CheckCircle2} label="Money Collected From Sales (Actually Received)" value={fmtMoney(moneyCollected.USD, "USD")} sub={fmtMoney(moneyCollected.IQD, "IQD")} tone="success" />
        <StatCard icon={PackageX} label="Balance Remaining in Stock" value={fmtMoney(totalStockValue.USD, "USD")} sub={fmtMoney(totalStockValue.IQD, "IQD")} tone="gold" />
        <StatCard icon={Wallet} label="Balance in Pocket" value={fmtMoney(pocketTotal.USD, "USD")} sub={fmtMoney(pocketTotal.IQD, "IQD")} tone={pocketTotal.USD < 0 ? "danger" : "success"} />
      </div>

      <div style={{ display: "flex", gap: 14, marginBottom: 16, flexWrap: "wrap" }}>
        <StatCard icon={Banknote} label="Purchased in Cash" value={fmtMoney(purchasedCash.USD, "USD")} sub={fmtMoney(purchasedCash.IQD, "IQD")} tone="gold" />
        <StatCard icon={Truck} label="Purchased on Debit" value={fmtMoney(purchasedDebit.USD, "USD")} sub={fmtMoney(purchasedDebit.IQD, "IQD")} tone="primary" />
        <StatCard icon={Banknote} label="Stock Bought with Cash" value={fmtMoney(stockCashValue.USD, "USD")} sub={fmtMoney(stockCashValue.IQD, "IQD")} tone="gold" />
        <StatCard icon={Truck} label="Stock Bought on Debit" value={fmtMoney(stockDebitValue.USD, "USD")} sub={fmtMoney(stockDebitValue.IQD, "IQD")} tone="primary" />
        <StatCard icon={Banknote} label="Sold in Cash" value={fmtMoney(soldCash.USD, "USD")} sub={fmtMoney(soldCash.IQD, "IQD")} tone="gold" />
        <StatCard icon={CircleDollarSign} label="Sold in Installment" value={fmtMoney(soldInstallment.USD, "USD")} sub={fmtMoney(soldInstallment.IQD, "IQD")} tone="accent" />
        <StatCard icon={CheckCircle2} label="Installments Collected" value={fmtMoney(customerCollected.USD, "USD")} sub={fmtMoney(customerCollected.IQD, "IQD")} tone="success" />
        <StatCard icon={Clock} label="Installments Still Owed to You" value={fmtMoney(customerReceivable.USD, "USD")} sub={fmtMoney(customerReceivable.IQD, "IQD")} tone="warning" />
      </div>

      <Card style={{ padding: 16, marginBottom: 16 }}>
        <h3 style={{ marginTop: 0, marginBottom: 12, fontSize: 15 }}>Purchases &amp; Stock — Cash vs Debit</h3>
        <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
          <thead><tr>{["", "USD", "IQD"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
          <tbody>
            <Row label="Purchased in Cash" usd={purchasedCash.USD} iqd={purchasedCash.IQD} />
            <Row label="Purchased on Debit" usd={purchasedDebit.USD} iqd={purchasedDebit.IQD} />
            <Row label="Total Purchased (Cash + Debit)" usd={totalPurchased.USD} iqd={totalPurchased.IQD} bold />
            <Row label="Of that, still in Stock — Cash" usd={stockCashValue.USD} iqd={stockCashValue.IQD} indent />
            <Row label="Of that, still in Stock — Debit" usd={stockDebitValue.USD} iqd={stockDebitValue.IQD} indent />
            <Row label="Total Balance Remaining in Stock" usd={totalStockValue.USD} iqd={totalStockValue.IQD} bold color={C.gold} />
          </tbody>
        </table></div>
      </Card>

      <Card style={{ padding: 16, marginBottom: 16 }}>
        <h3 style={{ marginTop: 0, marginBottom: 4, fontSize: 15 }}>Sales — Contract Value vs. Money Actually Collected</h3>
        <div style={{ fontSize: 12, color: C.sub, marginBottom: 12 }}>
          Installment sales only count as "collected" what was actually recorded as a down payment or installment payment. If no down payment was recorded, the full amount stays in "Still Owed to You" — it is not treated as cash received.
        </div>
        <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
          <thead><tr>{["", "USD", "IQD"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
          <tbody>
            <Row label="Sold in Cash (paid in full)" usd={soldCash.USD} iqd={soldCash.IQD} />
            <Row label="Sold in Installment (contract value)" usd={soldInstallment.USD} iqd={soldInstallment.IQD} />
            <Row label="Total Sold — Contract Value" usd={totalSold.USD} iqd={totalSold.IQD} bold />
            <Row label="Of the Installment total, Collected so far (recorded down/installment payments)" usd={customerCollected.USD} iqd={customerCollected.IQD} indent color={C.success} />
            <Row label="Of the Installment total, Still Owed to You (no payment recorded yet)" usd={customerReceivable.USD} iqd={customerReceivable.IQD} indent color={C.danger} />
            <Row label="Money Collected From Sales (Cash sold + Installments collected)" usd={moneyCollected.USD} iqd={moneyCollected.IQD} bold color={C.success} />
          </tbody>
        </table></div>
      </Card>

      <Card style={{ padding: 16 }}>
        <h3 style={{ marginTop: 0, marginBottom: 4, fontSize: 15 }}>Balance in Pocket — Cash vs Debit</h3>
        <div style={{ fontSize: 12, color: C.sub, marginBottom: 12 }}>
          Cash in hand from cash sales minus cash purchases, plus installment money actually collected (recorded payments only) minus what's been paid back to suppliers.
        </div>
        <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
          <thead><tr>{["", "USD", "IQD"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
          <tbody>
            <Row label="Cash Sold" usd={soldCash.USD} iqd={soldCash.IQD} indent />
            <Row label="minus Cash Purchases" usd={-purchasedCash.USD} iqd={-purchasedCash.IQD} indent />
            <Row label="= Pocket Balance (Cash side)" usd={pocketCash.USD} iqd={pocketCash.IQD} bold color={pocketCash.USD < 0 ? C.danger : C.success} />
            <Row label="Installments Collected (recorded payments only)" usd={customerCollected.USD} iqd={customerCollected.IQD} indent />
            <Row label="minus Supplier Payments Made" usd={-supplierPaid.USD} iqd={-supplierPaid.IQD} indent />
            <Row label="= Pocket Balance (Debit side)" usd={pocketDebt.USD} iqd={pocketDebt.IQD} bold color={pocketDebt.USD < 0 ? C.danger : C.success} />
            <Row label="Total Balance in Pocket" usd={pocketTotal.USD} iqd={pocketTotal.IQD} bold color={pocketTotal.USD < 0 ? C.danger : C.success} />
          </tbody>
        </table></div>
      </Card>
    </div>
  );
}

/* ---------------------------------- CURRENCY P&L ---------------------------------- */

// A supplier payment settles a debt that was originally recorded at the invoice's
// exchange rate. If the rate has moved by the time cash actually changes hands, the
// real IQD cost of clearing that USD debt differs from what was budgeted. This turns
// that gap into a concrete gain or loss per payment.
function CurrencyPnL({ ctx }) {
  const { invoices, invoiceMap, payments, settings } = ctx;
  const [supplierFilter, setSupplierFilter] = useState("all");
  const [onlyDiff, setOnlyDiff] = useState(true);

  const invoiceRate = (inv) => (Number(inv?.exchangeRate) > 0 ? Number(inv.exchangeRate) : (Number(settings.exchangeRate) || 1));

  const allRows = useMemo(() => {
    return payments
      .filter((p) => invoiceMap[p.invoiceId])
      .map((p) => {
        const inv = invoiceMap[p.invoiceId];
        const purRate = invoiceRate(inv);
        const payRate = Number(p.exchangeRate) > 0 ? Number(p.exchangeRate) : purRate;
        const payCur = p.currency || inv.currency || "USD";
        const amount = Number(p.amount) || 0;
        // How much of the (USD) debt this payment actually clears, regardless of which
        // currency the cash itself was handed over in.
        const usdSettled = payCur === "USD" ? amount : amount / payRate;
        const expectedIQD = usdSettled * purRate;
        const actualIQD = usdSettled * payRate;
        const fx = expectedIQD - actualIQD; // positive = gain (paid out less IQD than budgeted)
        return {
          id: p.id, date: p.date, supplier: inv.supplier, invoiceNumber: inv.number,
          amount, currency: payCur, purRate, payRate, usdSettled, fx,
        };
      })
      .sort((a, b) => new Date(b.date) - new Date(a.date));
  }, [payments, invoiceMap, settings]);

  const suppliers = useMemo(() => Array.from(new Set(invoices.map((i) => i.supplier))).sort(), [invoices]);

  const rows = allRows
    .filter((r) => supplierFilter === "all" || r.supplier === supplierFilter)
    .filter((r) => !onlyDiff || Math.abs(r.fx) > 0.5);

  const totalGain = rows.filter((r) => r.fx > 0).reduce((s, r) => s + r.fx, 0);
  const totalLoss = rows.filter((r) => r.fx < 0).reduce((s, r) => s + Math.abs(r.fx), 0);
  const net = totalGain - totalLoss;
  const refRate = Number(settings.exchangeRate) || 1;

  const bySupplier = useMemo(() => {
    const m = {};
    rows.forEach((r) => {
      if (!m[r.supplier]) m[r.supplier] = { supplier: r.supplier, gain: 0, loss: 0, count: 0 };
      m[r.supplier].count += 1;
      if (r.fx > 0) m[r.supplier].gain += r.fx; else if (r.fx < 0) m[r.supplier].loss += Math.abs(r.fx);
    });
    return Object.values(m).sort((a, b) => (b.gain - b.loss) - (a.gain - a.loss));
  }, [rows]);

  return (
    <div>
      <SectionHeader title="Currency P&L" sub="Gain or loss from the dinar/dollar rate moving between when a phone was purchased and when the supplier was actually paid" />

      <div style={{ fontSize: 12.5, color: C.sub, marginBottom: 16, background: C.primarySoft, padding: "10px 14px", borderRadius: 10 }}>
        Each invoice locks in a purchase-time rate; each payment records the rate you actually paid at. When the rate drops before you pay, you hand over fewer dinars than budgeted — a <b style={{ color: C.success }}>gain</b>. When it rises, you pay more — a <b style={{ color: C.danger }}>loss</b>.
      </div>

      <div style={{ display: "flex", gap: 14, marginBottom: 16, flexWrap: "wrap" }}>
        <StatCard icon={TrendUp} label="Total Gain" value={fmtMoney(totalGain, "IQD")} sub={fmtMoney(totalGain / refRate, "USD") + " approx."} tone="success" />
        <StatCard icon={AlertTriangle} label="Total Loss" value={fmtMoney(totalLoss, "IQD")} sub={fmtMoney(totalLoss / refRate, "USD") + " approx."} tone="danger" />
        <StatCard icon={Scale} label="Net Currency Result" value={fmtMoney(net, "IQD")} sub={fmtMoney(net / refRate, "USD") + " approx."} tone={net >= 0 ? "success" : "danger"} />
      </div>

      <div style={{ display: "flex", gap: 8, marginBottom: 14, flexWrap: "wrap", alignItems: "center" }}>
        <FilterPill active={supplierFilter === "all"} onClick={() => setSupplierFilter("all")} label="All Suppliers" />
        {suppliers.map((s) => (
          <FilterPill key={s} active={supplierFilter === s} onClick={() => setSupplierFilter(s)} label={s} />
        ))}
        <label style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12.5, color: C.sub, marginLeft: 8, cursor: "pointer" }}>
          <input type="checkbox" checked={onlyDiff} onChange={(e) => setOnlyDiff(e.target.checked)} />
          Only show payments where the rate actually moved
        </label>
      </div>

      {bySupplier.length > 0 && (
        <Card style={{ padding: 16, marginBottom: 16 }}>
          <h3 style={{ marginTop: 0, marginBottom: 12, fontSize: 15 }}>By Supplier</h3>
          <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}><table style={tableStyle}>
            <thead><tr>{["Supplier", "Payments", "Gain (IQD)", "Loss (IQD)", "Net (IQD)"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
            <tbody>
              {bySupplier.map((s) => (
                <tr key={s.supplier}>
                  <td style={tdStyle}><b>{s.supplier}</b></td>
                  <td style={tdStyle}>{s.count}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO, color: C.success }}>{fmtMoney(s.gain, "IQD")}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO, color: C.danger }}>{fmtMoney(s.loss, "IQD")}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700, color: (s.gain - s.loss) >= 0 ? C.success : C.danger }}>{fmtMoney(s.gain - s.loss, "IQD")}</td>
                </tr>
              ))}
            </tbody>
          </table></div>
        </Card>
      )}

      <Card>
        {rows.length === 0 ? (
          <EmptyState icon={Scale} text={onlyDiff ? "No payments with a rate difference yet — record a payment with a different exchange rate than its invoice to see it here." : "No supplier payments recorded yet."} />
        ) : (
          <div style={{ overflowX: "auto" }}>
            <table style={tableStyle}>
              <thead>
                <tr>{["Date", "Supplier", "Invoice #", "Amount Settled", "Purchase Rate", "Payment Rate", "Rate Diff", "FX Result (IQD)"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr>
              </thead>
              <tbody>
                {rows.map((r) => (
                  <tr key={r.id}>
                    <td style={tdStyle}>{fmtDate(r.date)}</td>
                    <td style={tdStyle}>{r.supplier}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{r.invoiceNumber}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(r.amount, r.currency)}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{r.purRate.toLocaleString()}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{r.payRate.toLocaleString()}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO, color: r.payRate === r.purRate ? C.sub : (r.payRate < r.purRate ? C.success : C.danger) }}>
                      {r.payRate === r.purRate ? "—" : `${r.payRate > r.purRate ? "+" : ""}${(r.payRate - r.purRate).toLocaleString()}`}
                    </td>
                    <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700, color: r.fx > 0 ? C.success : r.fx < 0 ? C.danger : C.sub }}>
                      {r.fx === 0 ? "—" : `${r.fx > 0 ? "+" : "-"}${fmtMoney(Math.abs(r.fx), "IQD")}`}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </div>
  );
}

/* ---------------------------------- SETTINGS ---------------------------------- */

function NotificationsSettingsCard() {
  const api = typeof window !== "undefined" ? window.karwanNotifications : null;
  const [name, setName] = useState(api ? api.getUserName() : "");
  const [status, setStatus] = useState(api ? api.permission() : "unsupported");
  const [busy, setBusy] = useState(false);

  const saveName = () => {
    if (api) api.setUserName(name.trim());
  };

  const enable = async () => {
    if (!api) return;
    setBusy(true);
    saveName();
    try {
      const ok = await api.enablePush();
      setStatus(api.permission());
      if (!ok) alert("Notifications weren't enabled. Check your browser's site permissions and try again.");
    } finally {
      setBusy(false);
    }
  };

  return (
    <Card style={{ padding: 18, marginBottom: 16 }}>
      <h3 style={{ margin: "0 0 6px", fontSize: 14.5, fontWeight: 700 }}>Notifications</h3>
      <div style={{ color: C.sub, fontSize: 12.5, marginBottom: 12 }}>
        Get notified when someone else on this shop's account makes a change — a toast while the app is open, and a phone notification when it's closed.
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 10, alignItems: "end", maxWidth: 420 }}>
        <Field label="Your name (shown in notifications)">
          <Input value={name} onChange={(e) => setName(e.target.value)} onBlur={saveName} placeholder="e.g. Ahmed" />
        </Field>
        <Button onClick={enable} disabled={busy || status === "unsupported"}>
          {status === "granted" ? "Re-sync device" : "Enable notifications"}
        </Button>
      </div>
      <div style={{ marginTop: 10, fontSize: 12, color: status === "granted" ? C.success : status === "denied" ? C.danger : C.sub }}>
        {status === "unsupported" && "Notifications aren't supported in this browser."}
        {status === "granted" && "Notifications are on for this device."}
        {status === "denied" && "Notifications are blocked for this site — allow them in your browser's site settings."}
        {status === "default" && "Not enabled yet on this device."}
      </div>
    </Card>
  );
}

// A single tappable row in the iOS-style Settings list: a colored icon square,
// a label, optional right-aligned hint text, and a chevron.
function SettingsRow({ icon: Icon, iconColor, label, hint, onClick, last }) {
  return (
    <button
      onClick={onClick}
      style={{
        display: "flex", alignItems: "center", gap: 12, width: "100%", textAlign: "left",
        padding: "11px 12px", background: "transparent", border: "none",
        borderBottom: last ? "none" : `1px solid ${C.border}`,
        cursor: "pointer", fontFamily: FONT,
      }}
    >
      <div style={{ width: 29, height: 29, borderRadius: 8, background: iconColor, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
        <Icon size={16} color="#fff" />
      </div>
      <span style={{ flex: 1, fontSize: 14.5, color: C.ink, fontWeight: 600 }}>{label}</span>
      {hint && <span style={{ fontSize: 13, color: C.sub }}>{hint}</span>}
      <ChevronRight size={15} color={C.faint} />
    </button>
  );
}

function SettingsGroup({ children }) {
  return (
    <Card style={{ marginBottom: 20, overflow: "hidden" }}>
      {children}
    </Card>
  );
}

function SettingsSubpageHeader({ title, onBack }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
      <button onClick={onBack} aria-label="Back to Settings" style={{
        display: "flex", alignItems: "center", justifyContent: "center", width: 34, height: 34,
        borderRadius: 10, border: `1px solid ${C.border}`, background: C.surface, cursor: "pointer",
      }}>
        <ChevronLeft size={17} color={C.ink} />
      </button>
      <h2 style={{ margin: 0, fontSize: 18, fontWeight: 800, color: C.ink }}>{title}</h2>
    </div>
  );
}

function SettingsGeneralPanel({ ctx, onBack }) {
  const { settings, updateSettings, logActivity } = ctx;
  const [shopName, setShopName] = useState(settings.shopName);

  const save = () => {
    updateSettings({ ...settings, shopName });
    logActivity("Settings updated", "Settings", { detailText: "Shop name changed" });
  };

  return (
    <div>
      <SettingsSubpageHeader title="General" onBack={onBack} />
      <Card style={{ padding: 18, marginBottom: 16 }}>
        <h3 style={{ margin: "0 0 12px", fontSize: 14.5, fontWeight: 700 }}>Shop Name</h3>
        <div style={{ maxWidth: 340 }}>
          <Field label="Shop Name"><Input value={shopName} onChange={(e) => setShopName(e.target.value)} /></Field>
        </div>
        <div style={{ marginTop: 12 }}><Button onClick={save}>Save</Button></div>
      </Card>
      <Card style={{ padding: 18 }}>
        <h3 style={{ margin: "0 0 12px", fontSize: 14.5, fontWeight: 700 }}>Language</h3>
        <div style={{ maxWidth: 300 }}>
          <Select value={ctx.language} onChange={e => ctx.setLanguage(e.target.value)}>
            <option value="en">English</option>
            <option value="ku">Kurdish (Sorani) — کوردی</option>
          </Select>
        </div>
        <div style={{ marginTop: 8, color: C.sub, fontSize: 12 }}>
          Change the language here and the whole app will switch automatically.
        </div>
      </Card>
    </div>
  );
}

function SettingsAppearancePanel({ ctx, onBack }) {
  const { settings, updateSettings } = ctx;
  return (
    <div>
      <SettingsSubpageHeader title="Appearance" onBack={onBack} />
      <Card style={{ padding: 18 }}>
        <div style={{ color: C.sub, fontSize: 12.5, marginBottom: 12 }}>Choose the visual style for the whole system. The theme is saved on this device.</div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 9 }}>
          {[
            { id: "ocean", label: "Ocean Professional", a: "#173B63", b: "#0B8F88" },
            { id: "emerald", label: "Emerald", a: "#14594F", b: "#0A8F72" },
            { id: "midnight", label: "Midnight", a: "#214B78", b: "#18A69B" },
          ].map(t => (
            <button key={t.id} onClick={() => {
              localStorage.setItem("karwan-ui-theme", t.id);
              updateSettings({ ...settings, uiTheme: t.id });
              setTimeout(() => window.location.reload(), 80);
            }} style={{
              display:"flex", alignItems:"center", gap:9, padding:"9px 12px", borderRadius:11,
              border: `1px solid ${settings.uiTheme === t.id ? C.accent : C.border}`,
              background: settings.uiTheme === t.id ? C.accentSoft : C.surface, color:C.ink,
              cursor:"pointer", fontWeight:700, fontSize:12.5
            }}>
              <span style={{ display:"flex", gap:3 }}>
                <span style={{ width:12, height:12, borderRadius:4, background:t.a }} />
                <span style={{ width:12, height:12, borderRadius:4, background:t.b }} />
              </span>
              {t.label}
            </button>
          ))}
        </div>
      </Card>
    </div>
  );
}

function SettingsExchangeRatePanel({ ctx, onBack }) {
  const { settings, updateSettings, logActivity } = ctx;
  const [rate, setRate] = useState(settings.exchangeRate);

  const save = () => {
    updateSettings({ ...settings, exchangeRate: Number(rate) || settings.exchangeRate });
    logActivity("Settings updated", "Settings", { detailText: "Exchange rate changed" });
  };

  return (
    <div>
      <SettingsSubpageHeader title="Exchange Rate" onBack={onBack} />
      <Card style={{ padding: 18 }}>
        <div style={{ maxWidth: 300 }}>
          <Field label="Exchange Rate (IQD per 1 USD)"><Input type="number" value={rate} onChange={(e) => setRate(e.target.value)} /></Field>
        </div>
        <div style={{ marginTop: 12 }}><Button onClick={save}>Save</Button></div>
      </Card>
    </div>
  );
}

function SettingsAddPanel({ ctx, onBack }) {
  const { settings, updateSettings, logActivity } = ctx;

  const updateBrands = (items) => {
    const modelsByBrand = { ...(settings.modelsByBrand || {}) };
    items.forEach((b) => { if (!modelsByBrand[b]) modelsByBrand[b] = []; });
    Object.keys(modelsByBrand).forEach((b) => { if (!items.includes(b)) delete modelsByBrand[b]; });
    updateSettings({ ...settings, brands: items, modelsByBrand });
    logActivity("Settings updated", "Settings", { detailText: "Brands list changed" });
  };

  const updateModelsForBrand = (brand, items) => {
    updateSettings({ ...settings, modelsByBrand: { ...(settings.modelsByBrand || {}), [brand]: items } });
    logActivity("Settings updated", "Settings", { detailText: `Models for ${brand} changed` });
  };

  return (
    <div>
      <SettingsSubpageHeader title="Add" onBack={onBack} />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 16 }}>
        <MasterListEditor label="Brands" icon={Tag} items={settings.brands} onChange={updateBrands} />
        <ModelsByBrandEditor brands={settings.brands} modelsByBrand={settings.modelsByBrand || {}} onChange={updateModelsForBrand} />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <ContactListEditor
          label="Suppliers" icon={Truck}
          items={settings.suppliers} phones={settings.supplierPhones || {}} locations={settings.supplierLocations || {}}
          onChange={(items, phones, locations) => {
            updateSettings({ ...settings, suppliers: items, supplierPhones: phones, supplierLocations: locations });
            logActivity("Settings updated", "Settings", { detailText: "Suppliers list changed" });
          }}
        />
        <ContactListEditor
          label="Customers" icon={Users}
          items={settings.customers} phones={settings.customerPhones || {}} locations={settings.customerLocations || {}}
          onChange={(items, phones, locations) => {
            updateSettings({ ...settings, customers: items, customerPhones: phones, customerLocations: locations });
            logActivity("Settings updated", "Settings", { detailText: "Customers list changed" });
          }}
        />
        <MasterListEditor label="Payment Methods" icon={Wallet} items={settings.paymentMethods} onChange={(items) => {
          updateSettings({ ...settings, paymentMethods: items });
          logActivity("Settings updated", "Settings", { detailText: "Payment Methods list changed" });
        }} />
      </div>
    </div>
  );
}

function SettingsBackupPanel({ onBack }) {
  return (
    <div>
      <SettingsSubpageHeader title="Backup & Restore" onBack={onBack} />
      <BackupRestoreCard />
      <AutoBackupCard />
    </div>
  );
}

const BG_PRESETS = [
  { id: "none", label: "Default", value: "" },
  { id: "dawn", label: "Dawn", value: "linear-gradient(160deg,#FFD9A0 0%,#FF8FA3 45%,#7C6FF0 100%)" },
  { id: "aurora", label: "Aurora", value: "linear-gradient(160deg,#0B8F88 0%,#173B63 60%,#0E1726 100%)" },
  { id: "mist", label: "Mist", value: "linear-gradient(160deg,#DCE9E5 0%,#A9C6C0 50%,#5E756F 100%)" },
  { id: "sunset", label: "Sunset", value: "linear-gradient(160deg,#FF9A5A 0%,#D8456C 50%,#3B2C6E 100%)" },
  { id: "slate", label: "Slate", value: "linear-gradient(160deg,#3A4A63 0%,#1F2937 60%,#0E1726 100%)" },
];

function SettingsBackgroundPanel({ onBack }) {
  const fileInputRef = useRef(null);
  const [current, setCurrent] = useState(localStorage.getItem("karwan-bg") || "");
  const [busy, setBusy] = useState(false);

  const applyBackground = (value) => {
    if (value) localStorage.setItem("karwan-bg", value);
    else localStorage.removeItem("karwan-bg");
    setCurrent(value);
    setBusy(true);
    setTimeout(() => window.location.reload(), 80);
  };

  const onFileChosen = (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      applyBackground(`center / cover no-repeat url(${reader.result})`);
    };
    reader.readAsDataURL(file);
  };

  const isCustomPhoto = current && current.startsWith("center / cover");

  return (
    <div>
      <SettingsSubpageHeader title="Background" onBack={onBack} />
      <Card style={{ padding: 18, marginBottom: 16 }}>
        <div style={{ color: C.sub, fontSize: 12.5, marginBottom: 14 }}>
          Pick a wallpaper or upload your own photo, like the background behind your iPhone's home screen. Cards get a frosted-glass look on top of it.
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, marginBottom: 16 }}>
          {BG_PRESETS.map((p) => {
            const selected = !isCustomPhoto && current === p.value;
            return (
              <button
                key={p.id}
                onClick={() => applyBackground(p.value)}
                disabled={busy}
                style={{
                  border: selected ? `2px solid ${C.accent}` : `1px solid ${C.border}`,
                  borderRadius: 14, padding: 0, cursor: busy ? "default" : "pointer",
                  overflow: "hidden", background: "transparent", fontFamily: FONT,
                }}
              >
                <div style={{
                  height: 60, borderRadius: 12,
                  background: p.value || C.bg,
                  border: p.value ? "none" : `1px dashed ${C.border}`,
                }} />
                <div style={{ fontSize: 11, fontWeight: 600, color: C.ink, padding: "6px 0" }}>{p.label}</div>
              </button>
            );
          })}
        </div>
        <input ref={fileInputRef} type="file" accept="image/*" onChange={onFileChosen} style={{ display: "none" }} />
        <Button variant="subtle" icon={ImageIcon} onClick={() => fileInputRef.current?.click()} disabled={busy}>
          {isCustomPhoto ? "Change Photo" : "Choose Photo From Device"}
        </Button>
        {isCustomPhoto && (
          <div style={{ marginTop: 8, fontSize: 12, color: C.sub }}>Currently using a custom photo as the background.</div>
        )}
      </Card>
    </div>
  );
}

function SettingsPage({ ctx }) {
  const { settings } = ctx;
  const [view, setView] = useState("root");
  const goRoot = () => setView("root");

  if (view === "general") return <SettingsGeneralPanel ctx={ctx} onBack={goRoot} />;
  if (view === "appearance") return <SettingsAppearancePanel ctx={ctx} onBack={goRoot} />;
  if (view === "background") return <SettingsBackgroundPanel onBack={goRoot} />;
  if (view === "exchangeRate") return <SettingsExchangeRatePanel ctx={ctx} onBack={goRoot} />;
  if (view === "add") return <SettingsAddPanel ctx={ctx} onBack={goRoot} />;
  if (view === "backup") {
    return (
      <div>
        <SettingsSubpageHeader title="Backup & Restore" onBack={goRoot} />
        <BackupRestoreCard />
        <AutoBackupCard />
      </div>
    );
  }
  if (view === "notifications") {
    return (
      <div>
        <SettingsSubpageHeader title="Notifications" onBack={goRoot} />
        <NotificationsSettingsCard />
      </div>
    );
  }

  return (
    <div>
      <SectionHeader title="Settings" sub="Master data and system configuration" />

      <Card style={{ padding: 12, display: "flex", alignItems: "center", gap: 12, marginBottom: 20 }} onClick={() => setView("general")}>
        <div style={{ width: 52, height: 52, borderRadius: 26, background: C.accent, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, cursor: "pointer" }}>
          <Store size={24} color="#fff" />
        </div>
        <div style={{ flex: 1, minWidth: 0, cursor: "pointer" }}>
          <div style={{ fontSize: 16, fontWeight: 700, color: C.ink }}>{settings.shopName}</div>
          <div style={{ fontSize: 12.5, color: C.sub }}>Shop profile</div>
        </div>
        <ChevronRight size={16} color={C.faint} />
      </Card>

      <SettingsGroup>
        <SettingsRow icon={Bell} iconColor="#FF3B30" label="Notifications" onClick={() => setView("notifications")} />
        <SettingsRow icon={SettingsIcon} iconColor="#8E8E93" label="General" hint="Name, Language" onClick={() => setView("general")} last />
      </SettingsGroup>

      <SettingsGroup>
        <SettingsRow icon={Palette} iconColor="#AF52DE" label="Appearance" onClick={() => setView("appearance")} />
        <SettingsRow icon={ImageIcon} iconColor="#FF2D55" label="Background" onClick={() => setView("background")} />
        <SettingsRow icon={CircleDollarSign} iconColor="#34C759" label="Exchange Rate" hint={`${Number(settings.exchangeRate || 0).toLocaleString()} IQD`} onClick={() => setView("exchangeRate")} last />
      </SettingsGroup>

      <SettingsGroup>
        <SettingsRow icon={Plus} iconColor="#007AFF" label="Add" hint="Brands, Suppliers…" onClick={() => setView("add")} last />
      </SettingsGroup>

      <SettingsGroup>
        <SettingsRow icon={CloudUpload} iconColor="#FF9500" label="Backup & Restore" onClick={() => setView("backup")} last />
      </SettingsGroup>
    </div>
  );
}

function AutoBackupCard() {
  const [status, setStatus] = useState(null);
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  const refresh = async () => {
    try { setStatus(await window.autoBackup.getStatus()); } catch { setStatus(null); }
  };
  useEffect(() => { refresh(); }, []);

  const toggle = async (e) => {
    setBusy(true); setMessage(""); setError("");
    try {
      await window.autoBackup.setEnabled(e.target.checked);
      await refresh();
    } catch (err) { setError(err?.message || "Could not update auto backup."); }
    finally { setBusy(false); }
  };

  const pickFolder = async () => {
    setBusy(true); setMessage(""); setError("");
    try {
      const name = await window.autoBackup.chooseFolder();
      setMessage(`Backup folder set to "${name}". A dated backup will be written here automatically once a day.`);
      await refresh();
    } catch (err) { setError(err?.message || "Could not select a folder."); }
    finally { setBusy(false); }
  };

  const forgetFolder = async () => {
    setBusy(true); setMessage(""); setError("");
    try { await window.autoBackup.clearFolder(); await refresh(); }
    catch (err) { setError(err?.message || "Could not clear the folder."); }
    finally { setBusy(false); }
  };

  const runNow = async () => {
    setBusy(true); setMessage(""); setError("");
    try {
      const r = await window.autoBackup.runBackupNow(() => window.storage.exportBackup(STORAGE_KEYS));
      setMessage(r.wroteToFolder ? `Backup written to your chosen folder (${r.filename}).` : `Backup downloaded (${r.filename}).`);
      await refresh();
    } catch (err) { setError(err?.message || "Backup failed."); }
    finally { setBusy(false); }
  };

  if (!status) return null;
  const lastText = status.lastBackupAt ? new Date(status.lastBackupAt).toLocaleString() : "Never yet";

  return (
    <Card style={{ padding: 18, marginTop: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
        <History size={17} color={C.accent} />
        <h3 style={{ margin: 0, fontSize: 14.5, fontWeight: 700 }}>Automatic Daily Backup</h3>
      </div>
      <div style={{ color: C.sub, fontSize: 12.5, lineHeight: 1.6, marginBottom: 13 }}>
        {status.supported
          ? "On this computer's browser, pick a folder once. Every day the app writes a dated backup file straight into it — no clicks needed. Only Chrome, Edge, and Opera on a computer can save silently to a chosen folder; this is a browser restriction, not something any website can work around."
          : "This browser (and every phone browser, including Safari and Chrome on Android/iPhone) doesn't allow a website to silently save into a chosen folder — that's an OS/browser security rule. Auto backup will still run once a day automatically and download a dated file; on iPhone/Android you'll get one tap to choose where it's saved (Files, iCloud Drive, Google Drive, etc.)."}
      </div>

      <label style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12, fontSize: 13, fontWeight: 650, cursor: "pointer" }}>
        <input type="checkbox" checked={!!status.enabled} disabled={busy} onChange={toggle} style={{ width: 16, height: 16 }} />
        Enable automatic daily backup
      </label>

      {status.supported && (
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 12 }}>
          <Button size="sm" variant="subtle" onClick={pickFolder} disabled={busy}>
            {status.folderName ? "Change Backup Folder" : "Choose Backup Folder"}
          </Button>
          {status.folderName && (
            <Button size="sm" variant="subtle" onClick={forgetFolder} disabled={busy}>Forget Folder</Button>
          )}
        </div>
      )}

      <div style={{ display: "grid", gap: 4, fontSize: 12.5, color: C.sub, marginBottom: 12 }}>
        {status.supported && (
          <div>
            Folder: <b style={{ color: C.ink }}>{status.folderName || "Not set — using downloads instead"}</b>
            {status.folderName && status.permission && status.permission !== "granted" && (
              <span style={{ color: C.danger }}> — access needs to be reconfirmed. Click "Change Backup Folder" and pick it again.</span>
            )}
          </div>
        )}
        <div>Last automatic backup: <b style={{ color: C.ink }}>{lastText}</b></div>
      </div>

      <Button icon={DownloadIcon} size="sm" onClick={runNow} disabled={busy}>{busy ? "Working…" : "Run Backup Now"}</Button>

      {message && <div style={{ marginTop: 10, color: C.success, fontSize: 12.5 }}>{message}</div>}
      {error && <div style={{ marginTop: 10, color: C.danger, fontSize: 12.5 }}>{error}</div>}
    </Card>
  );
}

function BackupRestoreCard() {
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  const makeBackup = async () => {
    setBusy(true); setMessage(""); setError("");
    try {
      const backup = await window.storage.exportBackup(STORAGE_KEYS);
      const blob = new Blob([JSON.stringify(backup, null, 2)], { type: "application/json" });
      const filename = `Karwan-System-Backup-${new Date().toISOString().slice(0,10)}.json`;
      const file = new File([blob], filename, { type: "application/json" });

      // iPhone/iPad: use the native share sheet so the user can choose Files.
      if (navigator.share && navigator.canShare && navigator.canShare({ files: [file] })) {
        await navigator.share({ title: "Karwan System Backup", files: [file] });
      } else {
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url; a.download = filename;
        document.body.appendChild(a); a.click(); a.remove();
        setTimeout(() => URL.revokeObjectURL(url), 1000);
      }
      setMessage(`Backup created: ${filename}`);
    } catch (e) {
      if (e?.name !== "AbortError") setError(e?.message || "Backup failed.");
    } finally { setBusy(false); }
  };

  const restoreBackup = async (e) => {
    const file = e.target.files?.[0];
    e.target.value = "";
    if (!file) return;
    setBusy(true); setMessage(""); setError("");
    try {
      const text = await file.text();
      const backup = JSON.parse(text);
      if (!backup || backup.format !== "karwan-shop-backup" || !backup.data) throw new Error("This is not a valid Karwan System backup.");
      if (!confirm("Restore this backup? Current data on this device will be replaced by the backup.")) return;
      await window.storage.importBackup(backup, STORAGE_KEYS);
      setMessage("Backup restored successfully. Reloading the system…");
      setTimeout(() => window.location.reload(), 700);
    } catch (e) {
      setError(e?.message || "Restore failed.");
    } finally { setBusy(false); }
  };

  return (
    <Card style={{ padding: 18, marginTop: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
        <History size={17} color={C.accent} />
        <h3 style={{ margin: 0, fontSize: 14.5, fontWeight: 700 }}>Backup & Restore</h3>
      </div>
      <div style={{ color: C.sub, fontSize: 12.5, lineHeight: 1.55, marginBottom: 13 }}>
        Save a complete copy of your shop data to iPhone Files, iCloud Drive, or your PC. The backup contains your business records, not your Supabase password or secret keys.
      </div>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
        <Button icon={DownloadIcon} onClick={makeBackup} disabled={busy}>
          {busy ? "Working…" : "Export Backup"}
        </Button>
        <label style={{ display: "inline-flex" }}>
          <input type="file" accept="application/json,.json" onChange={restoreBackup} disabled={busy} style={{ display: "none" }} />
          <span style={{ display: "inline-flex", alignItems: "center", gap: 7, border: `1px solid ${C.border}`, background: C.surface, color: C.ink, borderRadius: 9, padding: "9px 12px", fontSize: 13, fontWeight: 650, cursor: busy ? "not-allowed" : "pointer", opacity: busy ? .55 : 1 }}>
            <UploadIcon size={15} /> Restore Backup
          </span>
        </label>
      </div>
      {message && <div style={{ marginTop: 10, color: C.success, fontSize: 12.5 }}>{message}</div>}
      {error && <div style={{ marginTop: 10, color: C.danger, fontSize: 12.5 }}>{error}</div>}
    </Card>
  );
}

function MasterListEditor({ label, icon: Icon, items, onChange }) {
  const [val, setVal] = useState("");
  const add = () => { if (!val.trim() || items.includes(val.trim())) return; onChange([...items, val.trim()]); setVal(""); };
  const remove = (item) => onChange(items.filter((i) => i !== item));
  return (
    <Card style={{ padding: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
        <Icon size={15} color={C.accent} />
        <h3 style={{ margin: 0, fontSize: 14, fontWeight: 700 }}>{label}</h3>
        <span style={{ marginLeft: "auto", color: C.faint, fontSize: 12 }}>{items.length}</span>
      </div>
      <div style={{ display: "flex", gap: 6, marginBottom: 10 }}>
        <Input value={val} onChange={(e) => setVal(e.target.value)} placeholder={`Add ${label.toLowerCase().replace(/s$/, "")}`} onKeyDown={(e) => e.key === "Enter" && add()} />
        <Button size="sm" icon={Plus} onClick={add}>Add</Button>
      </div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6, maxHeight: 160, overflowY: "auto" }}>
        {items.length === 0 && <span style={{ fontSize: 12.5, color: C.faint }}>None yet.</span>}
        {items.map((i) => (
          <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 5, background: ACTIVE_THEME === "midnight" ? C.primarySoft : "#EEF0F5", color: C.ink, borderRadius: 999, padding: "4px 6px 4px 10px", fontSize: 12.5 }}>
            {i}
            <button onClick={() => remove(i)} style={{ background: "none", border: "none", cursor: "pointer", display: "flex", padding: 2 }}><X size={11} color={C.sub} /></button>
          </span>
        ))}
      </div>
    </Card>
  );
}

function ContactListEditor({ label, icon: Icon, items, phones, locations, onChange }) {
  const loc = locations || {};
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [location, setLocation] = useState("");
  const [editingItem, setEditingItem] = useState(null);
  const [editPhoneVal, setEditPhoneVal] = useState("");
  const [editLocationVal, setEditLocationVal] = useState("");

  const add = () => {
    const n = name.trim();
    if (!n || items.includes(n)) return;
    const nextPhones = { ...phones };
    const nextLocations = { ...loc };
    if (phone.trim()) nextPhones[n] = phone.trim();
    if (location.trim()) nextLocations[n] = location.trim();
    onChange([...items, n], nextPhones, nextLocations);
    setName(""); setPhone(""); setLocation("");
  };
  const remove = (item) => {
    const nextPhones = { ...phones };
    const nextLocations = { ...loc };
    delete nextPhones[item];
    delete nextLocations[item];
    onChange(items.filter((i) => i !== item), nextPhones, nextLocations);
  };
  const startEditContact = (item) => { setEditingItem(item); setEditPhoneVal(phones[item] || ""); setEditLocationVal(loc[item] || ""); };
  const saveContact = () => {
    const nextPhones = { ...phones };
    const nextLocations = { ...loc };
    if (editPhoneVal.trim()) nextPhones[editingItem] = editPhoneVal.trim();
    else delete nextPhones[editingItem];
    if (editLocationVal.trim()) nextLocations[editingItem] = editLocationVal.trim();
    else delete nextLocations[editingItem];
    onChange(items, nextPhones, nextLocations);
    setEditingItem(null); setEditPhoneVal(""); setEditLocationVal("");
  };

  return (
    <Card style={{ padding: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
        <Icon size={15} color={C.accent} />
        <h3 style={{ margin: 0, fontSize: 14, fontWeight: 700 }}>{label}</h3>
        <span style={{ marginLeft: "auto", color: C.faint, fontSize: 12 }}>{items.length}</span>
      </div>
      <div style={{ display: "flex", gap: 6, marginBottom: 10, flexWrap: "wrap" }}>
        <Input value={name} onChange={(e) => setName(e.target.value)} placeholder={`Add ${label.toLowerCase().replace(/s$/, "")} name`} style={{ flex: "1 1 140px" }} onKeyDown={(e) => e.key === "Enter" && add()} />
        <Input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="Phone number (optional)" style={{ flex: "1 1 140px" }} onKeyDown={(e) => e.key === "Enter" && add()} />
        <Input value={location} onChange={(e) => setLocation(e.target.value)} placeholder="Location / residence (optional)" style={{ flex: "1 1 140px" }} onKeyDown={(e) => e.key === "Enter" && add()} />
        <Button size="sm" icon={Plus} onClick={add}>Add</Button>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 6, maxHeight: 220, overflowY: "auto" }}>
        {items.length === 0 && <span style={{ fontSize: 12.5, color: C.faint }}>None yet.</span>}
        {items.map((i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, background: ACTIVE_THEME === "midnight" ? C.primarySoft : "#EEF0F5", borderRadius: 10, padding: "6px 6px 6px 10px" }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: C.ink, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{i}</div>
              {editingItem === i ? (
                <div style={{ display: "flex", gap: 6, marginTop: 4, flexWrap: "wrap" }}>
                  <Input value={editPhoneVal} onChange={(e) => setEditPhoneVal(e.target.value)} placeholder="Phone number" style={{ fontSize: 12, flex: "1 1 110px" }} onKeyDown={(e) => e.key === "Enter" && saveContact()} />
                  <Input value={editLocationVal} onChange={(e) => setEditLocationVal(e.target.value)} placeholder="Location / residence" style={{ fontSize: 12, flex: "1 1 110px" }} onKeyDown={(e) => e.key === "Enter" && saveContact()} />
                  <Button size="sm" onClick={saveContact}>Save</Button>
                  <Button size="sm" variant="ghost" onClick={() => setEditingItem(null)}>Cancel</Button>
                </div>
              ) : (
                <div style={{ fontSize: 11.5, color: C.sub, cursor: "pointer" }} onClick={() => startEditContact(i)}>
                  <span style={{ fontFamily: MONO }}>{phones[i] || "Add phone number"}</span>
                  {" · "}
                  <span>{loc[i] || "Add location"}</span>
                </div>
              )}
            </div>
            {editingItem !== i && <button title="Edit contact" onClick={() => startEditContact(i)} style={{ background: "none", border: "none", cursor: "pointer", display: "flex", padding: 4 }}><Pencil size={12} color={C.sub} /></button>}
            <button onClick={() => remove(i)} style={{ background: "none", border: "none", cursor: "pointer", display: "flex", padding: 4 }}><X size={13} color={C.sub} /></button>
          </div>
        ))}
      </div>
    </Card>
  );
}

function ModelsByBrandEditor({ brands, modelsByBrand, onChange }) {
  const [activeBrand, setActiveBrand] = useState(brands[0] || "");
  useEffect(() => {
    if (!brands.includes(activeBrand)) setActiveBrand(brands[0] || "");
  }, [brands]);

  const [val, setVal] = useState("");
  const items = modelsByBrand[activeBrand] || [];
  const add = () => {
    if (!activeBrand || !val.trim() || items.includes(val.trim())) return;
    onChange(activeBrand, [...items, val.trim()]);
    setVal("");
  };
  const remove = (item) => onChange(activeBrand, items.filter((i) => i !== item));

  return (
    <Card style={{ padding: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
        <Smartphone size={15} color={C.accent} />
        <h3 style={{ margin: 0, fontSize: 14, fontWeight: 700 }}>Models</h3>
        <span style={{ marginLeft: "auto", color: C.faint, fontSize: 12 }}>{items.length}</span>
      </div>

      <div style={{ marginBottom: 10 }}>
        <Field label="Brand">
          <Select value={activeBrand} onChange={(e) => setActiveBrand(e.target.value)} disabled={brands.length === 0}>
            {brands.length === 0 && <option value="">Add a brand first</option>}
            {brands.map((b) => <option key={b} value={b}>{b}</option>)}
          </Select>
        </Field>
      </div>

      <div style={{ display: "flex", gap: 6, marginBottom: 10 }}>
        <Input
          value={val}
          onChange={(e) => setVal(e.target.value)}
          placeholder={activeBrand ? `Add model for ${activeBrand}` : "Add a brand first"}
          disabled={!activeBrand}
          onKeyDown={(e) => e.key === "Enter" && add()}
        />
        <Button size="sm" icon={Plus} onClick={add} disabled={!activeBrand}>Add</Button>
      </div>

      <div style={{ display: "flex", flexWrap: "wrap", gap: 6, maxHeight: 160, overflowY: "auto" }}>
        {items.length === 0 && <span style={{ fontSize: 12.5, color: C.faint }}>No models for {activeBrand || "this brand"} yet.</span>}
        {items.map((i) => (
          <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 5, background: ACTIVE_THEME === "midnight" ? C.primarySoft : "#EEF0F5", color: C.ink, borderRadius: 999, padding: "4px 6px 4px 10px", fontSize: 12.5 }}>
            {i}
            <button onClick={() => remove(i)} style={{ background: "none", border: "none", cursor: "pointer", display: "flex", padding: 2 }}><X size={11} color={C.sub} /></button>
          </span>
        ))}
      </div>
    </Card>
  );
}

/* ------------------------- Brands (per-brand totals) ------------------------- */
// Rolls the existing phone records up by brand. No data is changed here: it only
// reads phones/invoices/settings and reuses the same money helpers the rest of the
// app uses, so every figure matches Dashboard and Reports exactly.
function Brands({ ctx }) {
  const { phones, invoices, settings } = ctx;
  const [currency, setCurrency] = useState("USD");

  const brandRows = useMemo(() => {
    const configured = Array.isArray(settings.brands) ? settings.brands : [];
    const names = [];
    configured.forEach((b) => { if (b && !names.includes(b)) names.push(b); });
    phones.forEach((p) => {
      const b = (p.brand || "").trim() || "Unknown";
      if (!names.includes(b)) names.push(b);
    });

    const rows = names.map((brand) => {
      const list = phones.filter((p) => ((p.brand || "").trim() || "Unknown") === brand);
      const active = list.filter((p) => p.status !== "returned");
      const stock = active.filter((p) => p.status === "in_stock");
      const sold = active.filter((p) => p.status === "sold");
      const returned = list.filter((p) => p.status === "returned");

      let purchase = 0, stockValue = 0, sales = 0, profit = 0;
      active.forEach((p) => { purchase += purchaseCostInCurrency(p, currency, invoices, settings); });
      stock.forEach((p) => { stockValue += purchaseCostInCurrency(p, currency, invoices, settings); });
      sold.forEach((p) => {
        sales += saleValueInCurrency(p, currency, settings);
        profit += saleProfitInCurrency(p, currency, invoices, settings);
      });

      return {
        brand,
        total: list.length,
        stock: stock.length,
        sold: sold.length,
        returned: returned.length,
        purchase, stockValue, sales, profit,
        color: brandColor(brand, names),
      };
    });

    return rows.sort((a, b) => b.total - a.total || a.brand.localeCompare(b.brand));
  }, [phones, invoices, settings, currency]);

  const totals = brandRows.reduce((t, r) => ({
    total: t.total + r.total, stock: t.stock + r.stock, sold: t.sold + r.sold, returned: t.returned + r.returned,
    purchase: t.purchase + r.purchase, stockValue: t.stockValue + r.stockValue, sales: t.sales + r.sales, profit: t.profit + r.profit,
  }), { total: 0, stock: 0, sold: 0, returned: 0, purchase: 0, stockValue: 0, sales: 0, profit: 0 });

  const money = (v) => fmtMoney(v, currency);
  const pct = (n) => (totals.total ? Math.round((n / totals.total) * 100) : 0);

  const toggle = (
    <div style={{ display: "inline-flex", border: `1px solid ${C.border}`, borderRadius: 999, overflow: "hidden" }}>
      {["USD", "IQD"].map((cur) => (
        <button
          key={cur}
          onClick={() => setCurrency(cur)}
          style={{
            border: "none", cursor: "pointer", padding: "7px 16px", fontSize: 12.5, fontWeight: 700,
            background: currency === cur ? C.primary : "transparent",
            color: currency === cur ? "#fff" : C.sub,
          }}
        >{cur}</button>
      ))}
    </div>
  );

  return (
    <div>
      <SectionHeader
        title="Brands"
        sub="Total phones, stock, sales and profit for every brand you deal in."
        right={toggle}
      />

      <div style={{ display: "flex", flexWrap: "wrap", gap: 12, marginBottom: 16 }}>
        <StatCard icon={Smartphone} label="Total phones" value={totals.total} sub={`${brandRows.filter((r) => r.total > 0).length} brands with phones`} />
        <StatCard icon={PackageCheck} label="In stock" value={totals.stock} sub={`Stock value ${money(totals.stockValue)}`} tone="accent" />
        <StatCard icon={ShoppingBag} label="Sold" value={totals.sold} sub={`Sales ${money(totals.sales)}`} tone="gold" />
        <StatCard icon={TrendUp} label="Profit" value={money(totals.profit)} sub={`Purchases ${money(totals.purchase)}`} tone={totals.profit >= 0 ? "success" : "danger"} />
      </div>

      {/* Share of total phones, brand by brand */}
      <Card style={{ padding: 16, marginBottom: 16 }}>
        <div style={{ fontSize: 13.5, fontWeight: 700, color: C.ink, marginBottom: 12 }}>Share of total phones</div>
        {brandRows.filter((r) => r.total > 0).length === 0 && (
          <div style={{ fontSize: 12.5, color: C.faint }}>No phones recorded yet.</div>
        )}
        {brandRows.filter((r) => r.total > 0).map((r) => (
          <div key={r.brand} style={{ marginBottom: 10 }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, color: C.ink, marginBottom: 4 }}>
              <span style={{ fontWeight: 600 }}>
                <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 4, background: r.color, marginRight: 7 }} />
                {r.brand}
              </span>
              <span style={{ color: C.sub, fontFamily: MONO }}>{r.total} · {pct(r.total)}%</span>
            </div>
            <div style={{ height: 8, borderRadius: 999, background: C.border }}>
              <div style={{ width: `${pct(r.total)}%`, height: "100%", borderRadius: 999, background: r.color }} />
            </div>
          </div>
        ))}
      </Card>

      <Card style={{ padding: 0, overflowX: "auto" }}>
        <table style={tableStyle}>
          <thead>
            <tr>
              <th style={thStyle}>Brand</th>
              <th style={thStyle}>Total</th>
              <th style={thStyle}>In stock</th>
              <th style={thStyle}>Sold</th>
              <th style={thStyle}>Returned</th>
              <th style={thStyle}>Purchases</th>
              <th style={thStyle}>Stock value</th>
              <th style={thStyle}>Sales</th>
              <th style={thStyle}>Profit</th>
            </tr>
          </thead>
          <tbody>
            <tr style={{ background: ACTIVE_THEME === "midnight" ? C.primarySoft : "#F6F8FB" }}>
              <td style={{ ...tdStyle, fontWeight: 800 }}>All brands</td>
              <td style={{ ...tdStyle, fontWeight: 800, fontFamily: MONO }}>{totals.total}</td>
              <td style={{ ...tdStyle, fontWeight: 800, fontFamily: MONO }}>{totals.stock}</td>
              <td style={{ ...tdStyle, fontWeight: 800, fontFamily: MONO }}>{totals.sold}</td>
              <td style={{ ...tdStyle, fontWeight: 800, fontFamily: MONO }}>{totals.returned}</td>
              <td style={{ ...tdStyle, fontWeight: 800, fontFamily: MONO }}>{money(totals.purchase)}</td>
              <td style={{ ...tdStyle, fontWeight: 800, fontFamily: MONO }}>{money(totals.stockValue)}</td>
              <td style={{ ...tdStyle, fontWeight: 800, fontFamily: MONO }}>{money(totals.sales)}</td>
              <td style={{ ...tdStyle, fontWeight: 800, fontFamily: MONO, color: totals.profit >= 0 ? C.success : C.danger }}>{money(totals.profit)}</td>
            </tr>
            {brandRows.map((r) => (
              <tr key={r.brand}>
                <td style={tdStyle}>
                  <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 4, background: r.color, marginRight: 7 }} />
                  <span style={{ fontWeight: 600 }}>{r.brand}</span>
                </td>
                <td style={{ ...tdStyle, fontFamily: MONO }}>{r.total}</td>
                <td style={{ ...tdStyle, fontFamily: MONO }}>{r.stock}</td>
                <td style={{ ...tdStyle, fontFamily: MONO }}>{r.sold}</td>
                <td style={{ ...tdStyle, fontFamily: MONO, color: r.returned ? C.danger : C.faint }}>{r.returned}</td>
                <td style={{ ...tdStyle, fontFamily: MONO }}>{money(r.purchase)}</td>
                <td style={{ ...tdStyle, fontFamily: MONO }}>{money(r.stockValue)}</td>
                <td style={{ ...tdStyle, fontFamily: MONO }}>{money(r.sales)}</td>
                <td style={{ ...tdStyle, fontFamily: MONO, color: r.profit >= 0 ? C.success : C.danger }}>{money(r.profit)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <div style={{ fontSize: 11.5, color: C.faint, marginTop: 10, lineHeight: 1.6 }}>
        Returned phones are counted separately and left out of purchases, sales and profit. Every amount uses the
        exchange rate saved with that purchase or sale, so past records keep their real value.
      </div>
    </div>
  );
}

/* ------------------------- Mount ------------------------- */
const rootEl = document.getElementById("root");
ReactDOM.createRoot(rootEl).render(<App />);
