// scanner.jsx — Barcode scan mode (PDA / มือถือ friendly)

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

// ── ScanResult — big action buttons ──────────────────────────
function ScanResult({ order, onAction, onNext }) {
  const [done, setDone] = useState(null); // status ที่เพิ่งกด
  const p = PLATFORMS[order.platform];

  const handleAction = (status) => {
    setDone(status);
    onAction(order.id, status);
    // auto-advance หลัง 800ms
    setTimeout(() => { setDone(null); onNext(); }, 800);
  };

  if (done) {
    // flash success
    const labels = { packed: 'แพ็คเสร็จแล้ว ✓', shipped: 'ส่งออกแล้ว ✓', cancelled: 'ยกเลิกแล้ว ✓' };
    const colors = { packed: '#2A6FDB', shipped: '#1F8A5B', cancelled: '#e05c5c' };
    return (
      <div className="scan-success-flash" style={{ background: colors[done] }}>
        <div className="ssf-text">{labels[done]}</div>
        <div className="ssf-code">{order.code}</div>
      </div>
    );
  }

  return (
    <div className="scan-result-v2">
      {/* Order info */}
      <div className="srv2-info">
        <div className="srv2-platform">
          <span className="platform-badge" style={{ width:28, height:28, background: p.dot, fontSize:12, borderRadius:6 }}>{p.short}</span>
          <span className="srv2-pname">{p.name}</span>
          <span className={`srv2-status-dot status-${order.status}`} />
          <span className="srv2-status-label">{STATUSES[order.status]?.label}</span>
        </div>
        <div className="srv2-code">{order.code}</div>
        <div className="srv2-meta">{order.customer} · {order.qty} ชิ้น</div>
      </div>

      {/* Big action buttons */}
      <div className="srv2-actions">
        <button
          className="srv2-btn packed"
          onClick={() => handleAction('packed')}
        >
          <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
            <path d="M5 14L11 20L23 8" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          <span>แพ็คเสร็จ</span>
          <small>กด 1</small>
        </button>

        <button
          className="srv2-btn shipped"
          onClick={() => handleAction('shipped')}
        >
          <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
            <path d="M5 14h16M17 8l6 6-6 6" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          <span>ส่งออกแล้ว</span>
          <small>กด 2</small>
        </button>

        <button
          className="srv2-btn cancelled"
          onClick={() => handleAction('cancelled')}
        >
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
            <path d="M5 5l14 14M19 5L5 19" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
          </svg>
          <span>ยกเลิก</span>
          <small>กด 3</small>
        </button>
      </div>

      <button className="srv2-skip" onClick={onNext}>
        ข้ามไปสแกนใบถัดไป →
      </button>
    </div>
  );
}

function NotFound({ code }) {
  return (
    <div className="scan-not-found">
      <div className="snf-icon">
        <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
          <circle cx="20" cy="20" r="17" stroke="currentColor" strokeWidth="1.8"/>
          <path d="M14 14l12 12M26 14L14 26" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
        </svg>
      </div>
      <div className="snf-title">ไม่พบคำสั่งซื้อ</div>
      <div className="snf-code">"{code}"</div>
      <div className="snf-hint">ตรวจสอบว่านำเข้า order นี้แล้วหรือยัง</div>
    </div>
  );
}

