const { useState, useEffect, useMemo, useCallback } = 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 "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 "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>;
    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 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");

/* ---------------------------------- THEME ---------------------------------- */
const C = {
  bg: "#F4F5F8",
  surface: "#FFFFFF",
  ink: "#12172B",
  sub: "#65708A",
  faint: "#9AA3B8",
  border: "#E4E7EE",
  primary: "#12314F",
  primarySoft: "#E7EEF4",
  accent: "#0E8E8E",
  accentSoft: "#E1F4F3",
  success: "#177B45",
  successSoft: "#E3F5EA",
  warning: "#B4650A",
  warningSoft: "#FCEEDA",
  danger: "#B3261E",
  dangerSoft: "#FBE7E6",
  gold: "#A6790A",
  goldSoft: "#FBF1DA",
};

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

/* ---------------------------------- 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; }
}
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);
}

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

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

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

/* ---------------------------------- 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: "#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: C.surface, 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" }) {
  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>}
    </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: 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: "#fff", 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 }) {
  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={onClose}>
      <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={onClose} 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: "dashboard", label: "Dashboard", icon: LayoutDashboard },
  { id: "purchases", label: "Purchases", icon: ShoppingBag },
  { id: "sales", label: "Sales & Stock", icon: Smartphone },
  { id: "payments", label: "Supplier Payments", icon: Wallet },
  { id: "customerPayments", label: "Customer Payments", icon: CircleDollarSign },
  { id: "reports", label: "Reports & Activity", icon: FileBarChart },
  { id: "settings", label: "Settings", icon: SettingsIcon },
];

function App() {
  useFonts();
  const [loading, setLoading] = useState(true);
  const [saveError, setSaveError] = useState("");
  const [section, setSection] = useState("dashboard");
  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([]);

  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({ ...DEFAULT_SETTINGS, ...out.settings });
      setPhones(out.phones || []);
      setInvoices(out.invoices || []);
      setPayments(out.payments || []);
      setCustomerPayments(out.customerPayments || []);
      setActivityLog(out.activityLog || []);
      setLoading(false);
    })();
  }, []);

  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 updateSettings = (next) => { setSettings(next); persist("settings", next); };
  const updatePhones = (next) => { setPhones(next); persist("phones", next); };
  const updateInvoices = (next) => { setInvoices(next); persist("invoices", next); };
  const updatePayments = (next) => { setPayments(next); persist("payments", next); };
  const updateCustomerPayments = (next) => { setCustomerPayments(next); persist("customerPayments", next); };
  const updateActivity = (next) => { setActivityLog(next); persist("activityLog", next); };

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

  /* ---------- 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]);
  const invoiceTotals = useMemo(() => {
    const m = {};
    invoices.forEach((inv) => {
      const invPhones = phones.filter((p) => p.invoiceId === inv.id);
      const total = invPhones.reduce((s, p) => s + (Number(p.purchasePrice) || 0), 0);
      const paid = (paymentsByInvoice[inv.id] || []).reduce((s, p) => s + (Number(p.amount) || 0), 0);
      const remaining = Math.max(0, total - paid);
      const status = remaining <= 0 ? "Paid" : paid > 0 ? "Partially Paid" : "Unpaid";
      m[inv.id] = { total, paid, remaining, status, phoneCount: invPhones.length };
    });
    return m;
  }, [invoices, phones, paymentsByInvoice]);

  /* ---------- shared data ops passed down ---------- */
  const ctx = {
    settings, updateSettings, phones, updatePhones, invoices, updateInvoices,
    payments, updatePayments, customerPayments, updateCustomerPayments, activityLog, logActivity, invoiceMap, invoiceTotals, paymentsByInvoice,
  };

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

  return (
    <div style={{ display: "flex", minHeight: "100vh", background: C.bg, fontFamily: FONT }}>
      {/* Sidebar */}
      <div style={{ width: 232, flexShrink: 0, background: C.primary, color: "#fff", display: "flex", flexDirection: "column", padding: "20px 14px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "0 8px 20px", borderBottom: "1px solid rgba(255,255,255,0.12)", marginBottom: 14 }}>
          <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: 14.5, lineHeight: 1.2 }}>{settings.shopName}</div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
          {SECTIONS.map((s) => {
            const active = section === s.id;
            return (
              <button key={s.id} onClick={() => setSection(s.id)} style={{
                display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderRadius: 9,
                background: active ? "rgba(255,255,255,0.14)" : "transparent", border: "none", color: "#fff",
                fontFamily: FONT, fontSize: 13.5, fontWeight: active ? 700 : 500, cursor: "pointer", textAlign: "left",
              }}>
                <s.icon size={16} style={{ opacity: active ? 1 : 0.75 }} />
                {s.label}
              </button>
            );
          })}
        </div>
        <div style={{ marginTop: "auto", padding: "10px 12px", fontSize: 11.5, color: "rgba(255,255,255,0.55)" }}>
          Exchange rate: 1 USD = {settings.exchangeRate.toLocaleString()} IQD
        </div>
      </div>

      {/* Main */}
      <div style={{ flex: 1, minWidth: 0, padding: "22px 26px 60px" }}>
        {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 === "dashboard" && <Dashboard ctx={ctx} />}
        {section === "purchases" && <Purchases ctx={ctx} />}
        {section === "sales" && <SalesStock ctx={ctx} />}
        {section === "payments" && <SupplierPayments ctx={ctx} />}
        {section === "customerPayments" && <CustomerPayments ctx={ctx} />}
        {section === "reports" && <Reports ctx={ctx} />}
        {section === "settings" && <SettingsPage ctx={ctx} />}
      </div>
    </div>
  );
}

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

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 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 invoiceTotalsByCurrency = { USD: 0, IQD: 0 };
  const paidByCurrency = { USD: 0, IQD: 0 };
  invoices.forEach((inv) => {
    const t = invoiceTotals[inv.id];
    invoiceTotalsByCurrency[inv.currency] = (invoiceTotalsByCurrency[inv.currency] || 0) + t.total;
    paidByCurrency[inv.currency] = (paidByCurrency[inv.currency] || 0) + t.paid;
  });
  const debtByCurrency = {
    USD: Math.max(0, (invoiceTotalsByCurrency.USD || 0) - (paidByCurrency.USD || 0)),
    IQD: Math.max(0, (invoiceTotalsByCurrency.IQD || 0) - (paidByCurrency.IQD || 0)),
  };

  const cashPurchaseTotals = { USD: 0, IQD: 0 };
  cashPhones.forEach((p) => { cashPurchaseTotals[p.purchaseCurrency] = (cashPurchaseTotals[p.purchaseCurrency] || 0) + (Number(p.purchasePrice) || 0); });

  const salesTotals = { USD: 0, IQD: 0 };
  const profitTotals = { USD: 0, IQD: 0 };
  soldPhones.forEach((p) => {
    const cur = p.sale.currency || "USD";
    salesTotals[cur] = (salesTotals[cur] || 0) + (Number(p.sale.totalPrice ?? p.sale.price) || 0);
    profitTotals[cur] = (profitTotals[cur] || 0) + saleProfit(p, 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);

  return (
    <div>
      <SectionHeader title="Dashboard" sub="Live overview of purchases, stock, debts and sales" />

      <div style={{ display: "flex", flexWrap: "wrap", gap: 14, marginBottom: 16 }}>
        <StatCard icon={ShoppingBag} label="Total Phones Purchased" value={phones.length} sub={`${debitPhones.length} on debit · ${cashPhones.length} cash`} tone="primary" />
        <StatCard icon={PackageCheck} label="Total Sold" value={soldPhones.length} tone="accent" />
        <StatCard icon={PackageX} label="Remaining in Stock" value={stockPhones.length} sub={`${debitStock} debit · ${cashStock} cash`} tone="gold" />
        <StatCard icon={CircleDollarSign} label="Est. Stock Value" value={"~$" + stockValueUSD.toLocaleString(undefined, { maximumFractionDigits: 0 })} sub="converted at current rate" tone="success" />
      </div>

      <div style={{ display: "flex", flexWrap: "wrap", gap: 14, marginBottom: 22 }}>
        <StatCard icon={Truck} label="Supplier Invoice Total" value={fmtMoney(invoiceTotalsByCurrency.USD, "USD")} sub={fmtMoney(invoiceTotalsByCurrency.IQD, "IQD")} tone="primary" />
        <StatCard icon={CheckCircle2} label="Supplier Payments Made" value={fmtMoney(paidByCurrency.USD, "USD")} sub={fmtMoney(paidByCurrency.IQD, "IQD")} tone="success" />
        <StatCard icon={AlertTriangle} label="Supplier Debt Remaining" value={fmtMoney(debtByCurrency.USD, "USD")} sub={fmtMoney(debtByCurrency.IQD, "IQD")} tone="danger" />
        <StatCard icon={Banknote} label="Cash Purchases" value={fmtMoney(cashPurchaseTotals.USD, "USD")} sub={fmtMoney(cashPurchaseTotals.IQD, "IQD")} tone="gold" />
        <StatCard icon={DollarSign} label="Total Sales" value={fmtMoney(salesTotals.USD, "USD")} sub={fmtMoney(salesTotals.IQD, "IQD")} tone="accent" />
        <StatCard icon={CircleDollarSign} label="Total Profit" value={fmtMoney(profitTotals.USD, "USD")} sub={fmtMoney(profitTotals.IQD, "IQD")} tone="success" />
      </div>

      <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." /> : (
            <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.total, inv.currency)}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(t.paid, inv.currency)}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700, color: C.danger }}>{fmtMoney(t.remaining, inv.currency)}</td>
                    <td style={tdStyle}><StatusBadge status={t.status} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </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} sold={debitPhones.length - debitStock} remaining={debitStock} />
          <StockSourceRow label="Cash Purchases" purchased={cashPhones.length} sold={cashPhones.length - cashStock} remaining={cashStock} />
          <StockSourceRow label="Overall" purchased={phones.length} sold={soldPhones.length} remaining={stockPhones.length} bold />
        </Card>
        <Card style={{ padding: 18 }}>
          <h3 style={{ margin: "0 0 10px", fontSize: 14.5, fontWeight: 700 }}>Currency Snapshot</h3>
          <CurrencyRow label="Supplier debt" usd={debtByCurrency.USD} iqd={debtByCurrency.IQD} tone="danger" />
          <CurrencyRow label="Cash purchases" usd={cashPurchaseTotals.USD} iqd={cashPurchaseTotals.IQD} tone="gold" />
          <CurrencyRow label="Sales" usd={salesTotals.USD} iqd={salesTotals.IQD} tone="success" />
        </Card>
      </div>
    </div>
  );
}

