/* ClinicBooking.jsx — 4-step partner clinic booking (high-risk tier).
   Choose clinic → select time → confirm referral → booked.
   Clinics are real/plausible Kano institutions (Fatima's city). On confirm, the
   booking is lifted to the controller (onComplete) so the dashboard hero + Care
   timeline reflect the booked state. */

const CLINICS = [
  { id: 'akth', name: 'Aminu Kano Teaching Hospital — Dental Wing', addr: 'Zaria Road', dist: '3.2 km away', rating: '4.7', services: ['Periodontal treatment', 'Diabetes management', 'On-site lab'] },
  { id: 'mmsh', name: 'Murtala Muhammad Specialist Hospital', addr: 'Kofar Mata Road', dist: '5.8 km away', rating: '4.5', services: ['Periodontal treatment', 'Internal medicine', 'Cardiology consult'] },
  { id: 'premier', name: 'Kano Premier Dental Clinic', addr: 'Bompai Road', dist: '2.1 km away', rating: '4.8', services: ['Periodontal treatment', 'Restorative dentistry', 'X-ray on-site'] },
];
const TIMES = ['9:00 AM', '11:30 AM', '2:00 PM', '4:00 PM'];
const WD = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const MO = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

function buildDates() {
  const base = new Date();
  const out = [];
  for (let i = 0; i < 7; i++) {
    const dt = new Date(base); dt.setDate(base.getDate() + i);
    out.push({
      id: 'd' + i,
      chip: i === 0 ? 'Today' : i === 1 ? 'Tomorrow' : WD[dt.getDay()],
      day: dt.getDate(), mon: MO[dt.getMonth()],
      full: i === 0 ? 'today' : i === 1 ? 'tomorrow' : `${WD[dt.getDay()]} ${dt.getDate()} ${MO[dt.getMonth()]}`,
    });
  }
  return out;
}

// ── Step 1 — clinic selection ────────────────────────────────────────────
function ClinicSelect({ value, onSelect, onBack, onContinue }) {
  return (
    <Screen footer={
      <div style={{ padding: '12px var(--gutter-screen) 30px', background: 'linear-gradient(180deg, rgba(250,248,245,0) 0%, var(--bg) 26%)' }}>
        <Button full variant="primary" disabled={!value} onClick={onContinue}>Continue</Button>
      </div>
    }>
      <HNav title="Choose a clinic" onBack={onBack}/>
      <div style={{ padding: '8px var(--gutter-screen) 0' }}>
        <h1 style={{ font: 'var(--type-display-m)', color: 'var(--fg-1)', letterSpacing: 'var(--tracking-tight)', marginBottom: 8 }}>In-person care for periodontal treatment.</h1>
        <p style={{ font: 'var(--type-body)', color: 'var(--fg-2)', textWrap: 'pretty', marginBottom: 20 }}>
          We’ve found 3 partner clinics near you in Kano with both medical and dental services on-site.
        </p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, paddingBottom: 110 }}>
          {CLINICS.map(c => {
            const sel = value === c.id;
            return (
              <div key={c.id} onClick={() => onSelect(c.id)} style={{
                cursor: 'pointer', background: sel ? 'var(--amber-50)' : '#fff',
                border: sel ? '2px solid var(--amber-500)' : '1px solid var(--border-default)',
                borderRadius: 'var(--radius-m)', padding: sel ? 15 : 16, boxShadow: 'var(--shadow-xs)',
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
                  <div style={{ font: 'var(--type-h3)', color: 'var(--fg-1)', textWrap: 'pretty' }}>{c.name}</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 3, font: '600 13px/1 var(--font-sans)', color: 'var(--amber-700)', flexShrink: 0 }}>
                    <Icon name="star" size={13}/> {c.rating}
                  </div>
                </div>
                <div style={{ font: 'var(--type-body-s)', color: 'var(--fg-3)', marginTop: 3 }}>{c.addr} · {c.dist}</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 10 }}>
                  {c.services.map(s => (
                    <span key={s} style={{ font: 'var(--type-caption)', color: 'var(--fg-2)', background: sel ? '#fff' : 'var(--stone-100)', padding: '3px 8px', borderRadius: 'var(--radius-pill)' }}>{s}</span>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </Screen>
  );
}

// ── Step 2 — time slot ─────────────────────────────────────────────────
function SlotSelect({ clinic, dates, dateId, slot, onPickDate, onPickSlot, onBack, onContinue }) {
  return (
    <Screen footer={
      <div style={{ padding: '12px var(--gutter-screen) 30px', background: 'linear-gradient(180deg, rgba(250,248,245,0) 0%, var(--bg) 26%)' }}>
        <Button full variant="primary" disabled={!slot} onClick={onContinue}>Continue</Button>
      </div>
    }>
      <HNav title={clinic ? clinic.name : 'Select a time'} onBack={onBack}/>
      <div style={{ padding: '8px var(--gutter-screen) 0' }}>
        <h1 style={{ font: 'var(--type-display-m)', color: 'var(--fg-1)', letterSpacing: 'var(--tracking-tight)', marginBottom: 6 }}>Select your preferred time.</h1>
        <p style={{ font: 'var(--type-body)', color: 'var(--fg-2)', marginBottom: 20 }}>Within the next 7 days.</p>

        {/* date chips */}
        <div style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 6, marginBottom: 22, WebkitOverflowScrolling: 'touch' }}>
          {dates.map(dt => {
            const sel = dateId === dt.id;
            return (
              <button key={dt.id} onClick={() => onPickDate(dt.id)} style={{
                flexShrink: 0, minWidth: 60, padding: '10px 8px', borderRadius: 'var(--radius-pill)', cursor: 'pointer',
                border: sel ? '0' : '1px solid var(--border-default)', background: sel ? 'var(--amber-500)' : '#fff',
                color: sel ? '#fff' : 'var(--fg-2)', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
              }}>
                <span style={{ font: 'var(--type-caption)', opacity: 0.9, whiteSpace: 'nowrap' }}>{dt.chip}</span>
                <span style={{ font: '600 15px/1 var(--font-sans)', whiteSpace: 'nowrap' }}>{dt.day} {dt.mon}</span>
              </button>
            );
          })}
        </div>

        {/* time slots */}
        <div className="overline" style={{ marginBottom: 12 }}>Available times</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, paddingBottom: 110 }}>
          {TIMES.map(t => (
            <RadioOption key={t} label={t} selected={slot === t} onClick={() => onPickSlot(t)}/>
          ))}
        </div>
      </div>
    </Screen>
  );
}

