// ReminderCenter — global reminder pop-ups that surface anywhere in the app.
// Watches contact reminders, deal follow-ups and calendar tasks; when one is due
// (scheduled time minus its lead-time), a card pops up with snooze / dismiss.
function ReminderCenter({ contacts, deals, tasks, reps, onOpenContact, onOpenDeal }) {
  const [now, setNow] = React.useState(Date.now());
  const [ackState, setAckState] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('kub_reminder_ack_v1')) || {}; } catch (e) { return {}; }
  });

  // Tick every 15s so reminders surface as time passes
  React.useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 15000);
    return () => clearInterval(id);
  }, []);

  const persist = (next) => {
    setAckState(next);
    try { localStorage.setItem('kub_reminder_ack_v1', JSON.stringify(next)); } catch (e) {}
  };

  const reminders = React.useMemo(() => {
    const list = [];
    (contacts || []).forEach(c => {
      if (c.reminder && c.reminder.date) {
        list.push({
          id: 'rc_' + c.id,
          title: (window.apptTypeLabel ? window.apptTypeLabel(c.reminder.type) : 'Reminder') + ' · ' + c.name,
          note: c.reminder.text || '',
          date: c.reminder.date, time: c.reminder.time || '09:00',
          type: c.reminder.type || 'reminder',
          lead: c.reminder.leadMinutes != null ? c.reminder.leadMinutes : 15,
          who: c.owner || '',
          link: { kind: 'contact', id: c.id },
        });
      }
    });
    (deals || []).forEach(d => {
      if (d.followUpReminder && d.followUpReminder.date) {
        list.push({
          id: 'rd_' + d.id,
          title: (window.apptTypeLabel ? window.apptTypeLabel(d.followUpReminder.type) : 'Follow up') + ' · ' + d.customer,
          note: d.followUpReminder.note || '',
          date: d.followUpReminder.date, time: d.followUpReminder.time || '09:00',
          type: d.followUpReminder.type || 'reminder',
          lead: d.followUpReminder.leadMinutes != null ? d.followUpReminder.leadMinutes : 15,
          who: d.repName || '',
          link: { kind: 'deal', id: d.id },
        });
      }
    });
    (tasks || []).forEach(t => {
      if (t.date) {
        const repName = (reps || []).find(r => r.id === t.repId)?.name || '';
        list.push({
          id: 'rt_' + t.id,
          title: t.title || 'Task',
          note: t.notes || '',
          date: t.date, time: t.time || '09:00',
          type: t.type || 'task',
          lead: t.leadMinutes != null ? t.leadMinutes : 15,
          who: repName,
          link: t.contactId ? { kind: 'contact', id: t.contactId } : (t.link || null),
        });
      }
    });
    return list;
  }, [contacts, deals, tasks, reps]);

  const GRACE = 12 * 3600 * 1000; // don't auto-pop reminders whose time passed > 12h ago (avoids old data spam)
  const active = reminders.map(r => {
    const sched = new Date(r.date + 'T' + (r.time || '09:00')).getTime();
    const due = sched - (r.lead || 0) * 60000;
    return { ...r, sched, due };
  }).filter(r => {
    if (isNaN(r.sched)) return false;
    const st = ackState[r.id] || {};
    if (st.acked) return false;
    if (st.snoozeUntil) return now >= st.snoozeUntil;           // re-surface once snooze elapses
    return now >= r.due && now <= r.sched + GRACE;              // due, within grace
  }).sort((a, b) => a.sched - b.sched).slice(0, 4);

  if (!active.length) return null;

  const snooze = (r, minutes) => persist({ ...ackState, [r.id]: { snoozeUntil: Date.now() + minutes * 60000 } });
  const dismiss = (r) => persist({ ...ackState, [r.id]: { acked: true } });
  const open = (r) => {
    if (r.link?.kind === 'contact') { const c = (contacts || []).find(x => x.id === r.link.id); if (c && onOpenContact) onOpenContact(c); }
    else if (r.link?.kind === 'deal') { const d = (deals || []).find(x => x.id === r.link.id); if (d && onOpenDeal) onOpenDeal(d); }
    dismiss(r);
  };

  return (
    <div style={{ position: 'fixed', right: 20, bottom: 20, zIndex: 300, display: 'flex', flexDirection: 'column', gap: 10, width: 350, maxWidth: 'calc(100vw - 40px)' }}>
      {active.map(r => <ReminderCard key={r.id} r={r} now={now} onSnooze={snooze} onDismiss={dismiss} onOpen={open}/>)}
    </div>
  );
}