function StockSourceRow({ label, purchased, 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 }}>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, tone }) {
  const color = { danger: C.danger, gold: C.gold, success: C.success }[tone];
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "9px 0", borderBottom: `1px solid ${C.border}` }}>
      <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>
  );
}

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 = {};

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

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, date: data.date, 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>
          <table style={tableStyle}>
            <thead><tr>{["Invoice #", "Supplier", "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}</td>
                    <td style={tdStyle}>{fmtDate(inv.date)}</td>
                    <td style={tdStyle}>{t.phoneCount}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(t.total, inv.currency)}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(t.paid, inv.currency)}</td>
                    <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700 }}>{fmtMoney(t.remaining, inv.currency)}</td>
                    <td style={tdStyle}><StatusBadge status={t.status} /></td>
                    <td style={tdStyle}><ChevronRight size={15} color={C.faint} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </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 }) {
  const [number, setNumber] = useState("INV-" + String(invoices.length + 1).padStart(4, "0"));
  const [supplier, setSupplier] = useState(settings.suppliers[0] || "");
  const [date, setDate] = useState(todayDate());
  const [currency, setCurrency] = useState("USD");
  const [exchangeRate, setExchangeRate] = useState(settings.exchangeRate || 1460);
  const [notes, setNotes] = useState("");
  return (
    <Modal title="New Supplier Invoice" onClose={onClose}>
      <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) => setSupplier(e.target.value)}>
            {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="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}>Cancel</Button>
        <Button disabled={!supplier || !number} onClick={() => onCreate({ number, supplier, date, currency, exchangeRate, notes })}>Create Invoice</Button>
      </div>
    </Modal>
  );
}

