/* ========== Shared components, hooks, icons ========== */
const { useState, useEffect, useMemo, useRef, useCallback } = React;
const { fmtMoney, fmtDate, fmtDateShort, fmtDateTime, relativeTime, uid } = window.PVUtil;

/** Subscribe to PVStore changes and re-render. */
function useStore() {
  const [state, setState] = useState(window.PVStore.state);
  useEffect(() => window.PVStore.subscribe(setState), []);
  return state;
}

/* ========== Icons (Lucide-style strokes) ========== */
const Icon = ({ name, size = 16, stroke = 2, color = 'currentColor', style }) => {
  const paths = ICONS[name];
  if (!paths) return null;
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke={color}
      strokeWidth={stroke}
      strokeLinecap="round"
      strokeLinejoin="round"
      style={style}
      aria-hidden="true"
    >
      {paths}
    </svg>
  );
};

const ICONS = {
  search:        <React.Fragment><circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" /></React.Fragment>,
  dashboard:     <React.Fragment><rect x="3" y="3" width="7" height="9" rx="1"/><rect x="14" y="3" width="7" height="5" rx="1"/><rect x="14" y="12" width="7" height="9" rx="1"/><rect x="3" y="16" width="7" height="5" rx="1"/></React.Fragment>,
  orders:        <React.Fragment><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 10h18"/><path d="M9 14h6"/><path d="M9 17h3"/></React.Fragment>,
  customers:     <React.Fragment><circle cx="9" cy="8" r="3.5"/><path d="M2.5 19a6.5 6.5 0 0 1 13 0"/><circle cx="17" cy="8" r="2.5"/><path d="M20 18.5a4 4 0 0 0-3.5-3.4"/></React.Fragment>,
  invoice:       <React.Fragment><path d="M6 2h9l4 4v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z"/><path d="M14 2v5h5"/><path d="M9 13h6"/><path d="M9 17h4"/></React.Fragment>,
  finance:       <React.Fragment><path d="M3 17V7"/><path d="M3 17h18"/><path d="M7 14V10"/><path d="M11 14V8"/><path d="M15 14V11"/><path d="M19 14V9"/></React.Fragment>,
  templates:     <React.Fragment><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18"/><path d="M9 9v12"/></React.Fragment>,
  settings:      <React.Fragment><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 0 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 0 1 0-4h.1A1.7 1.7 0 0 0 4.6 9a1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 0 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9c.3.4.8.7 1.4.7H21a2 2 0 0 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></React.Fragment>,
  plus:          <React.Fragment><path d="M12 5v14"/><path d="M5 12h14"/></React.Fragment>,
  close:         <React.Fragment><path d="M18 6 6 18"/><path d="m6 6 12 12"/></React.Fragment>,
  check:         <path d="M5 12l5 5L20 7" />,
  arrowLeft:     <path d="m15 18-6-6 6-6"/>,
  arrowRight:    <path d="m9 18 6-6-6-6"/>,
  edit:          <React.Fragment><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 1 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></React.Fragment>,
  trash:         <React.Fragment><path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="M10 11v6"/><path d="M14 11v6"/></React.Fragment>,
  upload:        <React.Fragment><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m17 8-5-5-5 5"/><path d="M12 3v12"/></React.Fragment>,
  download:      <React.Fragment><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/></React.Fragment>,
  file:          <React.Fragment><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><path d="M14 2v6h6"/></React.Fragment>,
  image:         <React.Fragment><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/></React.Fragment>,
  print:         <React.Fragment><path d="M6 9V2h12v7"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></React.Fragment>,
  eye:           <React.Fragment><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></React.Fragment>,
  more:          <React.Fragment><circle cx="5" cy="12" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/></React.Fragment>,
  phone:         <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.8 12.8 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.9a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.8 12.8 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/>,
  mail:          <React.Fragment><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 6-10 7L2 6"/></React.Fragment>,
  map:           <React.Fragment><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></React.Fragment>,
  calendar:      <React.Fragment><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4"/><path d="M8 2v4"/><path d="M3 10h18"/></React.Fragment>,
  clock:         <React.Fragment><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></React.Fragment>,
  passport:      <React.Fragment><rect x="4" y="2" width="16" height="20" rx="2"/><circle cx="12" cy="10" r="3"/><path d="M8 18h8"/></React.Fragment>,
  receipt:       <React.Fragment><path d="M4 2v20l3-2 3 2 3-2 3 2 3-2V2l-3 2-3-2-3 2-3-2z"/><path d="M8 8h8"/><path d="M8 12h8"/><path d="M8 16h5"/></React.Fragment>,
  trending:      <React.Fragment><path d="m22 7-9.5 9.5-5-5L1 18"/><path d="M16 7h6v6"/></React.Fragment>,
  alert:         <React.Fragment><circle cx="12" cy="12" r="10"/><path d="M12 8v4"/><path d="M12 16h.01"/></React.Fragment>,
  filter:        <path d="M22 3H2l8 9.5V19l4 2v-8.5z"/>,
  link:          <React.Fragment><path d="M9 17H7A5 5 0 0 1 7 7h2"/><path d="M15 7h2a5 5 0 0 1 0 10h-2"/><path d="M8 12h8"/></React.Fragment>,
  building:      <React.Fragment><rect x="4" y="2" width="16" height="20" rx="2"/><path d="M9 22v-4h6v4"/><path d="M8 6h.01M16 6h.01M8 10h.01M16 10h.01M8 14h.01M16 14h.01"/></React.Fragment>,
  globe:         <React.Fragment><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></React.Fragment>,
  chevronDown:   <path d="m6 9 6 6 6-6"/>,
  chevronUp:     <path d="m18 15-6-6-6 6"/>,
  copy:          <React.Fragment><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></React.Fragment>,
  refresh:       <React.Fragment><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/><path d="M3 21v-5h5"/></React.Fragment>,
  bell:          <React.Fragment><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/></React.Fragment>,
};

