// screens-schedule.jsx — ScheduleScreen, ScheduledScreen, RecruiterScreen
const { useState: useStateS, useMemo } = React;

const TZS = [
  'Asia/Kolkata (GMT+5:30)', 'Asia/Singapore (GMT+8)', 'Europe/London (GMT+1)',
  'America/New_York (GMT−4)', 'America/Los_Angeles (GMT−7)',
];
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const DOW = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
const SLOTS = ['09:00', '09:30', '10:00', '11:00', '11:30', '13:00', '14:00', '14:30', '15:30', '16:00', '16:30', '17:00'];

function Calendar({ value, onPick }) {
  const today = new Date(); today.setHours(0,0,0,0);
  const minDate = new Date(today); minDate.setDate(today.getDate() + 1);
  const [view, setView] = useStateS({ y: minDate.getFullYear(), m: minDate.getMonth() });
  const first = new Date(view.y, view.m, 1);
  const startDow = first.getDay();
  const days = new Date(view.y, view.m + 1, 0).getDate();
  const canPrev = !(view.y === 2026 && view.m <= 4);
  const cells = [];
  for (let i = 0; i < startDow; i++) cells.push(null);
  for (let d = 1; d <= days; d++) cells.push(d);

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <div style={{ fontSize: 15.5, fontWeight: 700, color: 'var(--text)' }}>{MONTHS[view.m]} {view.y}</div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button onClick={() => canPrev && setView((v) => ({ y: v.m === 0 ? v.y - 1 : v.y, m: v.m === 0 ? 11 : v.m - 1 }))}
            style={navBtn(!canPrev)}><Icon name="arrowLeft" size={16} stroke={2.4} /></button>
          <button onClick={() => setView((v) => ({ y: v.m === 11 ? v.y + 1 : v.y, m: v.m === 11 ? 0 : v.m + 1 }))}
            style={navBtn(false)}><Icon name="arrowRight" size={16} stroke={2.4} /></button>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 4, marginBottom: 4 }}>
        {DOW.map((d, i) => <div key={i} style={{ textAlign: 'center', fontSize: 11.5, fontWeight: 700, color: 'var(--text-faint)', padding: '4px 0' }}>{d}</div>)}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 4 }}>
        {cells.map((d, i) => {
          if (!d) return <div key={i} />;
          const date = new Date(view.y, view.m, d);
          const dow = date.getDay();
          const disabled = date < minDate || dow === 0 || dow === 6;
          const selected = value && value.y === view.y && value.m === view.m && value.d === d;
          return (
            <button key={i} disabled={disabled} onClick={() => onPick({ y: view.y, m: view.m, d })}
              style={{
                aspectRatio: '1', borderRadius: 10, border: '1px solid transparent', fontFamily: 'var(--font)',
                fontSize: 14, fontWeight: selected ? 700 : 500, cursor: disabled ? 'default' : 'pointer',
                background: selected ? 'var(--accent)' : 'transparent',
                color: selected ? 'var(--accent-fg)' : (disabled ? 'var(--text-faint)' : 'var(--text)'),
                opacity: disabled ? 0.35 : 1, transition: 'all .12s',
              }}
              onMouseEnter={(e) => { if (!disabled && !selected) e.currentTarget.style.background = 'var(--surface-2)'; }}
              onMouseLeave={(e) => { if (!selected) e.currentTarget.style.background = 'transparent'; }}>
              {d}
            </button>
          );
        })}
      </div>
    </div>
  );
}
function navBtn(disabled) {
  return {
    width: 32, height: 32, borderRadius: 9, border: '1px solid var(--border)', background: 'var(--surface)',
    color: disabled ? 'var(--text-faint)' : 'var(--text-dim)', display: 'grid', placeItems: 'center',
    cursor: disabled ? 'default' : 'pointer', opacity: disabled ? 0.4 : 1,
  };
}

function getFirstAvailableDate() {
  const d = new Date(); d.setHours(0,0,0,0); d.setDate(d.getDate() + 1);
  while (d.getDay() === 0 || d.getDay() === 6) d.setDate(d.getDate() + 1);
  return { y: d.getFullYear(), m: d.getMonth(), d: d.getDate() };
}