function InvoiceDetailModal({ ctx, invoiceId, onClose }) {
  const { invoices, updateInvoices, phones, updatePhones, payments, updatePayments, logActivity, invoiceTotals, settings } = ctx;
  const inv = invoices.find((i) => i.id === invoiceId);
  const [showAddPhone, setShowAddPhone] = useState(false);
  const [showPay, setShowPay] = 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 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?")) return;
    updatePhones(phones.filter((x) => x.id !== phoneId));
    logActivity("Purchase deleted", "Purchases", { detailText: `${p.brand} ${p.model} (IMEI ${p.imei})` });
  };
  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 removePayment = (paymentId) => {
    if (!confirm("Delete this payment record?")) return;
    const p = payments.find((x) => x.id === paymentId);
    updatePayments(payments.filter((x) => x.id !== paymentId));
    logActivity("Payment deleted", "Supplier Payments", { detailText: p ? `${fmtMoney(p.amount, p.currency)} from ${inv.number}` : inv.number });
  };

  return (
    <Modal title={`Invoice ${inv.number} — ${inv.supplier}`} onClose={onClose} width={760}>
      <div style={{ display: "flex", gap: 14, flexWrap: "wrap", marginBottom: 16 }}>
        <MiniStat label="Invoice Total" value={fmtMoney(t.total, inv.currency)} />
        <MiniStat label="Paid" value={fmtMoney(t.paid, inv.currency)} tone="success" />
        <MiniStat label="Remaining" value={fmtMoney(t.remaining, inv.currency)} tone="danger" />
        <MiniStat label="Invoice Exchange Rate" value={`1 USD = ${(Number(inv.exchangeRate) || Number(settings.exchangeRate) || 1).toLocaleString()} IQD`} />
        <div style={{ display: "flex", alignItems: "center" }}><StatusBadge status={t.status} /></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>
        <Button size="sm" icon={Plus} variant="subtle" onClick={() => setShowAddPhone(true)}>Add Phone</Button>
      </div>
      {invPhones.length === 0 ? <EmptyState icon={Smartphone} text="No phones added to this invoice yet." /> : (
        <table style={tableStyle}>
          <thead><tr>{["IMEI", "Brand / Model", "Storage", "Color", "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}>{p.storage || "-"}</td>
                <td style={tdStyle}>{p.color || "-"}</td>
                <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(p.purchasePrice, inv.currency)}</td>
                <td style={tdStyle}>{p.status === "sold" ? <Badge tone="sub">Sold</Badge> : <Badge tone="accent">In Stock</Badge>}</td>
                <td style={tdStyle}><button onClick={() => removePhone(p.id)} style={iconBtn}><Trash2 size={14} color={C.danger} /></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      )}

      <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." /> : (
        <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}><button onClick={() => removePayment(p.id)} style={iconBtn}><Trash2 size={14} color={C.danger} /></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      )}

      {showAddPhone && <AddPhoneModal settings={settings} currency={inv.currency} exchangeRate={inv.exchangeRate || settings.exchangeRate} lockCurrency onClose={() => setShowAddPhone(false)} onAdd={addPhone} />}
      {showPay && <AddPaymentModal settings={settings} currency={inv.currency} remaining={t.remaining} onClose={() => setShowPay(false)} onAdd={addPayment} />}
    </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 }) {
  const [imei, setImei] = useState("");
  const [brand, setBrand] = useState(settings.brands[0] || "");
  const [model, setModel] = useState(settings.models[0] || "");
  const [storage, setStorage] = useState("");
  const [color, setColor] = useState("");
  const [price, setPrice] = useState("");
  const [cur, setCur] = useState(currency || "USD");
  const [rate, setRate] = useState(exchangeRate || settings.exchangeRate || 1460);
  const [date, setDate] = useState(todayDate());
  const [notes, setNotes] = useState("");

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

  return (
    <Modal title="Add Phone" onClose={onClose}>
      <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) => setBrand(e.target.value)}>{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)}>{settings.models.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="Color (optional)"><Input value={color} onChange={(e) => setColor(e.target.value)} placeholder="e.g. Midnight" /></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)} disabled={lockCurrency}>
            <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)} disabled={lockCurrency && exchangeRate != null} />
        </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}>Cancel</Button>
        <Button disabled={!imei || !brand || !model || !price} onClick={submit}>Add Phone</Button>
      </div>
    </Modal>
  );
}

