// web-employee.jsx — Karyawan: absen (GPS asli), riwayat, akun
const { useState: useSE, useEffect: useEE } = React;

function greetWeb(h) { return h < 11 ? 'Selamat pagi' : h < 15 ? 'Selamat siang' : h < 18 ? 'Selamat sore' : 'Selamat malam'; }

// live GPS strip
function GpsLive({ gps, busy, onRetry }) {
  if (busy) return (
    <div style={stripWrap}>
      <div style={{ ...stripIcon, background: 'var(--accent-weak)' }}><Icon name="pin" size={17} stroke="var(--accent)" /></div>
      <div style={{ flex: 1 }}><div style={stripTitle}>Mendeteksi lokasi…</div><div style={stripSub}>Mohon izinkan akses lokasi</div></div>
      <div className="spin" style={{ width: 18, height: 18, border: '2.5px solid var(--border-2)', borderTopColor: 'var(--accent)', borderRadius: '50%' }}></div>
    </div>
  );
  if (!gps || !gps.ok) return (
    <div style={stripWrap}>
      <div style={{ ...stripIcon, background: 'var(--danger-weak)' }}><Icon name="pin" size={17} stroke="var(--danger)" /></div>
      <div style={{ flex: 1 }}><div style={stripTitle}>Lokasi belum aktif</div><div style={stripSub}>{gps ? gps.err : 'GPS dimatikan'}</div></div>
      <button onClick={onRetry} className="chip" style={{ color: 'var(--accent)', background: 'var(--accent-weak)' }}>Aktifkan</button>
    </div>
  );
  const lab = MA.locLabel(gps.lat, gps.lng);
  return (
    <div style={stripWrap}>
      <div style={{ position: 'relative', width: 34, height: 34, flexShrink: 0 }}>
        <div className="gps-pulse" style={{ position: 'absolute', inset: 8, opacity: .35 }}></div>
        <div style={{ ...stripIcon, position: 'relative', background: lab.inArea ? 'var(--success-weak)' : 'var(--warn-weak)' }}><Icon name="pin" size={17} stroke={lab.inArea ? 'var(--success)' : 'var(--warn)'} /></div>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={stripTitle}>{lab.name}</div>
        <div className="tnum" style={stripSub}>{gps.lat}, {gps.lng} · ±{gps.acc}m</div>
      </div>
      <span className={`chip ${lab.inArea ? 'hadir' : 'telat'}`} style={{ fontSize: 11 }}><span className="dot"></span>{lab.inArea ? 'Di dealer' : 'Di luar'}</span>
    </div>
  );
}

