/* global React */
// Annona Intake — shared primitives & mock data
// Exported to window so other babel scripts can reuse.

// ──────────────────────────────────────────────────────────────
// Icons — hand-drawn, match warm/friendly tone (not geometric)
// ──────────────────────────────────────────────────────────────
const Icon = ({ name, size = 22, color = 'currentColor', stroke = 1.8 }) => {
  const p = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: color, strokeWidth: stroke, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'back':    return <svg {...p}><path d="M15 6l-6 6 6 6"/></svg>;
    case 'close':   return <svg {...p}><path d="M6 6l12 12M18 6L6 18"/></svg>;
    case 'qr':      return <svg {...p}><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><path d="M14 14h3v3h-3zM20 14v3M14 20h3M20 20v1"/></svg>;
    case 'scan':    return <svg {...p}><path d="M4 8V6a2 2 0 0 1 2-2h2M16 4h2a2 2 0 0 1 2 2v2M20 16v2a2 2 0 0 1-2 2h-2M8 20H6a2 2 0 0 1-2-2v-2M7 12h10"/></svg>;
    case 'plus':    return <svg {...p}><path d="M12 5v14M5 12h14"/></svg>;
    case 'check':   return <svg {...p}><path d="M5 12l5 5L20 7"/></svg>;
    case 'chev':    return <svg {...p}><path d="M9 6l6 6-6 6"/></svg>;
    case 'mapPin':  return <svg {...p}><path d="M21 10c0 6-9 12-9 12S3 16 3 10a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="2.5"/></svg>;
    case 'coins':   return <svg {...p}><circle cx="8" cy="8" r="5"/><path d="M16 11a5 5 0 1 1 0 10 5 5 0 0 1 0-10"/><path d="M6 8h4M14 16h4"/></svg>;
    case 'phone':   return <svg {...p}><path d="M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.1-8.6A2 2 0 0 1 4 2h3a2 2 0 0 1 2 1.7 12.8 12.8 0 0 0 .7 2.8 2 2 0 0 1-.4 2.1L8 10a16 16 0 0 0 6 6l1.4-1.4a2 2 0 0 1 2.1-.4 12.8 12.8 0 0 0 2.8.7A2 2 0 0 1 22 16.9z"/></svg>;
    case 'mail':    return <svg {...p}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></svg>;
    case 'printer': return <svg {...p}><path d="M6 9V4h12v5M6 18H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="7" rx="1"/></svg>;
    case 'wa':      return <svg {...p}><path d="M21 12a9 9 0 0 1-13.5 7.8L3 21l1.3-4.4A9 9 0 1 1 21 12z"/><path d="M8 10c0 5 4 7 6 7l2-2-2-2-2 1c-1-.5-2-1.5-2.5-2.5l1-2-2-2-2 .5"/></svg>;
    case 'camera':  return <svg {...p}><path d="M3 8a2 2 0 0 1 2-2h2l2-2h6l2 2h2a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8z"/><circle cx="12" cy="13" r="3.5"/></svg>;
    case 'bag':     return <svg {...p}><path d="M6 7h12l-1 13a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L6 7z"/><path d="M9 7V5a3 3 0 0 1 6 0v2"/></svg>;
    case 'scale':   return <svg {...p}><path d="M12 3v2M5 7l-2 7a4 4 0 0 0 8 0l-2-7M19 7l-2 7a4 4 0 0 0 8 0l-2-7M4 21h16M9 7h6"/></svg>;
    case 'clock':   return <svg {...p}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>;
    case 'cloud':   return <svg {...p}><path d="M17 18a4 4 0 0 0 0-8 6 6 0 0 0-11.5 2A4 4 0 0 0 6 18h11z"/></svg>;
    case 'sync':    return <svg {...p}><path d="M3 12a9 9 0 0 1 15-6.7L21 8M21 12a9 9 0 0 1-15 6.7L3 16M21 3v5h-5M3 21v-5h5"/></svg>;
    case 'user':    return <svg {...p}><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg>;
    case 'search':  return <svg {...p}><circle cx="11" cy="11" r="7"/><path d="M20 20l-4-4"/></svg>;
    case 'flag':    return <svg {...p}><path d="M5 21V4M5 4h13l-2 5 2 5H5"/></svg>;
    case 'sun':     return <svg {...p}><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>;
    case 'download':return <svg {...p}><path d="M12 4v12M6 12l6 6 6-6M4 20h16"/></svg>;
    case 'wifi-off':return <svg {...p}><path d="M2 2l20 20M8.5 16.5a5 5 0 0 1 7 0M5 12.5a9 9 0 0 1 3-2M19 12.5a9 9 0 0 0-7-3.5M1.5 8.5a13 13 0 0 1 4-2.5M22.5 8.5a13 13 0 0 0-7-3.5"/><circle cx="12" cy="20" r="0.5" fill="currentColor"/></svg>;
    case 'check-c': return <svg {...p}><circle cx="12" cy="12" r="9"/><path d="M8 12l3 3 5-5"/></svg>;
    case 'circle':  return <svg {...p}><circle cx="12" cy="12" r="9"/></svg>;
    default: return <svg {...p}><circle cx="12" cy="12" r="9"/></svg>;
  }
};

