// web-owner.jsx — Pemilik: dashboard, karyawan, laporan (live data)
const { useState: useSO, useEffect: useEO } = React;

function BarsO({ data, max = 8, height = 92 }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 3, height }}>
      {data.map((v, i) => (
        <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', height: '100%' }}>
          <div style={{ height: `${(v / max) * 100}%`, borderRadius: 4, background: v >= max - 1 ? 'var(--accent)' : v <= max - 3 ? 'var(--warn)' : 'color-mix(in srgb, var(--accent) 55%, var(--surface-3))', minHeight: 4, transition: 'height .8s cubic-bezier(.2,.8,.2,1)' }}></div>
        </div>
      ))}
    </div>
  );
}

function OwnerHeaderW({ title, sub, onLogout }) {
  return (
    <div className="appbar">
      <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
        <Logo h={32} pad={5} radius={11} />
        <div><div className="appbar-title" style={{ fontSize: 20 }}>{title}</div><div className="appbar-sub">{sub}</div></div>
      </div>
      <IconBtn name="logout" onClick={onLogout} />
    </div>
  );
}

function WebDashboard({ data, onLogout, onOpenEmp }) {
  if (!data) return <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-mute)' }}><div className="appbar"><OwnerHeaderW title="Dashboard" sub="Memuat…" onLogout={onLogout} /></div></div>;
  const c = data.counts, total = data.today.length, hadirTotal = (c.hadir || 0) + (c.telat || 0);
  const pct = total ? Math.round((hadirTotal / total) * 100) : 0;
  const feed = data.today.filter(t => t.in && t.in !== '—').sort((a, b) => a.in.localeCompare(b.in));
  const countCard = (label, val, status) => (
    <div className="card" style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
      <StatusChip status={status} sm /><div className="display tnum" style={{ fontWeight: 800, fontSize: 30, lineHeight: 1, color: 'var(--text)' }}>{val || 0}</div><div style={{ fontSize: 11.5, color: 'var(--text-dim)', fontWeight: 600 }}>{label}</div>
    </div>
  );
  return (
    <div className="screen">
      <OwnerHeaderW title="Dashboard" sub={`${data.branch} · ${data.dateShort}`} onLogout={onLogout} />
      <div className="scroll content-pad stagger">
        <div className="card card-pad" style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
          <Ring value={pct} size={118} sw={13} label={pct + '%'} sub="hadir" />
          <div style={{ flex: 1 }}>
            <div className="label-cap">Kehadiran Hari Ini</div>
            <div className="display" style={{ fontWeight: 800, fontSize: 21, color: 'var(--text)', margin: '4px 0 2px' }}>{hadirTotal} <span style={{ color: 'var(--text-mute)', fontWeight: 600, fontSize: 15 }}>dari {total} karyawan</span></div>
            <div style={{ fontSize: 12.5, color: 'var(--text-dim)', fontWeight: 500, marginBottom: 10 }}>Update {MA.hhmm()}</div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              <span className="chip telat" style={{ fontSize: 11 }}><span className="dot"></span>{c.telat || 0} Telat</span>
              <span className="chip izin" style={{ fontSize: 11 }}><span className="dot"></span>{c.izin || 0} Izin</span>
              <span className="chip absen" style={{ fontSize: 11 }}><span className="dot"></span>{c.absen || 0} Absen</span>
            </div>
          </div>
        </div>
        <div style={{ height: 14 }}></div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {countCard('Tepat waktu', c.hadir, 'hadir')}{countCard('Terlambat', c.telat, 'telat')}
          {countCard('Izin / Sakit', c.izin, 'izin')}{countCard('Tidak hadir', c.absen, 'absen')}
        </div>
        <div style={{ height: 14 }}></div>
        <div className="card card-pad">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
            <div><div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>Tren Kehadiran</div><div style={{ fontSize: 12, color: 'var(--text-dim)', fontWeight: 500 }}>{data.monthLabel} · per hari kerja</div></div>
          </div>
          <BarsO data={data.trend} />
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '20px 2px 8px' }}>
          <div className="label-cap">Aktivitas Hari Ini</div><span style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-mute)' }}>{feed.length} check-in</span>
        </div>
        <div className="card" style={{ padding: '2px 16px' }}>
          {feed.length === 0 && <div style={{ padding: 18, textAlign: 'center', color: 'var(--text-mute)', fontSize: 13.5 }}>Belum ada yang absen hari ini</div>}
          {feed.map((a, i) => (
            <div className="row" key={i} onClick={() => onOpenEmp(a.id)} style={{ cursor: 'pointer' }}>
              <Avatar init={a.init} size={40} />
              <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>{a.name}</div><div style={{ fontSize: 12, color: 'var(--text-dim)', fontWeight: 500, display: 'flex', alignItems: 'center', gap: 4, marginTop: 1 }}><Icon name="pin" size={12} stroke="var(--text-mute)" />{a.loc}</div></div>
              <div style={{ textAlign: 'right' }}><div className="display tnum" style={{ fontWeight: 700, fontSize: 14, color: 'var(--text)' }}>{a.in}</div><StatusChip status={a.status} sm /></div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function WebKaryawan({ report, today, onLogout, onOpenEmp }) {
  const [q, setQ] = useSO('');
  const rows = (report ? report.perEmployee : []).map(e => ({ ...e, status: (today.find(t => t.id === e.id) || {}).status || 'belum' }));
  const list = rows.filter(e => e.name.toLowerCase().includes(q.toLowerCase()) || e.jabatan.toLowerCase().includes(q.toLowerCase()));
  return (
    <div className="screen">
      <OwnerHeaderW title="Karyawan" sub={`${rows.length} karyawan aktif`} onLogout={onLogout} />
      <div className="pad" style={{ paddingBottom: 8 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 13, padding: '11px 14px', boxShadow: 'var(--shadow-sm)' }}>
          <Icon name="search" size={18} stroke="var(--text-mute)" /><input value={q} onChange={e => setQ(e.target.value)} placeholder="Cari nama atau jabatan…" style={{ border: 'none', outline: 'none', background: 'transparent', flex: 1, fontSize: 14, fontWeight: 500, color: 'var(--text)', fontFamily: 'inherit' }} />
        </div>
      </div>
      <div className="scroll content-pad" style={{ paddingTop: 6 }}>
        <div className="stagger" style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
          {list.map(e => (
            <div key={e.id} className="card card-pad" onClick={() => onOpenEmp(e.id)} style={{ cursor: 'pointer', padding: 15 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
                <Avatar init={e.init} size={46} />
                <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--text)' }}>{e.name}</div><div style={{ fontSize: 12.5, color: 'var(--text-dim)', fontWeight: 500, marginTop: 1 }}>{e.jabatan}</div></div>
                <StatusChip status={e.status} sm />
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 13 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5 }}><span style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-mute)' }}>Kehadiran bulan ini</span><span className="tnum" style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--text)' }}>{e.pct}%</span></div>
                  <ProgressBar value={e.pct} color={e.pct >= 95 ? 'var(--success)' : e.pct >= 90 ? 'var(--accent)' : 'var(--warn)'} />
                </div>
                <Icon name="chevron" size={18} stroke="var(--text-mute)" />
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function WebDetail({ emp, today, onBack }) {
  const t = today.find(x => x.id === emp.id) || {};
  return (
    <div className="screen fade-key">
      <div className="appbar">
        <button onClick={onBack} style={{ width: 42, height: 42, borderRadius: 13, background: 'var(--surface)', border: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'var(--shadow-sm)' }}><Icon name="chevron" size={20} stroke="var(--text)" style={{ transform: 'rotate(180deg)' }} /></button>
        <div className="appbar-title" style={{ fontSize: 18 }}>Detail Karyawan</div><div style={{ width: 42 }}></div>
      </div>
      <div className="scroll content-pad stagger">
        <div className="card card-pad" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 4 }}>
          <Avatar init={emp.init} size={74} fs={27} />
          <div className="display" style={{ fontWeight: 800, fontSize: 20, color: 'var(--text)', marginTop: 8 }}>{emp.name}</div>
          <div style={{ fontSize: 13.5, color: 'var(--text-dim)', fontWeight: 600 }}>{emp.jabatan} · {emp.id}</div>
          <div style={{ marginTop: 6 }}><StatusChip status={t.status || 'belum'} /></div>
        </div>
        <div style={{ height: 14 }}></div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <StatCard label="Kehadiran" value={emp.pct} unit="%" icon="checkCircle" tone="success" />
          <StatCard label="Hari hadir" value={`${emp.hadir}/${emp.total}`} icon="calendar" tone="accent" />
          <StatCard label="Total jam" value={emp.hours} unit="j" icon="clock" tone="accent" />
          <StatCard label="Lembur" value={emp.ot} unit="j" icon="flame" tone="warn" />
        </div>
        <div style={{ height: 18 }}></div>
        <div className="label-cap" style={{ margin: '0 2px 8px' }}>Catatan Hari Ini</div>
        <div className="card card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {[['clock', 'var(--success)', 'Jam masuk', t.in || '—'], ['logout', 'var(--accent)', 'Jam pulang', t.out || '—'], ['pin', 'var(--text-mute)', 'Lokasi', t.loc || '—']].map(([ic, col, lab, val], i) => (
            <React.Fragment key={lab}>
              {i > 0 && <div className="divider"></div>}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><span style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 13.5, fontWeight: 600, color: 'var(--text-dim)' }}><Icon name={ic} size={18} stroke={col} />{lab}</span><span className={lab === 'Lokasi' ? '' : 'display tnum'} style={{ fontWeight: 700, fontSize: lab === 'Lokasi' ? 13.5 : 15, color: 'var(--text)' }}>{val}</span></div>
            </React.Fragment>
          ))}
        </div>
      </div>
    </div>
  );
}

