// token-modal.jsx — in-menu buyer-token unlock modal. A buyer who lands
// straight on a market menu (skipping the landing-page TokenPanel) can unlock
// pricing from here: locked prices expose a "View price" button that opens this
// modal. Reuses the App's onUnlock (POST /api/unlock) — no fetch logic here —
// and mirrors the landing TokenPanel input/notice/busy pattern inside the
// site's shared modal-scrim. Closes itself on a successful unlock.
const { useState: useStateT, useEffect: useEffectT } = React;

function TokenModal({ onUnlock, onClose }) {
  const [val, setVal] = useStateT('');
  const [notice, setNotice] = useStateT('');
  const [busy, setBusy] = useStateT(false);

  useEffectT(() => {
    const handler = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [onClose]);

  async function submit() {
    const v = val.trim().toLowerCase();
    if (!v) { setNotice('Enter your buyer code'); return; }
    setBusy(true); setNotice('');
    const res = await onUnlock(v);
    setBusy(false);
    if (res.ok) { onClose(); return; }
    setNotice(res.error === 'network' ? "Couldn't reach the server, try again" : "That code wasn't recognized");
  }

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="tk-card" onClick={(e) => e.stopPropagation()}>
        <button className="close-x" onClick={onClose} aria-label="Close">×</button>
        <div className="token-row">
          <span className="led led-red"></span>
          <span className="token-label">Wholesale token</span>
        </div>
        <h2 className="tk-title display-md">Enter buyer token</h2>
        <p className="tk-lede">Prices and buyer terms unlock with the code from your outreach email.</p>
        <div className="token-field">
          <input type="password" placeholder="Enter token here" value={val} autoFocus
            onChange={(e) => setVal(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && submit()} />
          <button onClick={submit} disabled={busy}>{busy ? 'Checking…' : 'Unlock'}</button>
        </div>
        <div className="token-notice">{notice || 'Specs are public — pricing unlocks per buyer'}</div>
      </div>
    </div>);

}

Object.assign(window, { TokenModal });