// ──────────────────────────────────────────────────────────────
// Mock data
// ──────────────────────────────────────────────────────────────
const PRODUCERS = [
  { id: 'P-0214', name: 'Ana María Restrepo',    initials: 'AR', cooperative: 'Asocafé Huila',       village: 'Pitalito · Vereda Bruselas', distance: 180, plots: 3,
    plotList: [
      { id: 'PL-214A', name: 'La Esperanza',  ha: 2.4, var: 'Caturra · Colombia',   alt: '1 680 m', lastPick: '5 d' },
      { id: 'PL-214B', name: 'El Mirador',    ha: 1.1, var: 'Castillo',             alt: '1 720 m', lastPick: '12 d' },
      { id: 'PL-214C', name: 'Bajo Palmar',   ha: 0.8, var: 'Tabi',                 alt: '1 540 m', lastPick: '2 d' },
    ]
  },
  { id: 'P-0187', name: 'Don Jairo Cárdenas',    initials: 'JC', cooperative: 'Asocafé Huila',       village: 'Pitalito · Bruselas',        distance: 340, plots: 2,
    plotList: [
      { id: 'PL-187A', name: 'Finca El Retiro',  ha: 3.2, var: 'Caturra · Bourbon', alt: '1 610 m', lastPick: '7 d' },
      { id: 'PL-187B', name: 'Potrero',          ha: 1.6, var: 'Castillo',          alt: '1 620 m', lastPick: '18 d' },
    ]
  },
  { id: 'P-0298', name: 'Lucía Valderrama',      initials: 'LV', cooperative: 'Asocafé Huila',       village: 'Pitalito · Charguayaco',     distance: 520, plots: 1, plotList: [] },
  { id: 'P-0156', name: 'Héctor Rojas Morales',  initials: 'HR', cooperative: 'Coop. Guacamayas',   village: 'Pitalito · Regueros',        distance: 780, plots: 4, plotList: [] },
];

const DAILY_PRICES = {
  origin: 'Huila · Colombia',
  parchment_cop_per_kg: 14_850,
  c_market_usd_lb: 3.47,
  differential_usd_lb: 0.42,
  fx_usd_cop: 4_120,
  set_at: '05:42',
  set_by: 'Kantoor Bogotá',
};

const PAYMENT_METHODS = [
  { id: 'cop-cash', label: 'Peso efectivo',   sub: 'COP · contant bij kassa',   icon: 'coins',  rate: 1,         unit: 'COP' },
  { id: 'usd-cash', label: 'Dólares',         sub: 'USD · contant bij kassa',   icon: 'coins',  rate: 1 / 4120,  unit: 'USD' },
  { id: 'nequi',    label: 'Nequi',           sub: 'Transfer directo · 2 min',  icon: 'phone',  rate: 1,         unit: 'COP', tag: 'Instant' },
  { id: 'bank',     label: 'Bancolombia',     sub: 'Transferencia · 24 h',      icon: 'phone',  rate: 1,         unit: 'COP' },
];

const TODAY_INTAKES = [
  { id: 'IN-2041', producer: 'Ana María Restrepo',  initials: 'AR', time: '07:14', bags: 8,  kg: 512.4,  value_cop: 7_609_140, status: 'paid'    },
  { id: 'IN-2042', producer: 'Don Jairo Cárdenas',  initials: 'JC', time: '08:02', bags: 12, kg: 768.2,  value_cop: 11_408_770, status: 'paid'   },
  { id: 'IN-2043', producer: 'Lucía Valderrama',    initials: 'LV', time: '09:31', bags: 4,  kg: 254.8,  value_cop: 3_783_780, status: 'at-kassa' },
  { id: 'IN-2044', producer: 'Héctor Rojas M.',     initials: 'HR', time: '10:18', bags: 15, kg: 961.5,  value_cop: 14_278_280, status: 'pending' },
  { id: 'IN-2045', producer: 'Ana María Restrepo',  initials: 'AR', time: '11:02', bags: 6,  kg: 381.6,  value_cop: 5_666_760, status: 'open'    },
];

// Formatters
const fmtCOP  = n => '$ ' + Math.round(n).toLocaleString('es-CO').replace(/,/g, '.');
const fmtKG   = n => n.toFixed(1).replace('.', ',') + ' kg';
const fmtUSD  = n => '$ ' + n.toFixed(2) + ' USD';
const fmtInt  = n => n.toLocaleString('es-CO').replace(/,/g, '.');

// Chip status lookup
const STATUS_STYLE = {
  'paid':     { label: 'Pagado',    cls: 'green' },
  'at-kassa': { label: 'En caja',   cls: 'rust' },
  'pending':  { label: 'Pendiente', cls: '' },
  'open':     { label: 'Abierto',   cls: 'outline' },
};

