// Mock secure-checkout. Charges the consult so the visit becomes joinable.
// Free follow-up logic lives in the booking flow + the visit page guard,
// so by the time we land here we've already decided payment is required.

function PayCheckout({ tone = 'warm', route = '' }) {
  const { user } = useAuth();
  const consults = useConsults();
  const [params] = React.useState(() => new URLSearchParams((route.split('?')[1] || '')));
  const consultId = params.get('consult') || '';
  const emergency = params.get('emergency') === '1';
  const [emergencyConsult, setEmergencyConsult] = React.useState(null);
  const creatingEmergency = React.useRef(false);
  const consult = emergencyConsult || consults.find((c) => c.id === consultId) || (!emergency ? consults[0] : null);
  const doc = consult ? DOC_BY_ID(consult.docId) : DOC_BY_ID(1);

  const [card, setCard] = React.useState({ number: '4242 4242 4242 4242', name: '', exp: '12/28', cvv: '123' });
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  const fee = consult?.fee ?? doc.fee;
  const tax = Math.round(fee * 0.0); // mock — no tax for now
  const total = fee + tax;

  React.useEffect(() => {
    if (!emergency || consult || creatingEmergency.current) return;
    creatingEmergency.current = true;
    (async () => {
      const created = await (window.startEmergencyConsult && window.startEmergencyConsult(user));
      if (created) setEmergencyConsult(created);
      creatingEmergency.current = false;
    })();
  }, [emergency, consult, user?.userId]);

  const submit = async () => {
    if (!consult) { setErr('No consult to pay for.'); return; }
    const last4 = (card.number.replace(/\s+/g, '').slice(-4)) || '4242';
    if (last4.length !== 4) { setErr('Card number looks off.'); return; }
    setBusy(true); setErr('');
    const saved = await (window.chargeConsult && window.chargeConsult({ consultId: consult.id, amount: total, last4, method: 'card' }));
    setBusy(false);
    if (saved) {
      window.navigate && window.navigate('/confirmed');
    } else {
      setErr("We couldn't process that. Try again.");
    }
  };

  return (
    <PortalShell active="appointments" title="Secure checkout" subtitle="Pay your consultation fee to confirm your slot.">
      <div style={{ padding: '24px 32px 48px', maxWidth: 1080, margin: '0 auto', display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 22 }}>

        {/* Left: card form */}
        <div className="ml-card" style={{ padding: 28 }}>
          <div className="ml-label" style={{ marginBottom: 12 }}>PAYMENT METHOD</div>
          <div style={{ display: 'flex', gap: 8, marginBottom: 20 }}>
            {['Card', 'UPI', 'Net banking'].map((m, i) => (
              <button key={m} className="ml-btn" disabled={i !== 0} style={{
                background: i === 0 ? 'var(--blue-soft)' : '#fff',
                color: i === 0 ? 'var(--blue-deep)' : 'var(--ink-3)',
                border: '1px solid ' + (i === 0 ? 'var(--blue)' : 'var(--line)'),
                opacity: i === 0 ? 1 : 0.5, cursor: i === 0 ? 'default' : 'not-allowed',
              }}>{m}{i !== 0 && ' (mock)'}</button>
            ))}
          </div>

          <Field label="Card number">
            <input value={card.number} onChange={(e) => setCard({ ...card, number: e.target.value })}
              className="ml-input" inputMode="numeric" placeholder="1234 5678 9012 3456" style={{ letterSpacing: '0.04em' }}/>
          </Field>
          <Field label="Cardholder name">
            <input value={card.name} onChange={(e) => setCard({ ...card, name: e.target.value })}
              className="ml-input" placeholder="Name as on card"/>
          </Field>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Field label="Expiry">
              <input value={card.exp} onChange={(e) => setCard({ ...card, exp: e.target.value })}
                className="ml-input" placeholder="MM/YY"/>
            </Field>
            <Field label="CVV">
              <input value={card.cvv} onChange={(e) => setCard({ ...card, cvv: e.target.value })}
                className="ml-input" inputMode="numeric" maxLength={4} placeholder="123"/>
            </Field>
          </div>

          {err && (
            <div style={{ marginTop: 12, padding: '10px 12px', borderRadius: 8, background: 'oklch(95% 0.05 25)', color: 'oklch(40% 0.14 25)', fontSize: 13 }}>
              {err}
            </div>
          )}

          <button onClick={submit} disabled={busy || !consult}
            className="ml-btn ml-btn--primary" style={{ marginTop: 18, padding: '12px 22px', width: '100%', justifyContent: 'center' }}>
            {busy ? 'Processing…' : <><I.lock size={13}/> Pay ₹{total} &amp; confirm</>}
          </button>
          <div className="ml-muted" style={{ fontSize: 11.5, marginTop: 10, textAlign: 'center' }}>
            🔒 Mock gateway · no real charge · use any card number for the demo.
          </div>
        </div>

        {/* Right: order summary */}
        <div className="ml-card" style={{ padding: 24, alignSelf: 'start' }}>
          <div className="ml-label" style={{ marginBottom: 14 }}>ORDER SUMMARY</div>

          {consult ? (
            <>
              <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 16 }}>
                <div className="ml-avatar" style={{
                  width: 52, height: 52, borderRadius: 12, fontSize: 18,
                  background: TONE_BG[doc.tone], color: TONE_FG[doc.tone],
                }}>{doc.avatar}</div>
                <div>
                  <div style={{ fontFamily: 'var(--display)', fontSize: 16, fontWeight: 500 }}>{doc.n}</div>
                  <div className="ml-muted" style={{ fontSize: 12 }}>{doc.spec}</div>
                </div>
              </div>

              <Row label="Visit ID" value={<span style={{ fontFamily: 'var(--mono)', fontSize: 12 }}>{consult.id}</span>}/>
              <Row label="Date &amp; time" value={`${consult.date} · ${consult.time}`}/>
              <Row label="Mode" value={consult.mode === 'chat' ? 'Chat consult' : (consult.mode === 'audio' ? 'Audio consult' : 'Video consult')}/>
              <Row label="Reason" value={consult.reason || 'Dental consultation'}/>

              <hr className="ml-hr" style={{ margin: '14px 0' }}/>

              <Row label="Consultation fee" value={`₹${fee}`}/>
              <Row label="Platform tax" value={`₹${tax}`}/>
              <Row label={<span style={{ fontWeight: 600, color: 'var(--ink)' }}>Total</span>}
                   value={<span style={{ fontWeight: 600, color: 'var(--ink)', fontSize: 16 }}>₹{total}</span>}/>

              <div style={{ marginTop: 16, padding: 12, borderRadius: 10, background: 'oklch(96% 0.04 165)', fontSize: 12, color: 'oklch(35% 0.10 165)', lineHeight: 1.5 }}>
                <strong>Free follow-up:</strong> Once you pay, you can book a follow-up consultation
                with {doc.n.split(' ').slice(0, 2).join(' ')} within the next 7 days at no extra cost.
              </div>
            </>
          ) : (
            <div className="ml-muted" style={{ fontSize: 13 }}>
              {emergency ? 'Preparing your 24/7 emergency consult with Dr. Shivani...' : 'No consult selected.'}
            </div>
          )}
        </div>
      </div>
    </PortalShell>
  );
}

function Field({ label, children }) {
  return (
    <label style={{ display: 'block', marginBottom: 12 }}>
      <div className="ml-label" style={{ marginBottom: 6, fontSize: 11 }}>{label.toUpperCase()}</div>
      {children}
    </label>
  );
}
function Row({ label, value }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 13.5, color: 'var(--ink-2)' }}>
      <span>{label}</span>
      <span style={{ color: 'var(--ink)', textAlign: 'right' }}>{value}</span>
    </div>
  );
}

Object.assign(window, { PayCheckout });
