// web-screens.jsx — Responsive web + mobile screens, flow: kode karyawan → sukses + zoom link

// ─────────────────────────────────────────────────────────
// Shared: Top bar (responsif)
// ─────────────────────────────────────────────────────────
function TopBar({ mode, onSwitchMode }) {
  return (
    <div style={{
      background: '#fff',
      borderBottom: `1px solid ${TOKENS.line}`,
      padding: '12px 20px',
      display: 'flex', alignItems: 'center', gap: 12,
      position: 'sticky', top: 0, zIndex: 10,
    }}>
      <img src="assets/LogoJCG.png" alt="The Jakarta Consulting Group" style={{ height: 44, width: 'auto', display: 'block', flexShrink: 0 }}/>
      <div style={{ flex: 1, minWidth: 0, paddingLeft: 4, borderLeft: `1px solid ${TOKENS.line}`, marginLeft: 4 }}>
        <div style={{ fontSize: 10, fontWeight: 600, color: TOKENS.slate, letterSpacing: 1.4, textTransform: 'uppercase' }}>Sistem Absensi</div>
        <div style={{ fontSize: 14, fontWeight: 700, color: TOKENS.navyInk, letterSpacing: -0.1, lineHeight: 1.1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Meeting Zoom</div>
      </div>
      <div style={{ display: 'flex', background: TOKENS.bg, padding: 3, borderRadius: 100, gap: 2 }}>
        {['peserta', 'admin'].map(m => (
          <button key={m} onClick={() => onSwitchMode(m)} style={{
            padding: '6px 12px', borderRadius: 100, border: 'none',
            background: mode === m ? TOKENS.navy : 'transparent',
            color: mode === m ? '#fff' : TOKENS.slate,
            fontSize: 11, fontWeight: 600, cursor: 'pointer',
            textTransform: 'capitalize', letterSpacing: 0.2,
          }}>{m}</button>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Meeting hero — used on input + success screens
// ─────────────────────────────────────────────────────────
function MeetingHero({ meeting, compact = false }) {
  return (
    <div style={{
      background: `linear-gradient(135deg, ${TOKENS.navyInk} 0%, ${TOKENS.navy} 55%, ${TOKENS.navy2} 100%)`,
      color: '#fff', borderRadius: 18, padding: compact ? 20 : 26,
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ position: 'absolute', top: -60, right: -60, width: 220, height: 220, borderRadius: 120, background: 'rgba(45,140,255,0.13)' }}/>
      <div style={{ position: 'absolute', bottom: -40, left: -40, width: 180, height: 180, borderRadius: 120, background: 'rgba(45,140,255,0.08)' }}/>
      <div style={{ position: 'relative' }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 10, fontWeight: 600, letterSpacing: 1.4, padding: '4px 10px', background: 'rgba(255,255,255,0.12)', borderRadius: 100, textTransform: 'uppercase' }}>
          <span style={{ width: 6, height: 6, borderRadius: 3, background: TOKENS.zoomBlue, boxShadow: `0 0 8px ${TOKENS.zoomBlue}` }}/>
          Zoom · {meeting.sessionLabel}
        </div>
        <div style={{ fontSize: compact ? 18 : 22, fontWeight: 700, marginTop: 10, letterSpacing: -0.4, lineHeight: 1.25, maxWidth: 480 }}>
          {meeting.title}
        </div>
        <div style={{ display: 'flex', gap: 18, marginTop: 14, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, opacity: 0.92 }}>
            <Icon.Calendar size={14} color="rgba(255,255,255,0.85)"/><span>{meeting.date}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, opacity: 0.92 }}>
            <Icon.Clock size={14} color="rgba(255,255,255,0.85)"/><span>{meeting.time}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, opacity: 0.92 }}>
            <Icon.User size={14} color="rgba(255,255,255,0.85)"/><span>{meeting.host}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// 1. Input screen — masukkan kode karyawan
// ─────────────────────────────────────────────────────────
// ▼ DIUBAH: tambah prop `sessionId` untuk kirim ke Supabase
function InputScreen({ meeting, sessionId, onSuccess }) {
  const [code, setCode] = React.useState('');
  const [error, setError] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [suggest, setSuggest] = React.useState(false);
  const inputRef = React.useRef(null);

  // Format as user types: dd.dd.dd.dddd
  const formatCode = (raw) => {
    const digits = raw.replace(/\D/g, '').slice(0, 10);
    const parts = [];
    if (digits.length > 0) parts.push(digits.slice(0, 2));
    if (digits.length > 2) parts.push(digits.slice(2, 4));
    if (digits.length > 4) parts.push(digits.slice(4, 6));
    if (digits.length > 6) parts.push(digits.slice(6, 10));
    return parts.join('.');
  };

  const onChange = (e) => {
    const v = formatCode(e.target.value);
    setCode(v);
    setError(null);
  };

  const suggestions = React.useMemo(() => {
    if (!code || code.length < 2) return [];
    return window.PARTICIPANTS.filter(p => p.empId.startsWith(code)).slice(0, 4);
  }, [code]);

  // DIUBAH: async — cek kode → simpan ke Supabase → baru pindah screen
  const submit = async () => {
    setLoading(true);
    setError(null);
    const user = window.PARTICIPANTS.find(p => p.empId === code);
    if (!user) {
      setError('Kode karyawan tidak ditemukan. Periksa kembali atau hubungi admin.');
      setLoading(false);
      return;
    }
    const now = new Date();
    const joinTime = `${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}`;
    try {
      if (sessionId) await window.DB_checkIn(sessionId, user, joinTime);
      onSuccess({ user, joinTime });
    } catch (e) {
      console.error('Check-in error:', e);
      setError('Gagal menyimpan absensi. Periksa koneksi dan coba lagi.');
      setLoading(false);
    }
  };

  React.useEffect(() => {
    if (inputRef.current) inputRef.current.focus();
  }, []);

  return (
    <div style={{ maxWidth: 1080, margin: '0 auto', padding: '32px 20px 60px' }}>
      {/* Mobile: stacked. Desktop: 2-col */}
      <div className="jcg-grid" style={{ display: 'grid', gap: 24 }}>
        <MeetingHero meeting={meeting}/>

        <div style={{
          background: '#fff', borderRadius: 18, padding: 28,
          border: `1px solid ${TOKENS.line}`,
          boxShadow: '0 1px 2px rgba(11,37,69,0.04), 0 8px 32px rgba(11,37,69,0.04)',
        }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: TOKENS.slate, letterSpacing: 1.2, textTransform: 'uppercase' }}>
            Isi untuk Mencatat Kehadiran
          </div>
          <div style={{ fontSize: 22, fontWeight: 700, color: TOKENS.navyInk, letterSpacing: -0.4, marginTop: 6 }}>
            Masukkan Kode Karyawan
          </div>
          <div style={{ fontSize: 13, color: TOKENS.slate, marginTop: 6, lineHeight: 1.5 }}>
            Format: <span className="mono" style={{ color: TOKENS.navy2 }}>NN.NN.NN.NNNN</span> — contoh: <span className="mono" style={{ color: TOKENS.navy2 }}>44.45.13.1929</span>
          </div>

          {/* Input */}
          <div style={{ marginTop: 20 }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10,
              background: error ? TOKENS.dangerSoft : TOKENS.bg,
              border: `1.5px solid ${error ? TOKENS.danger : 'transparent'}`,
              borderRadius: 14, padding: '14px 16px',
              transition: 'border-color .15s, background .15s',
            }}
            onFocus={() => setSuggest(true)}
            >
              <Icon.User size={18} color={TOKENS.slate}/>
              <input
                ref={inputRef}
                className="mono"
                type="text"
                inputMode="numeric"
                value={code}
                onChange={onChange}
                onFocus={() => setSuggest(true)}
                onKeyDown={(e) => { if (e.key === 'Enter' && code.length >= 12) submit(); }}
                placeholder="00.00.00.0000"
                style={{
                  flex: 1, border: 'none', outline: 'none', background: 'transparent',
                  fontSize: 18, letterSpacing: 1, color: TOKENS.navyInk, fontWeight: 500,
                  minWidth: 0,
                }}
              />
              {code && (
                <button onClick={() => { setCode(''); setError(null); inputRef.current?.focus(); }}
                  style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: TOKENS.slate, padding: 4, borderRadius: 6 }}>
                  <Icon.Close size={16}/>
                </button>
              )}
            </div>

            {/* Suggestions */}
            {suggest && suggestions.length > 0 && code !== suggestions[0]?.empId && (
              <div style={{
                marginTop: 8, background: '#fff',
                border: `1px solid ${TOKENS.line}`, borderRadius: 12, overflow: 'hidden',
              }}>
                <div style={{ padding: '8px 12px', fontSize: 10, color: TOKENS.slate, letterSpacing: 0.8, textTransform: 'uppercase', fontWeight: 600, background: TOKENS.bg }}>
                  Saran
                </div>
                {suggestions.map(s => (
                  <div
                    key={s.no}
                    className="jcg-row-press"
                    onClick={() => { setCode(s.empId); setSuggest(false); }}
                    style={{ padding: '8px 12px', display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', borderTop: `1px solid ${TOKENS.line}` }}
                  >
                    <span className="mono" style={{ fontSize: 12, color: TOKENS.navy, fontWeight: 600, minWidth: 110 }}>{s.empId}</span>
                    <span style={{ fontSize: 13, color: TOKENS.navyInk, flex: 1, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.name}</span>
                  </div>
                ))}
              </div>
            )}

            {error && (
              <div className="jcg-fadeup" style={{
                marginTop: 10, padding: '10px 12px', background: TOKENS.dangerSoft,
                color: TOKENS.danger, fontSize: 12, borderRadius: 10, fontWeight: 500,
                display: 'flex', alignItems: 'flex-start', gap: 8,
              }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={TOKENS.danger} strokeWidth="2" style={{ flexShrink: 0, marginTop: 1 }}><circle cx="12" cy="12" r="9"/><path d="M12 7v5M12 16v.5"/></svg>
                {error}
              </div>
            )}
          </div>

          {/* Submit */}
          <div style={{ marginTop: 20 }}>
            <PrimaryBtn onClick={submit} disabled={code.length < 12 || loading}>
              {loading ? (
                <>
                  <div style={{ width: 16, height: 16, borderRadius: 8, border: '2px solid rgba(255,255,255,0.35)', borderTopColor: '#fff', animation: 'jcg-spin 0.8s linear infinite' }}/>
                  Memproses…
                </>
              ) : (
                <>Absen Sekarang <Icon.ChevronRight size={16} color="#fff"/></>
              )}
            </PrimaryBtn>
          </div>

          {/* Help */}
          <div style={{ marginTop: 16, padding: '12px 14px', background: TOKENS.bg, borderRadius: 10, display: 'flex', gap: 10, alignItems: 'flex-start' }}>
            <div style={{
              width: 22, height: 22, borderRadius: 11, background: TOKENS.navy, color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 700, flexShrink: 0,
            }}>i</div>
            <div style={{ fontSize: 12, color: TOKENS.navy2, lineHeight: 1.5 }}>
              Setelah absen tercatat, Anda akan otomatis mendapat link Zoom untuk bergabung ke meeting.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// 2. Success + Zoom link
// ─────────────────────────────────────────────────────────
function SuccessZoomScreen({ user, meeting, joinTime, onDone }) {
  const [copied, setCopied] = React.useState(null);
  const copy = (label) => { setCopied(label); setTimeout(() => setCopied(null), 1400); };
  const zoomUrl = `https://zoom.us/j/${meeting.meetingId.replace(/\s/g,'')}?pwd=${meeting.passcode}`;
  const code = `JCG-0421-${user.no.toString().padStart(3,'0')}`;

  return (
    <div style={{ maxWidth: 1080, margin: '0 auto', padding: '32px 20px 60px' }}>
      <div className="jcg-grid" style={{ display: 'grid', gap: 24 }}>
        {/* LEFT: success confirmation */}
        <div style={{
          background: '#fff', borderRadius: 18, padding: 28,
          border: `1px solid ${TOKENS.line}`,
          boxShadow: '0 1px 2px rgba(11,37,69,0.04), 0 8px 32px rgba(11,37,69,0.04)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
            <div style={{ position: 'relative', flexShrink: 0 }}>
              <div style={{ position: 'absolute', inset: -4, borderRadius: '50%', background: TOKENS.okSoft, animation: 'jcg-ring 1.8s ease-out infinite' }}/>
              <div style={{
                width: 54, height: 54, borderRadius: 27, background: TOKENS.ok,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#fff', position: 'relative',
                boxShadow: '0 8px 20px rgba(31,138,90,0.3)',
              }}>
                <Icon.Check size={28} color="#fff" sw={3}/>
              </div>
            </div>
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: TOKENS.ok, letterSpacing: 1.2, textTransform: 'uppercase' }}>Absensi Tercatat</div>
              <div style={{ fontSize: 22, fontWeight: 700, color: TOKENS.navyInk, letterSpacing: -0.4, marginTop: 2 }}>
                Terima kasih, {user.name.split(' ')[0]}!
              </div>
            </div>
          </div>

          {/* Receipt */}
          <div style={{ background: TOKENS.bg, borderRadius: 14, padding: 18 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, paddingBottom: 14, borderBottom: `1px dashed ${TOKENS.line}` }}>
              <Avatar name={user.name} initials={user.initials} size={44}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: TOKENS.navyInk, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.name}</div>
                <div style={{ fontSize: 11, color: TOKENS.slate, marginTop: 2 }}>
                  <span className="mono">{user.empId}</span> · {user.orgName} · {user.position}
                </div>
              </div>
            </div>
            {[
              ['Sesi', meeting.title],
              ['Tanggal', meeting.date],
              ['Jam absen', joinTime + ' WIB'],
            ].map(([k, v]) => (
              <div key={k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 0', fontSize: 12 }}>
                <span style={{ color: TOKENS.slate }}>{k}</span>
                <span style={{ color: TOKENS.navyInk, fontWeight: 600, textAlign: 'right', maxWidth: '65%' }}>{v}</span>
              </div>
            ))}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 0', fontSize: 12 }}>
              <span style={{ color: TOKENS.slate }}>Status</span>
              <Badge tone="ok">● HADIR</Badge>
            </div>
            <div style={{
              marginTop: 8, paddingTop: 12, borderTop: `1px dashed ${TOKENS.line}`,
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            }}>
              <span style={{ fontSize: 10, color: TOKENS.slate, letterSpacing: 0.8, textTransform: 'uppercase', fontWeight: 600 }}>Kode Bukti</span>
              <span className="mono" style={{ fontSize: 13, color: TOKENS.navy, fontWeight: 600 }}>{code}</span>
            </div>
          </div>

          <div style={{ marginTop: 14, fontSize: 11, color: TOKENS.slate, textAlign: 'center', lineHeight: 1.5 }}>
            Simpan kode bukti di atas jika diperlukan konfirmasi ke admin.
          </div>
        </div>

        {/* RIGHT: Zoom link */}
        <div style={{
          background: `linear-gradient(135deg, ${TOKENS.zoomBlue} 0%, #1a6fe0 100%)`,
          color: '#fff', borderRadius: 18, padding: 28,
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{ position: 'absolute', top: -50, right: -50, width: 180, height: 180, borderRadius: 100, background: 'rgba(255,255,255,0.08)' }}/>
          <div style={{ position: 'relative' }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 12px', background: 'rgba(255,255,255,0.16)', borderRadius: 100 }}>
              <Icon.Video size={14} color="#fff"/>
              <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase' }}>Link Zoom Anda</span>
            </div>
            <div style={{ fontSize: 22, fontWeight: 700, marginTop: 14, letterSpacing: -0.4, lineHeight: 1.25 }}>
              Bergabung ke Meeting
            </div>
            <div style={{ fontSize: 13, opacity: 0.85, marginTop: 6, lineHeight: 1.5 }}>
              Klik tombol di bawah untuk buka Zoom.
              Aplikasi akan terbuka otomatis, atau Anda bisa buka via browser.
            </div>

            {/* Credentials */}
            <div style={{
              marginTop: 18, background: 'rgba(255,255,255,0.12)',
              borderRadius: 12, padding: 4,
              backdropFilter: 'blur(8px)',
              border: '1px solid rgba(255,255,255,0.15)',
            }}>
              {[
                { label: 'Meeting ID', value: meeting.meetingId },
                { label: 'Passcode', value: meeting.passcode },
              ].map((r, i, a) => (
                <div key={r.label} style={{
                  display: 'flex', alignItems: 'center', padding: '11px 14px',
                  borderBottom: i < a.length - 1 ? '1px solid rgba(255,255,255,0.15)' : 'none',
                }}>
                  <div style={{ fontSize: 11, opacity: 0.8, width: 80, flexShrink: 0, letterSpacing: 0.2 }}>{r.label}</div>
                  <div className="mono" style={{ flex: 1, fontSize: 14, fontWeight: 600, letterSpacing: 0.5 }}>{r.value}</div>
                  <button onClick={() => { navigator.clipboard?.writeText(r.value); copy(r.label); }} style={{
                    width: 28, height: 28, borderRadius: 8, border: 'none',
                    background: copied === r.label ? 'rgba(255,255,255,0.3)' : 'rgba(255,255,255,0.12)',
                    color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
                  }}>{copied === r.label ? <Icon.Check size={14}/> : <Icon.Copy size={14}/>}</button>
                </div>
              ))}
            </div>

            {/* Open zoom button */}
            <a href={zoomUrl} target="_blank" rel="noreferrer" style={{ textDecoration: 'none', display: 'block', marginTop: 16 }}>
              <div className="jcg-btn" style={{
                width: '100%', padding: '16px 18px', borderRadius: 14,
                background: '#fff', color: TOKENS.zoomBlue, fontWeight: 700, fontSize: 16,
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
                cursor: 'pointer', boxShadow: '0 8px 24px rgba(0,0,0,0.18)',
                transition: 'transform .1s',
                boxSizing: 'border-box',
              }}>
                <Icon.Video size={18} color={TOKENS.zoomBlue}/> Buka Zoom Meeting
              </div>
            </a>

            <div style={{ marginTop: 10, fontSize: 11, opacity: 0.85, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
              <span>atau salin link:</span>
              <button onClick={() => { navigator.clipboard?.writeText(zoomUrl); copy('url'); }}
                style={{
                  border: 'none', background: 'rgba(255,255,255,0.14)', color: '#fff',
                  padding: '3px 8px', borderRadius: 6, fontSize: 11, cursor: 'pointer',
                  display: 'inline-flex', alignItems: 'center', gap: 4, fontFamily: 'inherit',
                }}>
                {copied === 'url' ? <><Icon.Check size={10}/> tersalin</> : <><Icon.Copy size={10}/> copy link</>}
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Bottom action */}
      <div style={{ marginTop: 24, textAlign: 'center' }}>
        <button onClick={onDone} style={{
          border: 'none', background: 'transparent', color: TOKENS.slate,
          fontSize: 13, cursor: 'pointer', padding: '10px 20px',
          textDecoration: 'underline', textUnderlineOffset: 4,
          fontFamily: 'inherit',
        }}>
          Absen dengan kode karyawan lain
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { TopBar, InputScreen, SuccessZoomScreen, MeetingHero });