function ReminderCard({ r, now, onSnooze, onDismiss, onOpen }) {
  const [snoozeMin, setSnoozeMin] = React.useState(10);
  const overdue = now >= r.sched;
  const mins = Math.round(Math.abs(r.sched - now) / 60000);
  const rel = mins < 60 ? mins + ' min' : mins < 1440 ? Math.round(mins / 60) + ' h' : Math.round(mins / 1440) + ' d';
  const dateLabel = (() => {
    const d = new Date(r.date + 'T00:00:00');
    const t = new Date(); t.setHours(0, 0, 0, 0);
    const diff = Math.round((d - t) / 86400000);
    if (diff === 0) return 'today';
    if (diff === 1) return 'tomorrow';
    if (diff === -1) return 'yesterday';
    return d.toLocaleDateString('en-AU', { weekday: 'short', day: 'numeric', month: 'short' });
  })();
  const accent = (window.reminderTypeColor && window.reminderTypeColor(r.type)) || 'var(--accent)';

  return (
    <div style={{
      background: 'var(--surface)', border: '1px solid var(--border-strong)',
      borderRadius: 'var(--r-lg)', boxShadow: 'var(--shadow-lg)', overflow: 'hidden',
      animation: 'slideUp 0.18s ease',
    }}>
      <div style={{ height: 3, background: accent }}></div>
      <div style={{ padding: '12px 14px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 7 }}>
          <span style={{ width: 24, height: 24, borderRadius: 7, background: 'var(--accent-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name="alert" size={13} color="var(--accent-ink)"/>
          </span>
          <span style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.07em', fontWeight: 600, color: overdue ? 'var(--lost)' : 'var(--accent-ink)' }}>
            {overdue ? (mins < 2 ? 'Due now' : 'Overdue ' + rel) : 'Reminder · in ' + rel}
          </span>
          <button onClick={() => onDismiss(r)} className="detail-close" style={{ marginLeft: 'auto', padding: 3 }} title="Dismiss">
            <Icon name="close" size={14}/>
          </button>
        </div>

        <div style={{ fontSize: 13.5, fontWeight: 600, letterSpacing: '-0.01em', lineHeight: 1.3 }}>{r.title}</div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 3 }}>
          {dateLabel} at {r.time}{r.who ? ' · ' + r.who : ''}
        </div>
        {r.note && <div style={{ fontSize: 11.5, color: 'var(--ink-2)', fontStyle: 'italic', marginTop: 5 }}>“{r.note.slice(0, 90)}”</div>}

        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 11 }}>
          <select
            className="sel"
            value={snoozeMin}
            onChange={(e) => setSnoozeMin(Number(e.target.value))}
            style={{ fontSize: 11.5, padding: '4px 22px 4px 8px' }}
            title="Snooze duration"
          >
            {(window.SNOOZE_OPTS || [{ v: 10, label: '10 minutes' }]).map(o => <option key={o.v} value={o.v}>{o.label}</option>)}
          </select>
          <button className="btn sm" onClick={() => onSnooze(r, snoozeMin)}>
            <Icon name="clock" size={11}/> Snooze
          </button>
          <button className="btn sm primary" style={{ marginLeft: 'auto' }} onClick={() => onOpen(r)}>
            Open
          </button>
        </div>
      </div>
    </div>
  );
}

// Shared reminder/appt type colour (mirrors the Calendar palette)
window.reminderTypeColor = function (t) {
  const map = {
    design_appt: 'oklch(0.5 0.12 145)', quote_presentation: 'oklch(0.5 0.13 30)',
    forecast_deposit: 'oklch(0.6 0.14 70)', reminder: 'oklch(0.55 0.13 60)',
    site_visit: 'oklch(0.5 0.1 240)', call: 'oklch(0.5 0.1 200)', call_customer: 'oklch(0.5 0.1 200)',
    followup_call: 'oklch(0.55 0.13 60)', showroom_visit: 'var(--accent)',
    contract_signing: 'oklch(0.45 0.13 300)', payment_followup: 'oklch(0.5 0.13 30)',
    install_check: 'oklch(0.5 0.12 145)', meeting: 'var(--accent)', task: 'oklch(0.4 0.05 240)',
  };
  return map[t] || 'var(--accent)';
};

window.ReminderCenter = ReminderCenter;