function AddPaymentModal({ settings, currency, remaining, onClose, onAdd }) {
  const [amount, setAmount] = useState(remaining || "");
  const [date, setDate] = useState(todayDate());
  const [method, setMethod] = useState(settings.paymentMethods[0] || "Cash");
  const [notes, setNotes] = useState("");
  const submit = () => { if (!amount) return; onAdd({ amount: Number(amount), currency, date, method, notes }); };
  return (
    <Modal title="Record Supplier Payment" onClose={onClose}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <Field label={`Amount (${currency}) · remaining ${fmtMoney(remaining, currency)}`}><Input type="number" value={amount} onChange={(e) => setAmount(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}>Cancel</Button>
        <Button disabled={!amount} onClick={submit}>Record Payment</Button>
      </div>
    </Modal>
  );
}

function CashPurchases({ ctx }) {
  const { phones, updatePhones, settings, logActivity } = ctx;
  const [showAdd, setShowAdd] = useState(false);
  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())
  ).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 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?")) return;
    updatePhones(phones.filter((x) => x.id !== id));
    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" 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>
          <table style={tableStyle}>
            <thead><tr>{["IMEI", "Brand / Model", "Storage", "Color", "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}>{p.storage || "-"}</td>
                  <td style={tdStyle}>{p.color || "-"}</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> : <Badge tone="accent">In Stock</Badge>}</td>
                  <td style={tdStyle}><button onClick={() => removePhone(p.id)} style={iconBtn}><Trash2 size={14} color={C.danger} /></button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}
      {showAdd && <AddPhoneModal settings={settings} currency="USD" exchangeRate={settings.exchangeRate} onClose={() => setShowAdd(false)} onAdd={addPhone} cashMode />}
    </div>
  );
}

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