function WebLaporan({ report, onLogout }) {
  const [sheet, setSheet] = useSO(false);
  const [toast, setToast] = useSO(null);
  if (!report) return <div className="screen"><OwnerHeaderW title="Laporan" sub="Memuat…" onLogout={onLogout} /></div>;
  const flash = (m) => { setToast(m); setTimeout(() => setToast(null), 2800); };
  const doExport = (kind) => {
    setSheet(false);
    if (kind === 'Excel') {
      if (MA.CONFIG.SHEET_URL) { window.open(MA.CONFIG.SHEET_URL, '_blank'); flash('Membuka Google Sheet…'); }
      else flash('Atur SHEET_URL di api.js untuk membuka Sheet');
    } else { window.print(); }
  };
  return (
    <div className="screen">
      <OwnerHeaderW title="Laporan" sub="Rekap kehadiran bulanan" onLogout={onLogout} />
      <div className="pad" style={{ paddingBottom: 6 }}>
        <button style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', padding: '12px 16px', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 13, boxShadow: 'var(--shadow-sm)' }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 14.5, fontWeight: 700, color: 'var(--text)' }}><Icon name="calendar" size={18} stroke="var(--accent)" />{report.monthLabel}</span><Icon name="chevronDown" size={18} stroke="var(--text-mute)" />
        </button>
      </div>
      <div className="scroll content-pad" style={{ paddingTop: 8 }}>
        <div className="stagger">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <StatCard label="Rata-rata kehadiran" value={report.avgPct} unit="%" icon="trend" tone="success" />
            <StatCard label="Total jam kerja" value={report.totalHours} unit="j" icon="clock" tone="accent" />
            <StatCard label="Total lembur" value={report.totalOt} unit="j" icon="flame" tone="warn" />
            <StatCard label="Total keterlambatan" value={report.totalLate} unit="x" icon="bell" tone="danger" />
          </div>
          <div style={{ height: 16 }}></div>
          <div className="card card-pad">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}><div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>Kehadiran Harian</div><div style={{ fontSize: 12, color: 'var(--text-dim)', fontWeight: 500 }}>{report.totHadir}/{report.totHari} hari-orang</div></div>
            <BarsO data={report.trend} />
          </div>
          <div style={{ height: 18 }}></div>
          <div className="label-cap" style={{ margin: '0 2px 8px' }}>Rekap Per Karyawan</div>
          <div className="card" style={{ padding: '2px 16px' }}>
            {report.perEmployee.map(e => (
              <div className="row" key={e.id} style={{ gap: 12 }}>
                <Avatar init={e.init} size={38} fs={13} />
                <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--text)' }}>{e.name}</div><div className="tnum" style={{ fontSize: 11.5, color: 'var(--text-dim)', fontWeight: 600, marginTop: 1 }}>{e.hadir}/{e.total} hari · {e.hours}j · lembur {e.ot}j</div></div>
                <div style={{ textAlign: 'right' }}><div className="display tnum" style={{ fontWeight: 800, fontSize: 16, color: e.pct >= 95 ? 'var(--success)' : e.pct >= 90 ? 'var(--text)' : 'var(--warn)' }}>{e.pct}%</div>{e.late > 0 && <div className="tnum" style={{ fontSize: 10.5, color: 'var(--warn)', fontWeight: 700 }}>{e.late}x telat</div>}</div>
              </div>
            ))}
          </div>
          <div style={{ height: 16 }}></div>
          <button className="btn btn-primary btn-block" onClick={() => setSheet(true)}><Icon name="download" size={20} stroke="#fff" />Export Laporan</button>
        </div>
      </div>
      {sheet && (
        <div className="sheet-scrim" onClick={() => setSheet(false)}>
          <div className="sheet" onClick={e => e.stopPropagation()}>
            <div className="sheet-grab"></div>
            <div className="display" style={{ fontWeight: 800, fontSize: 18, color: 'var(--text)' }}>Export Laporan</div>
            <div style={{ fontSize: 13, color: 'var(--text-dim)', fontWeight: 500, marginBottom: 16 }}>Rekap {report.monthLabel} · {report.perEmployee.length} karyawan</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <button onClick={() => doExport('Excel')} style={sheetBtn}><div style={{ ...sheetIco, background: 'var(--success-weak)' }}><Icon name="excel" size={22} stroke="var(--success)" /></div><div style={{ flex: 1, textAlign: 'left' }}><div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--text)' }}>Buka di Google Sheets</div><div style={{ fontSize: 12, color: 'var(--text-dim)', fontWeight: 500 }}>Data lengkap, bisa diunduh .xlsx</div></div><Icon name="chevron" size={18} stroke="var(--text-mute)" /></button>
              <button onClick={() => doExport('PDF')} style={sheetBtn}><div style={{ ...sheetIco, background: 'var(--danger-weak)' }}><Icon name="pdf" size={22} stroke="var(--danger)" /></div><div style={{ flex: 1, textAlign: 'left' }}><div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--text)' }}>Cetak / Simpan PDF</div><div style={{ fontSize: 12, color: 'var(--text-dim)', fontWeight: 500 }}>Lewat dialog cetak browser</div></div><Icon name="chevron" size={18} stroke="var(--text-mute)" /></button>
            </div>
          </div>
        </div>
      )}
      {toast && <Toast>{toast}</Toast>}
    </div>
  );
}