function WebBeranda({ user, now, gps, locBusy, retryLoc, phase, masuk, pulang, onAct, acting, burst }) {
  const done = phase === 'pulang';
  const isMasuk = phase === 'belum';
  return (
    <div className="screen">
      <div className="appbar">
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <Avatar init={user.init} size={42} />
          <div>
            <div className="appbar-title" style={{ fontSize: 20 }}>{greetWeb(now.getHours())},</div>
            <div className="appbar-sub">{user.name.split(' ')[0]} · {user.jabatan}</div>
          </div>
        </div>
        <Logo h={26} pad={5} radius={10} />
      </div>
      <div className="scroll content-pad stagger">
        <div className="card card-pad" style={{ background: 'linear-gradient(135deg, var(--accent), var(--accent-2))', border: 'none', color: '#fff', overflow: 'hidden', position: 'relative' }}>
          <div style={{ position: 'absolute', right: -30, top: -30, width: 130, height: 130, borderRadius: '50%', background: 'rgba(255,255,255,.1)' }}></div>
          <div style={{ position: 'relative' }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, opacity: .9, letterSpacing: '.4px', textTransform: 'uppercase' }}>Waktu Sekarang</div>
            <div className="display tnum" style={{ fontWeight: 800, fontSize: 52, letterSpacing: '-2px', lineHeight: 1.05, marginTop: 4 }}>{MA.hhmmss(now)}</div>
            <div style={{ fontSize: 13, fontWeight: 500, opacity: .9, marginTop: 4 }}>{MA.dateLong(now)}</div>
          </div>
        </div>
        <div style={{ height: 14 }}></div>
        <GpsLive gps={gps} busy={locBusy} onRetry={retryLoc} />
        <div style={{ height: 14 }}></div>
        <button onClick={done || acting ? null : onAct} className="btn btn-block" style={{ padding: '17px', background: done ? 'var(--success)' : 'var(--accent)', color: '#fff', boxShadow: done ? '0 12px 30px rgba(21,163,74,.34)' : 'var(--accent-glow)', cursor: done ? 'default' : 'pointer', flexDirection: 'column', gap: 3, opacity: acting ? .8 : 1 }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 16.5 }}>
            {burst ? <Icon name="check" size={22} stroke="#fff" sw={2.4} style={{ animation: 'checkPop .4s' }} /> : <Icon name={done ? 'checkCircle' : isMasuk ? 'clock' : 'logout'} size={21} stroke="#fff" />}
            {acting ? 'Memproses…' : isMasuk ? 'Absen Masuk' : done ? 'Absensi Selesai' : 'Absen Pulang'}
          </span>
          <span style={{ fontSize: 12, fontWeight: 500, opacity: .85 }}>{isMasuk ? 'Tekan untuk mencatat kehadiran' : done ? 'Sampai jumpa besok!' : 'Tekan saat selesai bekerja'}</span>
        </button>
        <div style={{ height: 14 }}></div>
        <div style={{ display: 'flex', alignItems: 'center', padding: '14px 8px', background: 'var(--surface-2)', borderRadius: 14, border: '1px solid var(--border)' }}>
          {[['Masuk', masuk || '—', masuk ? 'var(--success)' : null], ['Pulang', pulang || '—', pulang ? 'var(--accent)' : null], ['Status', phase === 'belum' ? '—' : (masuk && masuk > MA.DEALER.lateAfter ? 'Telat' : 'Hadir'), null]].map(([l, v, col], i) => (
            <React.Fragment key={l}>
              {i > 0 && <div style={{ width: 1, height: 30, background: 'var(--border-2)' }}></div>}
              <div style={{ flex: 1, textAlign: 'center' }}>
                <div className="display tnum" style={{ fontWeight: 800, fontSize: 18, color: col || 'var(--text)' }}>{v}</div>
                <div style={{ fontSize: 11, color: 'var(--text-mute)', fontWeight: 600, marginTop: 3 }}>{l}</div>
              </div>
            </React.Fragment>
          ))}
        </div>
      </div>
    </div>
  );
}