function SalesStock({ ctx }) {
  const { phones, updatePhones, settings, logActivity, customerPayments, updateCustomerPayments } = ctx;
  const [filter, setFilter] = useState("in_stock");
  const [saleTab, setSaleTab] = useState("cash");
  const [q, setQ] = useState("");
  const [sellPhone, setSellPhone] = useState(null);
  const [editSale, setEditSale] = useState(null);

  const list = phones.filter((p) => filter === "all" || p.status === filter)
    .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()))
    .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 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="Sales & Stock" sub="Sell by Cash or Installment — every phone remains traceable by IMEI" />
      <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>

      <Card style={{ padding: 14, marginBottom: 14 }}>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
          <FilterPill active={filter === "in_stock"} onClick={() => setFilter("in_stock")} label="In Stock" />
          <FilterPill active={filter === "sold"} onClick={() => setFilter("sold")} label="Sold" />
          <FilterPill active={filter === "all"} onClick={() => setFilter("all")} label="All" />
          <div style={{ flex: 1 }} />
          <FilterPill active={saleTab === "cash"} onClick={() => setSaleTab("cash")} label="Cash Sales" />
          <FilterPill active={saleTab === "installment"} onClick={() => setSaleTab("installment")} label="Installment Sales" />
        </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." /> : (
            <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}>{p.brand} {p.model} {p.storage ? `· ${p.storage}` : ""}</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}><Button size="sm" variant="subtle" onClick={() => setSellPhone(p)}>Sell</Button></td>
                </tr>
              ))}</tbody>
            </table>
          )}
        </Card>
      ) : (
        <Card>
          {shownSales.length === 0 ? <EmptyState icon={saleTab === "cash" ? Banknote : Clock} text={`No ${saleTab} sales yet.`} /> : (
            <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}</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>
          )}
        </Card>
      )}

      {sellPhone && <SaleModal phone={sellPhone} settings={settings} onClose={()=>setSellPhone(null)} onSave={(data)=>recordSale(sellPhone.id,data)} />}
      {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 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 : "#fff", color: active ? "#fff" : C.ink, fontFamily: FONT,
      fontSize: 12.5, fontWeight: 600, cursor: "pointer",
    }}>{label}</button>
  );
}