// ── Step 3 — referral confirmation ──────────────────────────────────────
function ReferralConfirm({ clinic, dateLabel, slot, onBack, onConfirm }) {
  const cap = dateLabel.charAt(0).toUpperCase() + dateLabel.slice(1);
  return (
    <Screen footer={
      <div style={{ padding: '12px var(--gutter-screen) 30px', background: 'linear-gradient(180deg, rgba(250,248,245,0) 0%, var(--bg) 26%)' }}>
        <Button full variant="primary" glow onClick={onConfirm}>Confirm booking</Button>
      </div>
    }>
      <HNav title="Confirm referral" onBack={onBack}/>
      <div style={{ padding: '8px var(--gutter-screen) 0' }}>
        <h1 style={{ font: 'var(--type-display-m)', color: 'var(--fg-1)', letterSpacing: 'var(--tracking-tight)', marginBottom: 18 }}>You’re booking:</h1>

        <Card padding={20} style={{ marginBottom: 16 }}>
          <div style={{ font: 'var(--type-h3)', color: 'var(--fg-1)', marginBottom: 12, textWrap: 'pretty' }}>{clinic.name}</div>
          <Row icon="map-pin" label={`${clinic.addr} · ${clinic.dist}`}/>
          <Row icon="calendar" label={cap} style={{ marginTop: 10 }}/>
          <Row icon="clock" label={slot} style={{ marginTop: 10 }}/>
          <div style={{ height: 1, background: 'var(--border-subtle)', margin: '14px 0' }}/>
          <div style={{ font: 'var(--type-body-s)', color: 'var(--fg-3)', marginBottom: 8 }}>To be addressed</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {['Periodontal treatment', 'Diabetes coordination'].map(s => (
              <span key={s} style={{ font: 'var(--type-caption)', color: 'var(--fg-2)', background: 'var(--stone-100)', padding: '3px 8px', borderRadius: 'var(--radius-pill)' }}>{s}</span>
            ))}
          </div>
        </Card>

        {/* Referral package — the trust beat */}
        <div style={{ background: 'var(--sage-50)', borderRadius: 'var(--radius-m)', padding: 20, marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
            <div style={{ width: 36, height: 36, borderRadius: 'var(--radius-s)', background: '#fff', color: 'var(--sage-600)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="file-text" size={20}/></div>
            <div style={{ font: 'var(--type-h3)', color: 'var(--sage-700)' }}>What we’re sending ahead</div>
          </div>
          <p style={{ font: 'var(--type-body)', color: 'var(--fg-2)', textWrap: 'pretty' }}>
            Your screening results, today’s video consultation notes, your active prescription, and your health questionnaire responses will be shared with the clinic ahead of your visit. They’ll have everything they need — you won’t have to repeat your story.
          </p>
        </div>
        <div className="overline" style={{ color: 'var(--fg-3)', display: 'flex', alignItems: 'center', gap: 6, paddingLeft: 2 }}>
          <Icon name="lock" size={12}/> Shared securely. HIPAA compliant.
        </div>
        <div style={{ height: 120 }}/>
      </div>
    </Screen>
  );
}

function Row({ icon, label, style = {} }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, ...style }}>
      <Icon name={icon} size={18} color="var(--fg-3)"/>
      <div style={{ font: 'var(--type-body)', color: 'var(--fg-1)', textWrap: 'pretty' }}>{label}</div>
    </div>
  );
}

// ── Step 4 — confirmation ────────────────────────────────────────────────
function ClinicBooked({ clinic, dateLabel, slot, onDone, onCalendarSoon }) {
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => { const t = setTimeout(() => setShown(true), 30); return () => clearTimeout(t); }, []);
  return (
    <Screen footer={
      <div style={{ padding: '12px var(--gutter-screen) 38px' }}>
        <Button full variant="primary" onClick={onDone}>Back to care plan</Button>
      </div>
    }>
      <div style={{ padding: '0 var(--gutter-screen)', flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', minHeight: 560 }}>
        <div style={{ width: 92, height: 92, borderRadius: '50%', background: 'var(--sage-50)', color: 'var(--sage-600)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 26, transform: shown ? 'scale(1)' : 'scale(0.9)', opacity: shown ? 1 : 0, transition: 'transform var(--dur-reveal) var(--ease-out), opacity var(--dur-reveal) var(--ease-out)' }}>
          <Icon name="check" size={42} strokeWidth={2.4}/>
        </div>
        <h1 style={{ font: 'var(--type-display-m)', color: 'var(--fg-1)', letterSpacing: 'var(--tracking-tight)', marginBottom: 12 }}>Booked.</h1>
        <p style={{ font: 'var(--type-body-l)', color: 'var(--fg-2)', maxWidth: 320, textWrap: 'pretty', marginBottom: 22 }}>
          Your appointment at {clinic.name} is confirmed for {dateLabel} at {slot}. They’ll see you for periodontal treatment and to check in on your diabetes management.
        </p>
        <div style={{ width: '100%', background: '#fff', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-m)', padding: 18, boxShadow: 'var(--shadow-xs)', display: 'flex', gap: 12, alignItems: 'flex-start', textAlign: 'left', marginBottom: 16 }}>
          <div style={{ color: 'var(--sage-600)', flexShrink: 0, marginTop: 1 }}><Icon name="shopping-bag" size={20}/></div>
          <div>
            <div style={{ font: 'var(--type-h3)', color: 'var(--fg-1)', marginBottom: 3 }}>What to bring</div>
            <div style={{ font: 'var(--type-body)', color: 'var(--fg-2)', textWrap: 'pretty' }}>Just yourself. We’ve sent everything else ahead.</div>
          </div>
        </div>
        <Button variant="secondary" leftIcon="calendar" onClick={onCalendarSoon}>Add to calendar</Button>
      </div>
    </Screen>
  );
}

// ── Flow controller ──────────────────────────────────────────────────────
function ClinicBooking({ onExit, onDone, onComplete, onCalendarSoon, initStep = 0 }) {
  const [step, setStep] = React.useState(initStep);
  const [clinicId, setClinicId] = React.useState(initStep > 0 ? CLINICS[0].id : null);
  const dates = React.useMemo(buildDates, []);
  const [dateId, setDateId] = React.useState('d3'); // default 3 days out
  const [slot, setSlot] = React.useState(initStep > 1 ? '11:30 AM' : null);
  const clinic = CLINICS.find(c => c.id === clinicId);
  const dt = dates.find(x => x.id === dateId);
  const dateLabel = dt ? dt.full : '';

  const back = () => { if (step === 0) onExit(); else setStep(s => s - 1); };
  const confirm = () => {
    if (onComplete && clinic) onComplete({ clinicName: clinic.name, dateLabel, slot, dateShort: dt ? `${dt.day} ${dt.mon}` : '' });
    setStep(3);
  };

  if (step === 0) return <ClinicSelect value={clinicId} onSelect={setClinicId} onBack={back} onContinue={() => setStep(1)}/>;
  if (step === 1) return <SlotSelect clinic={clinic} dates={dates} dateId={dateId} slot={slot} onPickDate={setDateId} onPickSlot={setSlot} onBack={back} onContinue={() => setStep(2)}/>;
  if (step === 2) return <ReferralConfirm clinic={clinic} dateLabel={dateLabel} slot={slot} onBack={back} onConfirm={confirm}/>;
  return <ClinicBooked clinic={clinic} dateLabel={dateLabel} slot={slot} onDone={onDone} onCalendarSoon={onCalendarSoon}/>;
}

window.MunaClinicBooking = { ClinicBooking };