// ──────────────────────────────────────────────────────────────
// Shared UI pieces
// ──────────────────────────────────────────────────────────────

function StatusBar({ sync = 'online' }) {
  return (
    <div style={{ padding: '0 16px', height: 28, display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 12, color: 'var(--ink-2)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <Icon name={sync === 'offline' ? 'wifi-off' : 'cloud'} size={14} />
        <span style={{ fontWeight: 500 }}>{sync === 'offline' ? 'Sin señal · 3 pendientes' : sync === 'syncing' ? 'Sincronizando…' : 'Sincronizado'}</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
        <Icon name="sun" size={14} /><span>28°</span>
      </div>
    </div>
  );
}

function TopBar({ title, onBack, right, subtitle }) {
  return (
    <div className="topbar">
      {onBack !== undefined && (
        <div className="back"><Icon name="back" size={22} /></div>
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <h1>{title}</h1>
        {subtitle && <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 1 }}>{subtitle}</div>}
      </div>
      {right}
    </div>
  );
}

function StepDots({ step, total }) {
  return (
    <div className="dots">
      {Array.from({ length: total }).map((_, i) => (
        <div key={i} className={'d' + (i <= step ? ' active' : '')} />
      ))}
    </div>
  );
}

function Avatar({ initials, size = 'md', square = false, color }) {
  const cls = 'avatar ' + (size === 'lg' ? 'lg' : size === 'xl' ? 'xl' : '') + (square ? ' square' : '');
  return <div className={cls} style={color ? { background: color } : {}}>{initials}</div>;
}

// Colors for avatars
const AVATAR_GRADIENTS = [
  'linear-gradient(135deg, #B8894B, #8A5A2B)',
  'linear-gradient(135deg, #6B8E4E, #3F5A2E)',
  'linear-gradient(135deg, #B85C34, #8C3C1F)',
  'linear-gradient(135deg, #7A5FAE, #4E3C78)',
  'linear-gradient(135deg, #3E6B8A, #254A66)',
];
const gradientFor = (id) => {
  const sum = (id || '').split('').reduce((a, c) => a + c.charCodeAt(0), 0);
  return AVATAR_GRADIENTS[sum % AVATAR_GRADIENTS.length];
};

// QR code fake — pass seed for variety
function FakeQR({ size = 120, seed = 'abc' }) {
  const cells = 21;
  const cellSize = size / cells;
  // Deterministic pattern based on seed
  const hash = seed.split('').reduce((a, c) => (a * 31 + c.charCodeAt(0)) >>> 0, 5381);
  const rand = (n) => (((hash >> (n % 30)) ^ (hash * (n + 1))) >>> 0) % 100;

  const dots = [];
  for (let y = 0; y < cells; y++) {
    for (let x = 0; x < cells; x++) {
      // Finder corners — skip dots, draw separately
      const inCorner = (x < 7 && y < 7) || (x > cells - 8 && y < 7) || (x < 7 && y > cells - 8);
      if (inCorner) continue;
      if (rand(x * cells + y) > 50) {
        dots.push(<rect key={x + '_' + y} x={x * cellSize} y={y * cellSize} width={cellSize} height={cellSize} fill="#2B1D10" />);
      }
    }
  }
  const Finder = ({ x, y }) => (
    <g transform={`translate(${x * cellSize},${y * cellSize})`}>
      <rect x="0" y="0" width={cellSize * 7} height={cellSize * 7} fill="#2B1D10" />
      <rect x={cellSize} y={cellSize} width={cellSize * 5} height={cellSize * 5} fill="#fff" />
      <rect x={cellSize * 2} y={cellSize * 2} width={cellSize * 3} height={cellSize * 3} fill="#2B1D10" />
    </g>
  );
  return (
    <svg width={size} height={size} style={{ background: '#fff', borderRadius: 10, padding: 4, boxShadow: 'var(--card-shadow)', display: 'block' }}>
      {dots}
      <Finder x={0} y={0} />
      <Finder x={cells - 7} y={0} />
      <Finder x={0} y={cells - 7} />
    </svg>
  );
}

// ──────────────────────────────────────────────────────────────
// Export
// ──────────────────────────────────────────────────────────────
Object.assign(window, {
  IntakeIcon: Icon,
  IntakeStatusBar: StatusBar,
  IntakeTopBar: TopBar,
  IntakeStepDots: StepDots,
  IntakeAvatar: Avatar,
  IntakeFakeQR: FakeQR,
  intakeGradientFor: gradientFor,
  INTAKE_PRODUCERS: PRODUCERS,
  INTAKE_DAILY_PRICES: DAILY_PRICES,
  INTAKE_PAYMENT_METHODS: PAYMENT_METHODS,
  INTAKE_TODAY: TODAY_INTAKES,
  INTAKE_STATUS: STATUS_STYLE,
  intakeFmtCOP: fmtCOP,
  intakeFmtKG: fmtKG,
  intakeFmtUSD: fmtUSD,
  intakeFmtInt: fmtInt,
});