function SaleModal({ phone, settings, onClose, onSave, editing, addPayment, customerPayments = [], updateCustomerPayments }) {
  const s = phone.sale || {};
  const [customer, setCustomer] = useState(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 [downPayment, setDownPayment] = useState(s.downPayment ?? (s.paymentType === "Cash" ? s.price : "") ?? "");
  const [months, setMonths] = useState(s.installmentMonths || 12);
  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;
    onSave({
      customer, date, totalPrice: total, price: total, currency, saleType,
      downPayment: saleType === "installment" ? Number(downPayment || 0) : total,
      installmentMonths: saleType === "installment" ? Number(months) : 0,
      paymentMethod, notes
    });
  };

  const addInstallmentPayment = () => {
    if (!updateCustomerPayments) return;
    const remaining = Math.max(0,total-existingPaid);
    const amount = Number(document.getElementById("new-customer-payment")?.value || 0);
    const pdate = document.getElementById("new-customer-payment-date")?.value || todayDate();
    if (!amount || amount > remaining) return;
    const method = document.getElementById("new-customer-payment-method")?.value || settings.paymentMethods[0];
    updateCustomerPayments([{id:uid(),phoneId:phone.id,customer:customer,date:pdate,amount,currency,method,notes:"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> · 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 id="new-customer-payment" type="number" min="0" /></Field>
      <Field label="Payment Date"><Input id="new-customer-payment-date" type="date" defaultValue={todayDate()} /></Field>
      <Field label="Payment Method"><Select id="new-customer-payment-method">{settings.paymentMethods.map(m=><option key={m}>{m}</option>)}</Select></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 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=>setCustomer(e.target.value)} /><datalist id="customers-list">{settings.customers.map(c=><option key={c} value={c}/>)}</datalist></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>
        {saleType==="installment" && <>
          <Field label="Down Payment"><Input type="number" min="0" value={downPayment} onChange={e=>setDownPayment(e.target.value)} /></Field>
          <Field label="Installment Duration"><Select value={months} onChange={e=>setMonths(e.target.value)}>{[3,6,9,12,18,24].map(m=><option key={m} value={m}>{m} months</option>)}</Select></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}}>Suggested monthly amount: {fmtMoney(Math.max(0,total-(Number(downPayment)||0))/Number(months||1),currency)}</div>
      </div>}
      <div style={{display:"flex",justifyContent:"flex-end",gap:8,marginTop:18}}><Button variant="ghost" onClick={onClose}>Cancel</Button><Button disabled={!customer || !price} onClick={submit}>{editing ? "Save Changes" : "Confirm Sale"}</Button></div>
    </Modal>
  );
}

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

function CustomerPayments({ ctx }) {
  const { phones, customerPayments, updateCustomerPayments, settings, logActivity } = ctx;
  const sold = phones.filter(p => p.status === "sold" && p.sale?.saleType === "installment");
  const [payFor, setPayFor] = useState(null);
  const [filter, setFilter] = useState("");
  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 addPayment = (p, amount, date, method, notes) => {
    const t = totals(p);
    if (!amount || amount > t.remaining) return;
    updateCustomerPayments([{id:uid(),phoneId:p.id,customer:p.sale.customer,date,amount:Number(amount),currency:p.sale.currency,method,notes},...customerPayments]);
    logActivity("Customer payment", "Installments", {detailText:`${p.sale.customer} · IMEI ${p.imei} · ${fmtMoney(amount,p.sale.currency)}`});
    setPayFor(null);
  };

  return <div>
    <SectionHeader title="Customer Payments" sub="Track installment payments, paid totals and remaining balances" />
    <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."/> :
      <table style={tableStyle}><thead><tr>{["Customer","IMEI","Phone","Total","Paid","Remaining","Months","Action"].map(h=><th key={h} style={thStyle}>{h}</th>)}</tr></thead>
      <tbody>{rows.map(p=>{const t=totals(p);return <tr key={p.id}>
        <td style={tdStyle}>{p.sale.customer}</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}>{p.sale.installmentMonths}</td><td style={tdStyle}><Button size="sm" variant="subtle" onClick={()=>setPayFor(p)} disabled={!t.remaining}>Add Payment</Button></td>
      </tr>})}</tbody></table>}
    </Card>
    {payFor && <CustomerPaymentModal phone={payFor} settings={settings} onClose={()=>setPayFor(null)} onSave={addPayment} customerPayments={customerPayments}/>}
  </div>;
}

function CustomerPaymentModal({phone,settings,onClose,onSave,customerPayments}) {
  const total=Number(phone.sale.totalPrice ?? phone.sale.price)||0;
  const paid=customerPayments.filter(x=>x.phoneId===phone.id).reduce((s,x)=>s+(Number(x.amount)||0),0);
  const remaining=Math.max(0,total-paid);
  const [amount,setAmount]=useState("");
  const [date,setDate]=useState(todayDate());
  const [method,setMethod]=useState(settings.paymentMethods[0]||"Cash");
  const [notes,setNotes]=useState("");
  return <Modal title={`Payment — ${phone.sale.customer}`} onClose={onClose}>
    <div style={{marginBottom:14}}>Total: <b>{fmtMoney(total,phone.sale.currency)}</b> · Paid: <b>{fmtMoney(paid,phone.sale.currency)}</b> · Remaining: <b style={{color:C.danger}}>{fmtMoney(remaining,phone.sale.currency)}</b></div>
    <Field label="Payment Amount"><Input type="number" min="0" max={remaining} 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",justifyContent:"flex-end",gap:8,marginTop:18}}><Button variant="ghost" onClick={onClose}>Cancel</Button><Button disabled={!amount || Number(amount)<=0 || Number(amount)>remaining} onClick={()=>onSave(Number(amount),date,method,notes)}>Record Payment</Button></div>
  </Modal>;
}

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