// ── Main ScannerModal ─────────────────────────────────────────
function ScannerModal({ orders, onClose, onStatusChange }) {
  const [input, setInput]       = useState('');
  const [found, setFound]       = useState(null);
  const [notFound, setNotFound] = useState('');
  const [history, setHistory]   = useState([]);
  const [scanCount, setScanCount] = useState(0);
  const inpRef = useRef(null);

  useEffect(() => { setTimeout(() => inpRef.current?.focus(), 80); }, []);

  useEffect(() => {
    const fn = (e) => {
      if (e.key === 'Escape') { onClose(); return; }
      // keyboard shortcuts เมื่อเจอ order แล้ว
      if (found && !e.target.closest('input')) {
        if (e.key === '1') handleAction(found.id, 'packed');
        if (e.key === '2') handleAction(found.id, 'shipped');
        if (e.key === '3') handleAction(found.id, 'cancelled');
      }
    };
    window.addEventListener('keydown', fn);
    return () => window.removeEventListener('keydown', fn);
  }, [found, onClose]);

  const doSearch = useCallback((raw) => {
    const q = raw.trim().toUpperCase();
    if (!q) return;
    const match = orders.find(o =>
      o.code.toUpperCase() === q ||
      o.code.toUpperCase().includes(q) ||
      q.includes(o.code.toUpperCase())
    );
    if (match) { setFound(match); setNotFound(''); }
    else { setFound(null); setNotFound(raw.trim()); }
    setScanCount(c => c + 1);
    setInput('');
  }, [orders]);

  // Auto-search หลังพิมพ์หยุด 400ms (ปืนสแกนส่ง Enter ด้วย แต่นี่ทำให้ไม่ต้องกดปุ่ม)
  useEffect(() => {
    if (!input.trim()) return;
    const t = setTimeout(() => doSearch(input), 400);
    return () => clearTimeout(t);
  }, [input, doSearch]);

  const handleAction = (id, status) => {
    onStatusChange(id, status);
    const o = orders.find(o => o.id === id);
    if (o) setHistory(prev => [
      { code: o.code, customer: o.customer, platform: o.platform, newStatus: status },
      ...prev.slice(0, 9)
    ]);
    setFound(prev => prev?.id === id ? { ...prev, status } : prev);
  };

  const clearAndRefocus = () => {
    setFound(null); setNotFound(''); setInput('');
    setTimeout(() => inpRef.current?.focus(), 50);
  };

  const HIST_COLORS = {
    packed:    { bg: 'oklch(0.93 0.05 245)', text: 'oklch(0.42 0.14 245)' },
    shipped:   { bg: 'oklch(0.93 0.05 155)', text: 'oklch(0.40 0.12 155)' },
    cancelled: { bg: 'oklch(0.97 0.02 18)',  text: 'oklch(0.52 0.22 18)'  },
  };

  return (
    <div className="modal-backdrop scan-backdrop" onClick={onClose}>
      <div className="scan-modal" onClick={e => e.stopPropagation()}>

        {/* Header */}
        <div className="scan-header">
          <div className="scan-header-left">
            <div className="scan-icon-wrap">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                <path d="M3 7V4a1 1 0 0 1 1-1h3M17 3h3a1 1 0 0 1 1 1v3M21 17v3a1 1 0 0 1-1 1h-3M7 21H4a1 1 0 0 1-1-1v-3" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
                <path d="M6 8v8M9 8v8M12 8v8M15 8v8M18 8v8" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
              </svg>
            </div>
            <div>
              <div className="scan-title">โหมดสแกน Barcode</div>
              <div className="scan-subtitle">วางปืนสแกนบน Barcode ใบส่งของได้เลย</div>
            </div>
          </div>
          <div className="scan-header-right">
            {scanCount > 0 && <div className="scan-count">{scanCount} ครั้ง</div>}
            <button className="close-btn" onClick={onClose}>×</button>
          </div>
        </div>

        {/* Input */}
        <div className="scan-input-zone" onClick={() => inpRef.current?.focus()}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" style={{ color:'var(--ink-3)', flexShrink:0 }}>
            <path d="M3 7V4a1 1 0 0 1 1-1h3M17 3h3a1 1 0 0 1 1 1v3M21 17v3a1 1 0 0 1-1 1h-3M7 21H4a1 1 0 0 1-1-1v-3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
            <path d="M6 8v8M9 8v8M12 8v8M15 8v8M18 8v8" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
          </svg>
          <input
            ref={inpRef}
            className="scan-input"
            type="text"
            placeholder="สแกน Barcode หรือพิมพ์เลข Order แล้วกด Enter…"
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') { doSearch(input); e.preventDefault(); } }}
            autoComplete="off" autoCorrect="off" spellCheck={false}
          />
          {input && <button className="scan-clear" onClick={() => setInput('')}>×</button>}
          <button className="scan-go" onClick={() => doSearch(input)} disabled={!input.trim()}>ค้นหา</button>
        </div>

        {/* Result */}
        <div className="scan-body">
          {!found && !notFound && (
            <div className="scan-idle">
              <svg width="48" height="48" viewBox="0 0 48 48" fill="none" opacity=".25">
                <rect x="4" y="8" width="4" height="32" rx="1" fill="currentColor"/>
                <rect x="12" y="8" width="2" height="32" rx="1" fill="currentColor"/>
                <rect x="18" y="8" width="4" height="32" rx="1" fill="currentColor"/>
                <rect x="26" y="8" width="2" height="32" rx="1" fill="currentColor"/>
                <rect x="32" y="8" width="6" height="32" rx="1" fill="currentColor"/>
                <rect x="42" y="8" width="2" height="32" rx="1" fill="currentColor"/>
              </svg>
              <p>พร้อมสแกน</p>
            </div>
          )}
          {found && <ScanResult order={found} onAction={handleAction} onNext={clearAndRefocus} />}
          {notFound && !found && <NotFound code={notFound} />}
        </div>

        {/* History */}
        {history.length > 0 && (
          <div className="scan-history">
            <div className="sh-label">ประวัติสแกน</div>
            {history.map((h, i) => {
              const p = PLATFORMS[h.platform];
              const col = HIST_COLORS[h.newStatus] || HIST_COLORS.cancelled;
              return (
                <div key={i} className="sh-row">
                  <span className="platform-badge" style={{ width:14, height:14, background: p?.dot, fontSize:7, borderRadius:3, flexShrink:0 }}>{p?.short}</span>
                  <span className="sh-code">{h.code}</span>
                  <span className="sh-customer">{h.customer}</span>
                  <span className="sh-status" style={{ background: col.bg, color: col.text }}>{STATUSES[h.newStatus]?.label}</span>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { ScannerModal });
