// TruckOrderShared.jsx — utilities + small components shared across the
// truck-order screens. Loaded FIRST among the truck-order scripts so other
// files can read these off window.
//
//   toFmtDate / toFmtTime / toFmtDateTime / toFmtQty  — formatters
//   PinGate    — modal that captures a 4-digit PIN and resolves to staff
//   OverrideMark — tiny badge shown next to manually-overridden order amounts

const { useState: useTOS, useRef: useRefTOS, useEffect: useEffectTOS } = React;

// ------------------------------------------------------------------
// Formatters
// ------------------------------------------------------------------
const toFmtDate = (iso) => {
  if (!iso) return '';
  const d = new Date(iso);
  return d.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
};
const toFmtTime = (iso) => {
  if (!iso) return '';
  const d = new Date(iso);
  return d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
};
const toFmtDateTime = (iso) => `${toFmtDate(iso)} · ${toFmtTime(iso)}`;
const toFmtQty = (n) => {
  if (n === 0 || n === '0') return '0';
  const v = Number(n);
  if (!isFinite(v)) return '0';
  if (Math.abs(v - Math.round(v)) < 0.001) return String(Math.round(v));
  return v.toFixed(2).replace(/\.?0+$/, '');
};

// ------------------------------------------------------------------
// PinGate — modal with keypad + keyboard input
// ------------------------------------------------------------------
const PinGate = ({ purpose, onCancel, onSuccess }) => {
  const [pin, setPin] = useTOS('');
  const [err, setErr] = useTOS('');
  const [shake, setShake] = useTOS(false);
  const inputRef = useRefTOS(null);

  useEffectTOS(() => { inputRef.current?.focus(); }, []);

  const handleSubmit = (val) => {
    const p = val !== undefined ? val : pin;
    if (p.length < 4) return;
    const staff = window.SAMPLE_STAFF.find(s => s.pin === p);
    if (staff) {
      onSuccess(staff);
    } else {
      setErr('PIN not recognized');
      setShake(true);
      setTimeout(() => setShake(false), 400);
      setTimeout(() => { setPin(''); inputRef.current?.focus(); }, 150);
    }
  };

  // Auto-submit on 4-digit entry
  useEffectTOS(() => {
    if (pin.length === 4) {
      const t = setTimeout(() => handleSubmit(pin), 100);
      return () => clearTimeout(t);
    }
    if (pin.length > 0) setErr('');
  }, [pin]);

  const pad  = (d) => () => setPin(p => (p + d).slice(0, 4));
  const back = ()  => setPin(p => p.slice(0, -1));

  return (
    <PModal open={true} onClose={onCancel} width={360}>
      <div style={{ padding: '24px 24px 20px', textAlign: 'center' }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 6 }}>
          PIN required
        </div>
        <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--fg-1)', letterSpacing: '-0.01em', marginBottom: 18 }}>
          {purpose}
        </div>

        {/* Visible dots */}
        <div style={{
          display: 'flex', justifyContent: 'center', gap: 14,
          marginBottom: 8,
          animation: shake ? 'pin-shake 0.4s ease' : undefined,
        }}>
          {[0,1,2,3].map(i => (
            <div key={i} style={{
              width: 18, height: 18, borderRadius: 999,
              background: i < pin.length ? 'var(--fg-1)' : 'transparent',
              border: '2px solid ' + (err ? '#BE123C' : 'var(--border-1)'),
              transition: 'all 120ms ease',
            }} />
          ))}
        </div>
        <div style={{ height: 18, fontSize: 12, color: err ? '#BE123C' : 'var(--fg-3)', marginBottom: 14 }}>
          {err || 'Enter your 4-digit PIN'}
        </div>

        {/* Hidden input for keyboard entry */}
        <input
          ref={inputRef}
          value={pin}
          onChange={e => setPin(e.target.value.replace(/\D/g, '').slice(0, 4))}
          onKeyDown={e => { if (e.key === 'Enter') handleSubmit(); }}
          inputMode="numeric"
          maxLength={4}
          style={{
            position: 'absolute', opacity: 0, pointerEvents: 'none',
            width: 1, height: 1,
          }}
        />

        {/* Keypad */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginBottom: 14 }}>
          {['1','2','3','4','5','6','7','8','9'].map(d => (
            <button key={d} onClick={pad(d)} style={{
              height: 52, fontSize: 20, fontWeight: 500, fontFamily: 'var(--font-num)',
              background: 'var(--bg-sunken)', border: 'none', borderRadius: 8,
              cursor: 'pointer', color: 'var(--fg-1)',
            }}>{d}</button>
          ))}
          <div />
          <button onClick={pad('0')} style={{
            height: 52, fontSize: 20, fontWeight: 500, fontFamily: 'var(--font-num)',
            background: 'var(--bg-sunken)', border: 'none', borderRadius: 8,
            cursor: 'pointer', color: 'var(--fg-1)',
          }}>0</button>
          <button onClick={back} style={{
            height: 52, background: 'transparent', border: 'none', borderRadius: 8,
            cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--fg-2)',
          }}>
            <PIcon name="chevronL" size={20} />
          </button>
        </div>

        <PBtn variant="ghost" onClick={onCancel} fullWidth>Cancel</PBtn>
      </div>

      <style>{`
        @keyframes pin-shake {
          0%, 100% { transform: translateX(0); }
          20% { transform: translateX(-8px); }
          40% { transform: translateX(8px); }
          60% { transform: translateX(-4px); }
          80% { transform: translateX(4px); }
        }
      `}</style>
    </PModal>
  );
};

// ------------------------------------------------------------------
// Tiny "Overridden" badge
// ------------------------------------------------------------------
const OverrideMark = ({ children }) => (
  <span style={{
    display: 'inline-flex', alignItems: 'center', gap: 4,
    fontSize: 10, fontWeight: 700, color: '#92400E',
    background: '#FDE68A', padding: '2px 7px', borderRadius: 4,
    letterSpacing: '0.04em', textTransform: 'uppercase',
    whiteSpace: 'nowrap',
  }}>
    {children || 'Overridden'}
  </span>
);

Object.assign(window, {
  toFmtDate, toFmtTime, toFmtDateTime, toFmtQty,
  PinGate, OverrideMark,
});