/* ========== Prime brand mark ========== */
const PrimeLogo = ({ size = 28 }) => (
  <svg width={size} height={size} viewBox="0 0 40 40" fill="none" aria-hidden="true">
    <rect width="40" height="40" rx="4" fill="#1B3A6B"/>
    <path d="M9 28 L25 16 M25 16 L19 13 M25 16 L23 22" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
    <text x="20" y="34" fontFamily="Fraunces, serif" fontWeight="700" fontSize="9" textAnchor="middle" fill="#fff">Prime</text>
  </svg>
);

/* ========== Modal ========== */
function Modal({ open, onClose, title, children, footer, size = 'md' }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose && onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className={`modal ${size}`} onClick={(e)=>e.stopPropagation()}>
        <div className="modal-header">
          <h2>{title}</h2>
          <button className="close" onClick={onClose} aria-label="Close"><Icon name="close" size={18}/></button>
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-footer">{footer}</div>}
      </div>
    </div>
  );
}

/* ========== Stage badge ========== */
function StageBadge({ stageId }) {
  const stage = window.PVStore.state.stages.find(s=>s.id===stageId);
  if (!stage) return <span className="badge">{stageId}</span>;
  return <span className={`badge ${stage.color}`}><span className="dot"/>{stage.label}</span>;
}

/* ========== Helpers ========== */
function customerById(id) {
  return window.PVStore.state.customers.find(c=>c.id===id);
}
function customerName(id) {
  const c = customerById(id);
  return c ? c.name : '—';
}
function countryName(code) {
  if (!code) return '';
  const p = window.PVStore.state.pricing.find(x=>x.code===code);
  return p ? p.name : code;
}
function countryFlag(code) {
  if (!code) return '';
  const p = window.PVStore.state.pricing.find(x=>x.code===code);
  return p ? p.flag : '';
}

/* ========== Toast ========== */
function useToast() {
  const [msg, setMsg] = useState(null);
  const show = useCallback((text) => {
    setMsg(text);
    setTimeout(() => setMsg(null), 2500);
  }, []);
  const view = msg ? (
    <div style={{
      position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)',
      background: '#0b2347', color: '#fff', padding: '10px 18px',
      borderRadius: 8, fontSize: 13, fontWeight: 500, zIndex: 200,
      boxShadow: '0 8px 24px rgba(0,0,0,0.25)'
    }}>{msg}</div>
  ) : null;
  return [show, view];
}

/* ========== Read file as data URL (for uploads) ========== */
function fileToDataUrl(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

/* ========== Export to window ========== */
Object.assign(window, {
  useStore, Icon, ICONS, PrimeLogo, Modal, StageBadge,
  customerById, customerName, countryName, countryFlag,
  fmtMoney, fmtDate, fmtDateShort, fmtDateTime, relativeTime, uid,
  useToast, fileToDataUrl,
});