function ScheduleScreen({ go, cfg, attempts, onConfirm }) {
  const [date, setDate] = useStateS(() => getFirstAvailableDate());
  const [slot, setSlot] = useStateS(SLOTS[0]);
  const [tz, setTz] = useStateS(TZS[0]);
  const [saving, setSaving] = useStateS(false);

  const dateObj = date ? new Date(date.y, date.m, date.d) : null;
  const dayName  = dateObj ? ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][dateObj.getDay()] : null;
  const dateLabel = dateObj ? `${dayName}, ${MONTHS[date.m].slice(0,3)} ${date.d}` : null;
  // Header label for slots panel — "Mon, Jun 1" style matching design
  const slotsHeader = dateObj
    ? `${dayName}, ${MONTHS[date.m].slice(0,3)} ${date.d}`
    : null;

  return (
    <div style={{ width: '100%' }}>
      <TopBar right={null} />
      <Screen max={840} style={{ padding: '12px 24px 60px' }}>
        <div style={{ textAlign: 'center', marginBottom: 6, width: '100%' }}>
          {attempts > 0 && <div style={{ marginBottom: 12 }}><StatusPill status="warn" icon="refresh">Reschedule · attempt {attempts + 1} of {cfg.maxReschedule}</StatusPill></div>}
          <h1 style={{ fontSize: 'clamp(24px,4vw,32px)', fontFamily: 'var(--font-display)', fontWeight: 500, letterSpacing: '-0.01em', width: '100%', color: 'var(--text)', margin: 0 }}>Pick a time that works</h1>
          <p style={{ fontSize: 16, color: 'var(--text-dim)', marginTop: 10, marginBottom: 26 }}>Choose a date and slot. We'll email you an updated interview link.</p>
        </div>

        <Card pad={0} style={{ width: '100%', overflow: 'hidden' }}>
          <div className="sched-grid" style={{ display: 'grid', gridTemplateColumns: 'minmax(280px, 1fr) minmax(220px, 0.85fr)' }}>
            {/* Calendar side */}
            <div style={{ padding: 24, borderRight: '1px solid var(--border)' }}>
              {/* Globe icon + timezone — matches design */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16, border: '1px solid var(--border)', borderRadius: 10, padding: '8px 12px', background: 'var(--surface-2)' }}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--text-dim)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{flexShrink:0}}>
                  <circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/>
                  <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
                </svg>
                <select value={tz} onChange={e => setTz(e.target.value)} style={{
                  flex: 1, appearance: 'none', border: 'none', background: 'transparent',
                  fontSize: 13, fontFamily: 'var(--font)', color: 'var(--text)', fontWeight: 500, cursor: 'pointer', outline: 'none',
                }}>
                  {TZS.map(t => <option key={t}>{t}</option>)}
                </select>
              </div>
              <Calendar value={date} onPick={d => { setDate(d); setSlot(null); }} />
            </div>

            {/* Slots side */}
            <div style={{ padding: 24, display: 'flex', flexDirection: 'column', minHeight: 360 }}>
              {/* Header matches design: "Mon, Jun 1" in bold + calendar icon */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 4 }}>
                {slotsHeader && (
                  <div style={{ width: 18, height: 18, borderRadius: 5, background: 'var(--accent-soft)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                    <Icon name="calendar" size={11} stroke={2.5} style={{ color: 'var(--accent)' }} />
                  </div>
                )}
                <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>
                  {slotsHeader || 'Select a date'}
                </div>
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--text-faint)', marginBottom: 14 }}>
                {date ? 'Available slots — tap to select' : 'Pick a day to see times'}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, overflowY: 'auto', flex: 1 }}>
                {SLOTS.map(s => (
                  <button key={s} onClick={() => setSlot(s)} style={{
                    padding: '12px 8px', borderRadius: 10, fontFamily: 'var(--font)', fontSize: 14, fontWeight: 600, cursor: 'pointer',
                    border: `1px solid ${slot === s ? 'var(--accent)' : 'var(--border)'}`,
                    background: slot === s ? 'var(--accent)' : 'var(--surface)',
                    color: slot === s ? 'var(--accent-fg)' : 'var(--text)', transition: 'all .12s',
                  }}>{s}</button>
                ))}
              </div>
            </div>
          </div>
        </Card>

        <div style={{ display: 'flex', gap: 12, marginTop: 24, width: '100%', maxWidth: 460 }}>
          <Button variant="ghost" icon="arrowLeft" onClick={() => go(attempts > 0 ? 'scheduled' : 'landing')}>Back</Button>
          <Button full disabled={!date || !slot || saving} iconRight="check"
            onClick={async () => {
              setSaving(true);
              const [h, m] = slot.split(':').map(Number);
              const dt = new Date(date.y, date.m, date.d, h, m, 0);
              if (cfg.interviewToken) {
                try {
                  await fetch(`${API_BASE}/api/v1/public/interview/${cfg.interviewToken}/schedule-request`, {
                    method: 'POST', headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ scheduled_iso: dt.toISOString(), timezone_label: tz }),
                  });
                } catch(_) {}
              }
              setSaving(false);
              onConfirm({ dateLabel, time: slot, tz });
            }}>
            {saving ? 'Confirming…' : 'Confirm booking'}
          </Button>
        </div>
      </Screen>
    </div>
  );
}