function WebOwner({ user, onLogout }) {
  const [tab, setTab] = useSO('dashboard');
  const [dash, setDash] = useSO(null);
  const [report, setReport] = useSO(null);
  const [empId, setEmpId] = useSO(null);

  useEO(() => { MA.dashboard().then(r => r.ok && setDash(r)); MA.report().then(r => r.ok && setReport(r)); }, []);

  const today = dash ? dash.today : [];
  const empObj = report && empId ? report.perEmployee.find(e => e.id === empId) : null;
  const tabs = [{ id: 'dashboard', icon: 'grid', label: 'Dashboard' }, { id: 'karyawan', icon: 'users', label: 'Karyawan' }, { id: 'laporan', icon: 'chart', label: 'Laporan' }];

  if (empObj) return <WebDetail emp={empObj} today={today} onBack={() => setEmpId(null)} />;
  return (
    <>
      <div className="fade-key" key={tab} style={{ height: '100%' }}>
        {tab === 'dashboard' && <WebDashboard data={dash} onLogout={onLogout} onOpenEmp={setEmpId} />}
        {tab === 'karyawan' && <WebKaryawan report={report} today={today} onLogout={onLogout} onOpenEmp={setEmpId} />}
        {tab === 'laporan' && <WebLaporan report={report} onLogout={onLogout} />}
      </div>
      <BottomNav tabs={tabs} active={tab} onChange={setTab} />
    </>
  );
}

const sheetBtn = { display: 'flex', alignItems: 'center', gap: 13, padding: 14, borderRadius: 14, background: 'var(--surface-2)', border: '1px solid var(--border)' };
const sheetIco = { width: 42, height: 42, borderRadius: 11, display: 'flex', alignItems: 'center', justifyContent: 'center' };

window.WebOwner = WebOwner;
