// ---------- Attendance ----------

function Attendance({ role }) {
  const isBoss = role === 'boss';
  const [tab, setTab] = React.useState('today'); // today | history
  const [rows, setRows] = React.useState(() => seedTodayRows());
  const [editing, setEditing] = React.useState(null);
  const [editClockIn, setEditClockIn] = React.useState('');
  const [editClockOut, setEditClockOut] = React.useState('');
  const [editReason, setEditReason] = React.useState('');
  const [auditEdits, setAuditEdits] = React.useState([]);

  const [fromDate, setFromDate] = React.useState('2026-04-01');
  const [toDate, setToDate] = React.useState('2026-04-26');
  const [empFilter, setEmpFilter] = React.useState('all');

  const presentToday = rows.filter(r => r.status !== 'absent' && r.clock_in).length;
  const lateArrivals = rows.filter(r => r.status === 'late').length;
  const absentToday = rows.filter(r => r.status === 'absent').length;

  React.useEffect(() => {
    window.__attendanceLateTodayCount = lateArrivals;
  }, [lateArrivals]);

  const openEdit = (r) => {
    setEditing(r);
    setEditClockIn(r.clock_in || '');
    setEditClockOut(r.clock_out || '');
    setEditReason('');
  };

  const saveEdit = () => {
    if (!editing) return;
    if (!editReason.trim()) return;
    setRows(rows.map(r => {
      if (r.id !== editing.id) return r;
      const next = {
        ...r,
        clock_in: editClockIn || null,
        clock_out: editClockOut || null,
        manually_edited: true,
        edited_by: 'boss',
        edit_reason: editReason.trim(),
      };
      const recalc = computeStatus(next.shift_start, next.clock_in, next.clock_out);
      return { ...next, status: recalc.status, hours_worked: recalc.hours_worked };
    }));
    setAuditEdits([
      {
        id: 'ae_' + Math.random().toString(16).slice(2),
        employee: editing.employee_name,
        at: fmtDateTime(new Date().toISOString()),
        reason: editReason.trim(),
      },
      ...auditEdits,
    ].slice(0, 8));
    setEditing(null);
  };

  const filteredHistory = seedHistoryRows()
    .filter(r => (!fromDate || r.work_date >= fromDate) && (!toDate || r.work_date <= toDate))
    .filter(r => empFilter === 'all' ? true : r.employee_id === empFilter);

  return (
    <div style={{display:'flex',flexDirection:'column',gap:20}}>
      <div style={{display:'flex',gap:4,borderBottom:'1px solid var(--border)'}}>
        {[['today','Today'],['history','Clock-in history']].map(([k,l]) => (
          <button key={k} onClick={()=>setTab(k)} style={{padding:'12px 16px',fontSize:13,borderBottom:'2px solid '+(tab===k?'var(--accent)':'transparent'),color: tab===k?'var(--accent)':'var(--text-dim)',fontWeight:500}}>
            {l}
          </button>
        ))}
      </div>

      {tab === 'today' && (
        <>
          <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(220px,1fr))',gap:14}}>
            <KPI label="Present Today" value={presentToday} icon={Icon.Users} color="var(--green)"/>
            <KPI label="Late Arrivals" value={lateArrivals} icon={Icon.Clock} color="var(--gold)"/>
            <KPI label="Absent Today" value={absentToday} icon={Icon.AlertTriangle} color="var(--red)"/>
          </div>

          <TablePanel
            title="Today's Clock-ins"
            right={<div className="chip" style={{fontFamily:'JetBrains Mono',fontSize:10,letterSpacing:'0.15em',textTransform:'uppercase'}}>Shift start <span style={{color:'var(--accent)',marginLeft:6}}>09:00</span></div>}
          >
            <table style={{width:'100%',borderCollapse:'collapse'}}>
              <thead><tr>
                <Th>Employee</Th>
                <Th>Clock In</Th>
                <Th>Clock Out</Th>
                <Th>Hours Worked</Th>
                <Th>Status</Th>
                <Th>Notes</Th>
                {isBoss && <Th align="end">Manual Override</Th>}
              </tr></thead>
              <tbody>
                {rows.map(r => (
                  <tr key={r.id}>
                    <Td>
                      <div style={{display:'flex',alignItems:'center',gap:12}}>
                        <div style={{width:34,height:34,borderRadius:'50%',background:'var(--accent-dim)',border:'1px solid var(--accent-border)',color:'var(--accent)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:12,fontWeight:600}}>
                          {r.initials}
                        </div>
                        <div>
                          <div style={{fontWeight:500}}>{r.employee_name}</div>
                          <div style={{fontSize:11,color:'var(--text-dim)'}}>{r.department}</div>
                        </div>
                      </div>
                    </Td>
                    <Td><span className="mono" style={{fontSize:12,color:r.clock_in? 'var(--text)' : 'var(--text-dim)'}}>{r.clock_in || '—'}</span></Td>
                    <Td><span className="mono" style={{fontSize:12,color:r.clock_out? 'var(--text)' : 'var(--text-dim)'}}>{r.clock_out || '—'}</span></Td>
                    <Td><span className="mono" style={{fontSize:12,color:'var(--text-dim)'}}>{r.hours_worked != null ? r.hours_worked.toFixed(2) : '—'}</span></Td>
                    <Td><AttendanceStatusBadge status={r.status}/></Td>
                    <Td><span style={{color:'var(--text-dim)'}}>{r.notes || '—'}</span></Td>
                    {isBoss && (
                      <Td align="end">
                        <button className="btn btn-sm" style={{background:'var(--card2)'}} onClick={()=>openEdit(r)}>
                          <Icon.Edit size={13}/> Edit
                        </button>
                      </Td>
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          </TablePanel>

          <div style={{display:'grid',gridTemplateColumns:'1.2fr 1fr',gap:14}} className="att-grid">
            <div className="card" style={{padding:18}}>
              <div style={{fontSize:12,fontWeight:600,marginBottom:8}}>Device Setup Instructions</div>
              <div style={{color:'var(--text-dim)',fontSize:13,lineHeight:1.6}}>
                <div>1. Connect NGTeco device to WiFi</div>
                <div>2. Set webhook URL to: <span className="mono">https://[project].supabase.co/functions/v1/clock-punch</span></div>
                <div>3. Map each badge ID to an employee in <span style={{color:'var(--text)'}}>Settings &gt; Attendance Devices</span></div>
                <div>4. Test with a tap — it should appear here in real time</div>
              </div>
              <div className="chip" style={{marginTop:14,fontFamily:'JetBrains Mono',fontSize:10,letterSpacing:'0.12em',textTransform:'uppercase'}}>
                Payload <span style={{color:'var(--accent)',marginLeft:8}}>{`{ employee_id, device_id, punch_type: 'in' | 'out', timestamp }`}</span>
              </div>
            </div>

            <div className="card" style={{padding:18}}>
              <div style={{fontSize:12,fontWeight:600,marginBottom:8}}>Database: attendance table (SQL)</div>
              <div style={{fontSize:12,color:'var(--text-dim)',lineHeight:1.6,marginBottom:10}}>
                Paste this into Supabase SQL editor.
              </div>
              <pre style={{whiteSpace:'pre-wrap',wordBreak:'break-word',fontSize:11,lineHeight:1.5,background:'var(--bg)',border:'1px solid var(--border)',borderRadius:10,padding:12,margin:0}}>
{ATTENDANCE_SQL}
              </pre>
            </div>
          </div>

          {isBoss && (
            <TablePanel
              title="Recent manual edits"
              right={<div className="chip" style={{fontFamily:'JetBrains Mono',fontSize:10,letterSpacing:'0.15em',textTransform:'uppercase'}}>Boss only</div>}
            >
              <table style={{width:'100%',borderCollapse:'collapse'}}>
                <thead><tr>
                  <Th>Employee</Th><Th>Edited at</Th><Th>Reason</Th>
                </tr></thead>
                <tbody>
                  {auditEdits.length === 0 ? (
                    <tr><Td style={{color:'var(--text-dim)'}} colSpan={3}>No edits yet.</Td></tr>
                  ) : auditEdits.map(a => (
                    <tr key={a.id}>
                      <Td><span style={{fontWeight:500}}>{a.employee}</span></Td>
                      <Td><span className="mono" style={{fontSize:12,color:'var(--text-dim)'}}>{a.at}</span></Td>
                      <Td><span style={{color:'var(--text-dim)'}}>{a.reason}</span></Td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </TablePanel>
          )}
        </>
      )}

      {tab === 'history' && (
        <>
          <div style={{display:'flex',gap:10,flexWrap:'wrap',alignItems:'center',justifyContent:'space-between'}}>
            <div style={{display:'flex',gap:10,flexWrap:'wrap',alignItems:'center'}}>
              <div className="field">
                <label>Date from</label>
                <input type="date" value={fromDate} onChange={e=>setFromDate(e.target.value)} />
              </div>
              <div className="field">
                <label>Date to</label>
                <input type="date" value={toDate} onChange={e=>setToDate(e.target.value)} />
              </div>
              <div className="field">
                <label>Employee</label>
                <select value={empFilter} onChange={e=>setEmpFilter(e.target.value)}>
                  <option value="all">All employees</option>
                  {(EMPLOYEES || []).filter(e=>e.status==='active').map(e => (
                    <option key={e.id} value={e.id}>{e.full_name}</option>
                  ))}
                </select>
              </div>
            </div>
            <button className="btn btn-primary btn-sm" onClick={()=>window.print()}>
              <Icon.Download size={14}/> Export to PDF
            </button>
          </div>

          <TablePanel title="Clock-in History">
            <table style={{width:'100%',borderCollapse:'collapse'}}>
              <thead><tr>
                <Th>Date</Th><Th>Employee</Th><Th>Clock In</Th><Th>Clock Out</Th><Th>Hours</Th><Th>Status</Th><Th>Notes</Th>
              </tr></thead>
              <tbody>
                {filteredHistory.map(r => (
                  <tr key={r.id}>
                    <Td><span className="mono" style={{fontSize:12,color:'var(--text-dim)'}}>{r.work_date}</span></Td>
                    <Td><span style={{fontWeight:500}}>{r.employee_name}</span></Td>
                    <Td><span className="mono" style={{fontSize:12,color:'var(--text-dim)'}}>{r.clock_in || '—'}</span></Td>
                    <Td><span className="mono" style={{fontSize:12,color:'var(--text-dim)'}}>{r.clock_out || '—'}</span></Td>
                    <Td><span className="mono" style={{fontSize:12,color:'var(--text-dim)'}}>{r.hours_worked != null ? r.hours_worked.toFixed(2) : '—'}</span></Td>
                    <Td><AttendanceStatusBadge status={r.status}/></Td>
                    <Td><span style={{color:'var(--text-dim)'}}>{r.notes || '—'}</span></Td>
                  </tr>
                ))}
              </tbody>
            </table>
          </TablePanel>
        </>
      )}

      {editing && (
        <div className="modal-backdrop" onClick={()=>setEditing(null)}>
          <div className="modal" onClick={e=>e.stopPropagation()} style={{maxWidth:640}}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:12,marginBottom:18}}>
              <div>
                <h3 style={{fontSize:24}}>Manual override</h3>
                <div style={{fontSize:12,color:'var(--text-dim)',marginTop:4}}>
                  {editing.employee_name} · <span className="mono">{editing.work_date}</span>
                </div>
              </div>
              <button onClick={()=>setEditing(null)} style={{padding:6,color:'var(--text-dim)'}}><Icon.X size={18}/></button>
            </div>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14}}>
              <div className="field">
                <label>Clock in (HH:MM)</label>
                <input value={editClockIn || ''} onChange={e=>setEditClockIn(e.target.value)} placeholder="e.g. 09:02"/>
              </div>
              <div className="field">
                <label>Clock out (HH:MM)</label>
                <input value={editClockOut || ''} onChange={e=>setEditClockOut(e.target.value)} placeholder="e.g. 17:10"/>
              </div>
              <div className="field" style={{gridColumn:'1 / -1'}}>
                <label>Reason (required)</label>
                <textarea rows="3" value={editReason} onChange={e=>setEditReason(e.target.value)} placeholder="Explain why this edit is needed..."/>
              </div>
            </div>
            <div style={{display:'flex',gap:10,justifyContent:'flex-end',marginTop:20}}>
              <button className="btn btn-ghost btn-sm" onClick={()=>setEditing(null)}>Cancel</button>
              <button className="btn btn-primary btn-sm" onClick={saveEdit} disabled={!editReason.trim()}>
                Save
              </button>
            </div>
          </div>
        </div>
      )}

      <style>{`
        @media (max-width: 900px) {
          .att-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
}

function AttendanceStatusBadge({ status }) {
  const map = {
    on_time: ['On Time', 'badge-green'],
    late: ['Late', 'badge-gold'],
    absent: ['Absent', 'badge-red'],
    left_early: ['Left Early', 'badge-blue'],
  };
  const [label, cls] = map[status] || [status, 'badge-muted'];
  return <span className={'badge '+cls}><span className="badge-dot" style={{background:'currentColor'}}/>{label}</span>;
}

function seedTodayRows() {
  const emps = (EMPLOYEES || []).filter(e => e.status === 'active').slice(0, 9);
  const workDate = '2026-04-26';
  const shiftStart = '09:00';
  return emps.map((e, i) => {
    const variant = i % 7;
    const clockIn =
      variant === 0 ? '08:55' :
      variant === 1 ? '09:04' :
      variant === 2 ? '09:18' :
      variant === 3 ? null :
      variant === 4 ? '09:12' :
      variant === 5 ? '08:58' :
      '09:27';
    const clockOut =
      clockIn == null ? null :
      variant === 5 ? '15:40' :
      '17:08';
    const computed = computeStatus(shiftStart, clockIn, clockOut);
    return {
      id: 'att_' + e.id,
      employee_id: e.id,
      employee_name: e.full_name,
      initials: e.initials,
      department: e.department,
      work_date: workDate,
      shift_start: shiftStart,
      clock_in: clockIn,
      clock_out: clockOut,
      status: computed.status,
      hours_worked: computed.hours_worked,
      notes: computed.status === 'absent' ? 'No punch recorded' : computed.status === 'late' ? 'Traffic reported' : computed.status === 'left_early' ? 'Left with manager approval' : '',
      manually_edited: false,
    };
  });
}

// Provide a deterministic badge count for the sidebar before the page is opened.
try {
  window.__attendanceLateTodayCount = seedTodayRows().filter(r => r.status === 'late').length;
} catch {}

function seedHistoryRows() {
  const emps = (EMPLOYEES || []).filter(e => e.status === 'active').slice(0, 8);
  const days = ['2026-04-26','2026-04-25','2026-04-24','2026-04-23','2026-04-22','2026-04-21','2026-04-20'];
  const shiftStart = '09:00';
  const out = [];
  for (const d of days) {
    emps.forEach((e, i) => {
      const seed = (d.charCodeAt(9) + i) % 9;
      const clockIn =
        seed === 0 ? '08:58' :
        seed === 1 ? '09:03' :
        seed === 2 ? '09:16' :
        seed === 3 ? null :
        seed === 4 ? '09:11' :
        seed === 5 ? '09:25' :
        seed === 6 ? '08:52' :
        '09:07';
      const clockOut = clockIn == null ? null : (seed === 6 ? '15:20' : '17:05');
      const computed = computeStatus(shiftStart, clockIn, clockOut);
      out.push({
        id: `ath_${d}_${e.id}`,
        employee_id: e.id,
        employee_name: e.full_name,
        work_date: d,
        clock_in: clockIn,
        clock_out: clockOut,
        status: computed.status,
        hours_worked: computed.hours_worked,
        notes: computed.status === 'absent' ? 'No punch recorded' : '',
      });
    });
  }
  return out;
}

function computeStatus(shiftStart, clockIn, clockOut) {
  if (!clockIn) return { status:'absent', hours_worked: null };
  const shiftMin = hhmmToMin(shiftStart);
  const inMin = hhmmToMin(clockIn);
  const outMin = clockOut ? hhmmToMin(clockOut) : null;
  const late = inMin > (shiftMin + 10);
  const leftEarly = outMin != null && outMin < (17 * 60);
  const hours = outMin != null ? Math.max(0, (outMin - inMin) / 60) : null;
  return { status: leftEarly ? 'left_early' : late ? 'late' : 'on_time', hours_worked: hours };
}

function hhmmToMin(s) {
  const m = /^(\d{1,2}):(\d{2})$/.exec(String(s || '').trim());
  if (!m) return 0;
  return parseInt(m[1], 10) * 60 + parseInt(m[2], 10);
}

const ATTENDANCE_SQL = `CREATE TABLE attendance (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  employee_id UUID REFERENCES profiles(id) ON DELETE CASCADE,
  clock_in TIMESTAMPTZ,
  clock_out TIMESTAMPTZ,
  work_date DATE DEFAULT CURRENT_DATE,
  status TEXT CHECK (status IN ('on_time','late','absent','left_early')) DEFAULT 'on_time',
  notes TEXT,
  manually_edited BOOLEAN DEFAULT FALSE,
  edited_by UUID REFERENCES profiles(id),
  edit_reason TEXT,
  device_id TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

ALTER TABLE attendance ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Boss views all attendance" ON attendance FOR ALL USING (
  EXISTS (SELECT 1 FROM profiles WHERE id = auth.uid() AND role = 'boss')
);
CREATE POLICY "Employees view own attendance" ON attendance FOR SELECT USING (
  auth.uid() = employee_id
);
CREATE POLICY "System inserts attendance" ON attendance FOR INSERT WITH CHECK (true);`;

Object.assign(window, { Attendance });