function CopyLink({ url }) {
  const [copied, setCopied] = useStateS(false);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 11, padding: '6px 6px 6px 14px' }}>
      <Icon name="lock" size={14} stroke={2} style={{ color: 'var(--text-faint)', flexShrink: 0 }} />
      <span style={{ flex: 1, fontSize: 13, color: 'var(--text-dim)', fontFamily: 'ui-monospace, monospace', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{url}</span>
      <Button size="sm" variant={copied ? 'secondary' : 'primary'} icon={copied ? 'check' : 'copy'}
        onClick={() => { setCopied(true); setTimeout(() => setCopied(false), 1800); }}>{copied ? 'Copied' : 'Copy'}</Button>
    </div>
  );
}

function ScheduledScreen({ go, cfg, slot, attempts, onReschedule }) {
  const canReschedule = attempts < cfg.maxReschedule;
  return (
    <div style={{ width: '100%' }}>
      <TopBar right={<StatusPill status="good" icon="check">Booked</StatusPill>} />
      <Screen max={560} style={{ padding: '24px 24px 60px' }}>
        <div style={{
          width: 70, height: 70, borderRadius: '50%', background: 'var(--success-soft)', color: 'var(--success)',
          display: 'grid', placeItems: 'center', marginBottom: 22, animation: 'popIn .4s cubic-bezier(.2,.8,.3,1.4)',
        }}>
          <Icon name="check" size={36} stroke={2.6} />
        </div>
        <h1 style={{ fontSize: 'clamp(26px,4vw,32px)', fontFamily: 'var(--font-display)', fontWeight: 500, letterSpacing: '-0.01em', width: '100%', color: 'var(--text)', margin: 0, textAlign: 'center' }}>You're all set</h1>
        <p style={{ fontSize: 16.5, color: 'var(--text-dim)', marginTop: 12, marginBottom: 26, textAlign: 'center', textWrap: 'pretty' }}>
          Your interview is confirmed. We've sent the updated link to <strong style={{ color: 'var(--text)' }}>{cfg.candidate.email}</strong>.
        </p>

        <Card style={{ width: '100%' }} pad={22}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{ textAlign: 'center', background: 'var(--accent-soft)', borderRadius: 13, padding: '12px 16px', minWidth: 76 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--accent)', textTransform: 'uppercase' }}>{slot.dateLabel.split(',')[0]}</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 500, color: 'var(--text)', lineHeight: 1 }}>{slot.dateLabel.split(' ').pop()}</div>
              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-dim)' }}>{slot.dateLabel.split(' ')[1]}</div>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 19, fontWeight: 700, color: 'var(--text)' }}>{slot.time}</div>
              <div style={{ fontSize: 13.5, color: 'var(--text-dim)', marginTop: 2 }}>{slot.tz}</div>
              <div style={{ fontSize: 13.5, color: 'var(--text-faint)', marginTop: 8 }}>{cfg.role} · {cfg.duration} min</div>
            </div>
          </div>
          <div style={{ height: 1, background: 'var(--border)', margin: '18px 0' }} />
          <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.03em', marginBottom: 10 }}>Your updated interview link</div>
          <CopyLink url={`interview.simplai.ai/s/${cfg.candidate.first.toLowerCase()}-9f3a2`} />
          <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
            <Button variant="secondary" size="sm" icon="calendar" full>Add to calendar</Button>
            <Button variant="secondary" size="sm" icon="mail" full>Email me details</Button>
          </div>
        </Card>

        <div style={{ width: '100%', marginTop: 18, padding: 16, background: 'var(--surface-2)', borderRadius: 13, border: '1px solid var(--border)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>Need a different time?</div>
              <div style={{ fontSize: 12.5, color: 'var(--text-faint)', marginTop: 2 }}>
                {canReschedule ? `You can reschedule ${cfg.maxReschedule - attempts} more time${cfg.maxReschedule - attempts > 1 ? 's' : ''}.` : 'You\'ve used all reschedule attempts.'}
              </div>
            </div>
            <Button size="sm" variant={canReschedule ? 'secondary' : 'ghost'} icon="refresh"
              onClick={() => canReschedule ? go('schedule') : go('recruiter')}>
              {canReschedule ? 'Reschedule' : 'Contact recruiter'}
            </Button>
          </div>
        </div>

        {/* "Actually, start now instead" — subtle text link matching the design */}
        <div style={{ marginTop: 22, textAlign: 'center' }}>
          <button onClick={() => go('check')} style={{
            background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--font)',
            fontSize: 14, color: 'var(--text-dim)', display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
            Actually, start now instead
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
          </button>
        </div>
      </Screen>
    </div>
  );
}

function RecruiterScreen({ go, cfg }) {
  return (
    <div style={{ width: '100%' }}>
      <TopBar right={null} />
      <Screen max={520} style={{ padding: '24px 24px 60px' }}>
        <div style={{ width: 70, height: 70, borderRadius: '50%', background: 'var(--warn-soft)', color: 'var(--warn)', display: 'grid', placeItems: 'center', marginBottom: 22 }}>
          <Icon name="user" size={34} stroke={2} />
        </div>
        <h1 style={{ fontSize: 'clamp(24px,4vw,30px)', fontFamily: 'var(--font-display)', fontWeight: 500, letterSpacing: '-0.01em', width: '100%', color: 'var(--text)', margin: 0, textAlign: 'center', textWrap: 'balance' }}>Let's find a time together</h1>
        <p style={{ fontSize: 16, color: 'var(--text-dim)', marginTop: 12, marginBottom: 26, textAlign: 'center', textWrap: 'pretty' }}>
          You've reached the limit of {cfg.maxReschedule} self-service reschedules. No problem — your recruiter will personally help you book a slot that works.
        </p>
        <Card style={{ width: '100%' }} pad={22}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 52, height: 52, borderRadius: '50%', background: 'var(--accent-soft)', color: 'var(--accent)', display: 'grid', placeItems: 'center', fontSize: 19, fontWeight: 700 }}>
              {cfg.recruiter.name.split(' ').map((n) => n[0]).join('')}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 16.5, fontWeight: 700, color: 'var(--text)' }}>{cfg.recruiter.name}</div>
              <div style={{ fontSize: 13.5, color: 'var(--text-faint)' }}>{cfg.recruiter.title}</div>
            </div>
          </div>
          <div style={{ height: 1, background: 'var(--border)', margin: '18px 0' }} />
          <a href={`mailto:${cfg.recruiter.email}?subject=Interview rescheduling — ${cfg.role}`} style={{ textDecoration: 'none' }}>
            <Button full icon="mail">Email {cfg.recruiter.email.split('@')[0]}</Button>
          </a>
          <div style={{ textAlign: 'center', marginTop: 12, fontSize: 13.5, color: 'var(--text-dim)' }}>
            or write directly to <span style={{ color: 'var(--accent)', fontWeight: 600 }}>{cfg.recruiter.email}</span>
          </div>
        </Card>
        <div style={{ marginTop: 20 }}>
          <Button variant="ghost" icon="arrowLeft" onClick={() => go('scheduled')}>Back to my booking</Button>
        </div>
      </Screen>
    </div>
  );
}

Object.assign(window, { ScheduleScreen, ScheduledScreen, RecruiterScreen });