function WebRiwayat({ user, history }) {
  return (
    <div className="screen">
      <AppHeader title="Riwayat Absensi" sub={MA.monthLabel()} right={<IconBtn name="calendar" />} />
      <div className="scroll content-pad stagger">
        <div className="card card-pad" style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <Ring value={user.pct} size={92} sw={10} label={user.pct + '%'} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>Tingkat Kehadiran</div>
            <div style={{ fontSize: 12.5, color: 'var(--text-dim)', fontWeight: 500, margin: '2px 0 12px' }}>Bulan {MA.monthLabel()}</div>
            <div style={{ display: 'flex', gap: 18 }}>
              {[[`${user.hadir}/${user.total}`, 'Hari hadir', 'var(--text)'], [user.late, 'Telat', 'var(--warn)'], [user.ot + 'j', 'Lembur', 'var(--accent)']].map(([v, l, c]) => (
                <div key={l}><div className="display tnum" style={{ fontWeight: 800, fontSize: 18, color: c }}>{v}</div><div style={{ fontSize: 11, color: 'var(--text-mute)', fontWeight: 600 }}>{l}</div></div>
              ))}
            </div>
          </div>
        </div>
        <div className="label-cap" style={{ margin: '20px 2px 8px' }}>Detail Harian</div>
        <div className="card" style={{ padding: '2px 16px' }}>
          {history === null && <div style={{ padding: 22, textAlign: 'center', color: 'var(--text-mute)', fontSize: 14 }}>Memuat…</div>}
          {(history || []).map((h, i) => (
            <div className="row" key={i}>
              <div style={{ width: 44, textAlign: 'center', flexShrink: 0 }}>
                <div className="display tnum" style={{ fontWeight: 800, fontSize: 20, color: 'var(--text)', lineHeight: 1 }}>{h.d}</div>
                <div style={{ fontSize: 10.5, color: 'var(--text-mute)', fontWeight: 700 }}>{h.date.split(',')[0]}</div>
              </div>
              <div style={{ width: 1, height: 32, background: 'var(--border)' }}></div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <StatusChip status={h.status} sm />
                <div className="tnum" style={{ fontSize: 12.5, color: 'var(--text-dim)', fontWeight: 600, marginTop: 5 }}>{h.in !== '—' ? `${h.in} – ${h.out}` : h.loc}</div>
              </div>
              <div className="display tnum" style={{ fontWeight: 700, fontSize: 13.5, color: 'var(--text-dim)' }}>{h.hours}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function WebAkun({ user, onLogout, theme, onToggleTheme }) {
  const item = (icon, label, right, danger, onClick) => (
    <div className="row" style={{ cursor: 'pointer' }} onClick={onClick}>
      <div style={{ width: 38, height: 38, borderRadius: 11, background: danger ? 'var(--danger-weak)' : 'var(--surface-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={icon} size={19} stroke={danger ? 'var(--danger)' : 'var(--text-dim)'} /></div>
      <div style={{ flex: 1, fontSize: 14.5, fontWeight: 600, color: danger ? 'var(--danger)' : 'var(--text)' }}>{label}</div>
      {right || <Icon name="chevron" size={18} stroke="var(--text-mute)" />}
    </div>
  );
  return (
    <div className="screen">
      <AppHeader title="Akun Saya" />
      <div className="scroll content-pad stagger">
        <div className="card card-pad" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 4 }}>
          <Avatar init={user.init} size={76} fs={28} />
          <div className="display" style={{ fontWeight: 800, fontSize: 20, color: 'var(--text)', marginTop: 8 }}>{user.name}</div>
          <div style={{ fontSize: 13.5, color: 'var(--text-dim)', fontWeight: 600 }}>{user.jabatan} · {user.id}</div>
          <div className="chip neutral" style={{ marginTop: 6 }}><Icon name="shield" size={13} stroke="var(--text-dim)" />{MA.DEALER.branch}</div>
        </div>
        <div style={{ display: 'flex', gap: 12, margin: '14px 0' }}>
          {[['Kehadiran', user.pct + '%'], ['Jam Kerja', user.hours + 'j'], ['Lembur', user.ot + 'j']].map(([l, v]) => (
            <div key={l} className="card card-pad" style={{ flex: 1, textAlign: 'center', padding: '14px 8px' }}><div className="display tnum" style={{ fontWeight: 800, fontSize: 20, color: 'var(--text)' }}>{v}</div><div style={{ fontSize: 11, color: 'var(--text-mute)', fontWeight: 600, marginTop: 3 }}>{l}</div></div>
          ))}
        </div>
        <div className="card" style={{ padding: '2px 16px' }}>
          {item('user', 'Data Pribadi')}
          {item('settings', 'Mode Gelap', (
            <button onClick={(e) => { e.stopPropagation(); onToggleTheme(); }} style={{ width: 46, height: 27, borderRadius: 999, background: theme === 'dark' ? 'var(--accent)' : 'var(--border-2)', position: 'relative', transition: 'background .2s' }}>
              <span style={{ position: 'absolute', top: 3, left: theme === 'dark' ? 22 : 3, width: 21, height: 21, borderRadius: '50%', background: '#fff', transition: 'left .2s', boxShadow: '0 1px 3px rgba(0,0,0,.3)' }}></span>
            </button>
          ), false, () => {})}
        </div>
        <div style={{ height: 12 }}></div>
        <div className="card" style={{ padding: '2px 16px' }}>{item('logout', 'Keluar', null, true, onLogout)}</div>
      </div>
    </div>
  );
}

function WebEmployee({ user, now, onLogout, theme, onToggleTheme }) {
  const [tab, setTab] = useSE('beranda');
  const [phase, setPhase] = useSE('belum');
  const [masuk, setMasuk] = useSE(null);
  const [pulang, setPulang] = useSE(null);
  const [gps, setGps] = useSE(null);
  const [locBusy, setLocBusy] = useSE(true);
  const [acting, setActing] = useSE(false);
  const [burst, setBurst] = useSE(false);
  const [toast, setToast] = useSE(null);
  const [history, setHistory] = useSE(null);

  const loadLoc = () => {
    setLocBusy(true);
    MA.getLocation().then(g => {
      // di mode demo, jika GPS diblokir (mis. di pratinjau), pakai lokasi dealer sbg contoh
      if ((!g || !g.ok) && MA.DEMO) g = { ok: true, lat: MA.DEALER.lat + 0.0004, lng: MA.DEALER.lng - 0.0003, acc: 12 };
      setGps(g); setLocBusy(false);
    });
  };
  useEE(() => {
    loadLoc();
    MA.myStatus(user.id).then(r => { if (r.ok) { setPhase(r.phase); setMasuk(r.masuk || null); setPulang(r.pulang || null); } });
    MA.myHistory(user.id).then(r => setHistory(r.ok ? r.history : []));
  }, []);

  const flash = (m) => { setToast(m); setTimeout(() => setToast(null), 2800); };

  const act = async () => {
    let g = gps;
    if (!g || !g.ok) { setLocBusy(true); g = await MA.getLocation(); if ((!g || !g.ok) && MA.DEMO) g = { ok: true, lat: MA.DEALER.lat, lng: MA.DEALER.lng, acc: 15 }; setGps(g); setLocBusy(false); }
    setActing(true);
    if (phase === 'belum') {
      const r = await MA.clockIn(user.id, g);
      setActing(false);
      if (r.ok) { setPhase('masuk'); setMasuk(r.time); setBurst(true); setTimeout(() => setBurst(false), 600); flash(`Absen masuk tercatat · ${r.time}`); }
      else flash(r.err || 'Gagal absen');
    } else if (phase === 'masuk') {
      const r = await MA.clockOut(user.id, g);
      setActing(false);
      if (r.ok) { setPhase('pulang'); setPulang(r.time); flash(`Absen pulang tercatat · ${r.time}`); }
      else flash(r.err || 'Gagal absen');
    }
  };

  const tabs = [{ id: 'beranda', icon: 'home', label: 'Absen' }, { id: 'riwayat', icon: 'history', label: 'Riwayat' }, { id: 'akun', icon: 'user', label: 'Akun' }];
  return (
    <>
      <div className="fade-key" key={tab} style={{ height: '100%' }}>
        {tab === 'beranda' && <WebBeranda user={user} now={now} gps={gps} locBusy={locBusy} retryLoc={loadLoc} phase={phase} masuk={masuk} pulang={pulang} onAct={act} acting={acting} burst={burst} />}
        {tab === 'riwayat' && <WebRiwayat user={user} history={history} />}
        {tab === 'akun' && <WebAkun user={user} onLogout={onLogout} theme={theme} onToggleTheme={onToggleTheme} />}
      </div>
      {toast && <Toast>{toast}</Toast>}
      <BottomNav tabs={tabs} active={tab} onChange={setTab} />
    </>
  );
}

const stripWrap = { display: 'flex', alignItems: 'center', gap: 11, padding: '11px 14px', background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 14 };
const stripIcon = { width: 34, height: 34, borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 };
const stripTitle = { fontSize: 13.5, fontWeight: 700, color: 'var(--text)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' };
const stripSub = { fontSize: 11.5, color: 'var(--text-dim)', fontWeight: 500 };

window.WebEmployee = WebEmployee;