function SupplierPayments({ ctx }) {
  const { invoices, invoiceTotals, payments, settings } = ctx;
  const [payFor, setPayFor] = useState(null);
  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" />
      <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>
          <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.total, inv.currency)}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO }}>{fmtMoney(t.paid, inv.currency)}</td>
                  <td style={{ ...tdStyle, fontFamily: MONO, fontWeight: 700 }}>{fmtMoney(t.remaining, inv.currency)}</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>}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}
      {payFor && (
        <InvoiceDetailModal ctx={ctx} invoiceId={payFor.id} onClose={() => setPayFor(null)} />
      )}
    </div>
  );
}

/* ---------------------------------- REPORTS ---------------------------------- */

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

  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 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][inv.currency].total += t.total;
    supplierBalances[inv.supplier][inv.currency].paid += t.paid;
  });

  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: "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 Purchases" value={phones.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: "Price", k: (p) => fmtMoney(p.purchasePrice, p.purchaseCurrency), 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", k: (p) => fmtMoney(p.sale.totalPrice ?? p.sale.price, p.sale.currency), mono: true },
            { h: "Cost", k: (p) => fmtMoney(purchaseCostInCurrency(p, p.sale.currency, invoices, ctx.settings), p.sale.currency), mono: true },
            { h: "Profit", 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: "Cost", k: (p) => fmtMoney(p.purchasePrice, p.purchaseCurrency), 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].total, i.currency), mono: true },
            { h: "Paid", k: (i) => fmtMoney(invoiceTotals[i.id].paid, i.currency), mono: true },
            { h: "Remaining", k: (i) => fmtMoney(invoiceTotals[i.id].remaining, i.currency), mono: true },
            { 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." /> : (
            <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>
          )}
        </Card>
      )}

      {tab === "activity" && (
        <Card style={{ padding: 16 }}>
          {activityLog.length === 0 ? <EmptyState icon={History} text="No activity recorded yet." /> : (
            <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>
          )}
        </Card>
      )}
    </div>
  );
}

function ReportTable({ rows, columns, empty }) {
  if (rows.length === 0) return <EmptyState icon={ListChecks} text={empty} />;
  return (
    <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>
  );
}

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

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

  const saveShopInfo = () => {
    updateSettings({ ...settings, shopName, exchangeRate: Number(rate) || settings.exchangeRate });
    logActivity("Settings updated", "Settings", { detailText: "Shop info / exchange rate" });
  };

  const listConfigs = [
    { key: "brands", label: "Brands", icon: Tag },
    { key: "models", label: "Models", icon: Smartphone },
    { key: "suppliers", label: "Suppliers", icon: Truck },
    { key: "customers", label: "Customers", icon: Users },
    { key: "paymentMethods", label: "Payment Methods", icon: Wallet },
  ];

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

      <Card style={{ padding: 18, marginBottom: 16 }}>
        <h3 style={{ margin: "0 0 12px", fontSize: 14.5, fontWeight: 700 }}>Shop Information</h3>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, maxWidth: 560 }}>
          <Field label="Shop Name"><Input value={shopName} onChange={(e) => setShopName(e.target.value)} /></Field>
          <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={saveShopInfo}>Save</Button></div>
      </Card>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        {listConfigs.map((lc) => (
          <MasterListEditor key={lc.key} label={lc.label} icon={lc.icon} items={settings[lc.key]} onChange={(items) => {
            updateSettings({ ...settings, [lc.key]: items });
            logActivity("Settings updated", "Settings", { detailText: `${lc.label} list changed` });
          }} />
        ))}
      </div>
    </div>
  );
}

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: "#EEF0F5", 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>
  );
}

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