// screen-reminders.jsx — push-notification-style list grouped by trigger type.

function RemindersScreen({ theme, customers, schedule, openCustomer }) {
  const today = todayISO();
  // push state, shared by the bell button and the enable card
  const [pushSt, setPushSt] = React.useState('off');
  const [pushBusy, setPushBusy] = React.useState(false);
  React.useEffect(() => { if (window.Push) Push.status().then(setPushSt); }, []);
  const enablePush = async () => {
    if (!window.Push) return;
    if (pushSt === 'unsupported' || pushSt === 'denied') {
      alert(pushSt === 'unsupported'
        ? 'Add the app to your home screen first, then turn on notifications (iPhone rule).'
        : 'Notifications are blocked. Turn them on in your phone Settings for this app.');
      return;
    }
    setPushBusy(true);
    const r = await Push.enable();
    setPushBusy(false);
    setPushSt(r.ok ? 'on' : (r.reason || 'off'));
  };
  // Today's reminders: callbacks + appointments due today, plus nurturing customers
  // whose ready-date has arrived.
  const reminders = [];
  customers.forEach(c => {
    if (c.callbackAt && c.callbackAt.slice(0, 10) === today)
      reminders.push({ id: c.id + '-cb', t: c.callbackAt.slice(11, 16), kind: 'callback', icon: 'phone', tone: 'blue',
        title: 'Call back ' + (c.name || 'customer'), sub: c.car || '', tag: c.callbackLabel || '', cid: c.id, when: c.callbackAt.slice(11, 16) });
    if (c.appointmentAt && c.appointmentAt.slice(0, 10) === today)
      reminders.push({ id: c.id + '-appt', t: c.appointmentAt.slice(11, 16), kind: 'appt', icon: 'calendar', tone: 'blue',
        title: (c.name || 'Customer') + ' · appointment', sub: c.car || '', tag: c.appointmentLabel || '', cid: c.id, when: c.appointmentAt.slice(11, 16) });
    if (c.nurturing && c.readyDate && c.readyDate <= today)
      reminders.push({ id: c.id + '-nurt', t: 'Today', kind: 'nurturing', icon: 'sprout', tone: 'green',
        title: (c.name || 'Customer') + ' is ready', sub: c.car ? ('Wants ' + String(c.car).toLowerCase()) : 'Nurturing customer',
        cid: c.id, when: 'auto-resurfaced' });
  });
  reminders.sort((a, b) => (a.when || '').localeCompare(b.when || ''));

  // ALL active appointments (any date, not yet completed). Completing clears the
  // date, so anything with appointmentAt set is still outstanding. Oldest first
  // so overdue ones surface at the top.
  const allAppointments = customers
    .filter(c => c.appointmentAt)
    .sort((a, b) => a.appointmentAt.localeCompare(b.appointmentAt))
    .map(c => {
      const day = c.appointmentAt.slice(0, 10);
      const overdue = day < today;
      return {
        id: c.id + '-allappt', icon: 'calendar', tone: overdue ? 'red' : 'blue',
        title: c.name || 'Customer',
        sub: c.car || '', tag: c.appointmentLabel || '',
        t: fmtTime(c.appointmentAt.slice(11, 16)),
        when: (overdue ? 'Overdue · ' : '') + humanDate(day),
        cid: c.id,
      };
    });

  return (
    <React.Fragment>
      <TopBar theme={theme} large
        kicker={reminders.length ? ('Push notifications · ' + reminders.length + ' ahead') : 'Push notifications'}
        title="Reminders"
        trailing={
          <button onClick={enablePush} title="Notifications" style={{
            border: 'none', width: 44, height: 44,
            borderRadius: 99, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            background: pushSt === 'on' ? (theme.accentSolid || theme.blue) : theme.surface,
            color: pushSt === 'on' ? '#fff' : theme.text,
            border: `0.5px solid ${pushSt === 'on' ? 'transparent' : theme.border}`,
          }}>
            <Icon name="bell" size={16}/>
          </button>
        }
      />

      <ScrollBody>
        <PushEnable theme={theme} st={pushSt} busy={pushBusy} onEnable={enablePush} />
        <SectionHeader theme={theme} title="Upcoming" count={reminders.length} kicker="TODAY"/>
        {reminders.length === 0 ? (
          <Card theme={theme}>
            <div style={{ padding: '8px 2px', textAlign: 'center' }}>
              <div style={{ color: theme.text, fontSize: 15, fontWeight: 600, letterSpacing: -0.2 }}>Nothing due yet</div>
              <div style={{ color: theme.textMute, fontSize: 13, marginTop: 4, lineHeight: 1.45 }}>
                Callbacks, appointments and nurturing ready-dates will show up here.
              </div>
            </div>
          </Card>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {reminders.map(r => (
              <ReminderCard key={r.id} r={r} theme={theme}
                onClick={() => openCustomer(r.cid)} />
            ))}
          </div>
        )}

        {/* All active appointments — every booked appointment not yet completed */}
        <div style={{ marginTop: 22 }}>
          <SectionHeader theme={theme} title="All appointments" count={allAppointments.length} kicker="BOOKED" />
          {allAppointments.length === 0 ? (
            <Card theme={theme}>
              <div style={{ padding: '8px 2px', textAlign: 'center', color: theme.textMute, fontSize: 13.5 }}>
                No appointments booked. Set one on a customer's card.
              </div>
            </Card>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {allAppointments.map(r => (
                <ReminderCard key={r.id} r={r} theme={theme} onClick={() => openCustomer(r.cid)} />
              ))}
            </div>
          )}
        </div>

        <div style={{ marginTop: 22 }}>
          <SectionHeader theme={theme} title="Notification settings" kicker="QUIET HOURS"/>
          <Card theme={theme}>
            <SettingRow theme={theme} label="Lead-in window" value="15 min before" />
            <Divider2 theme={theme}/>
            <SettingRow theme={theme} label="Quiet hours" value="7:00 PM – 7:00 AM" />
            <Divider2 theme={theme}/>
            <SettingRow theme={theme} label="Nurturing resurfacing" value="On ready-date · 9:00 AM" />
          </Card>
        </div>

        <div style={{ height: 100 }} />
      </ScrollBody>
    </React.Fragment>
  );
}

function ReminderCard({ r, theme, onClick, past }) {
  const toneMap = {
    blue: { bg: theme.blueSoft, ink: theme.blueInk },
    green: { bg: theme.greenSoft, ink: theme.greenInk },
    red: { bg: theme.redSoft, ink: theme.redInk },
    neutral: { bg: theme.chip, ink: theme.chipInk },
  };
  const t = toneMap[r.tone];
  return (
    <Card theme={theme} onClick={onClick} style={{ opacity: past ? 0.6 : 1 }}>
      <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        <div style={{
          width: 42, height: 42, borderRadius: 12,
          background: t.bg, color: t.ink, flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name={r.icon} size={20} stroke={1.9}/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8,
          }}>
            <span style={{ fontSize: 15, fontWeight: 600, color: theme.text, letterSpacing: -0.2 }}>
              {r.title}
            </span>
            <span style={{ fontSize: 12, color: t.ink, fontWeight: 600, letterSpacing: -0.05, whiteSpace: 'nowrap' }}>
              {fmtTime(r.t)}
            </span>
          </div>
          {r.tag && (
            <div style={{ marginTop: 5 }}>
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 4,
                background: theme.blueSoft, color: theme.blueInk,
                fontSize: 11, fontWeight: 600, letterSpacing: -0.05, padding: '3px 8px', borderRadius: 99,
              }}>
                <Icon name="tag" size={10} stroke={2.2}/>{r.tag}
              </span>
            </div>
          )}
          {r.sub && (
            <div style={{ fontSize: 12.5, color: theme.textMute, marginTop: 4, letterSpacing: -0.05 }}>
              {r.sub}
            </div>
          )}
          <div style={{ fontSize: 11.5, color: theme.textDim, marginTop: 4 }}>
            {fmtTime(r.when)}
          </div>
        </div>
      </div>
    </Card>
  );
}

function SettingRow({ theme, label, value }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '10px 0',
    }}>
      <span style={{ fontSize: 14.5, color: theme.text, letterSpacing: -0.15 }}>{label}</span>
      <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
        <span style={{ fontSize: 13, color: theme.textMute, letterSpacing: -0.1 }}>{value}</span>
        <Icon name="chevron" size={14} style={{ color: theme.textDim }}/>
      </div>
    </div>
  );
}

function Divider2({ theme }) {
  return <div style={{ height: 0.5, background: theme.border }} />;
}

function PushEnable({ theme, st, busy, onEnable }) {
  if (st === 'on') return null;
  const msg = st === 'unsupported'
    ? 'Add the app to your home screen first, then turn this on (iOS rule).'
    : st === 'denied'
      ? 'Notifications are blocked — turn them on in your phone Settings.'
      : 'Get a buzz when callbacks, appointments and nurturing dates are due.';
  return (
    <Card theme={theme} style={{ marginBottom: 12 }}>
      <div style={{ fontSize: 15, fontWeight: 600, color: theme.text, letterSpacing: -0.2 }}>Turn on reminders</div>
      <div style={{ fontSize: 13, color: theme.textMute, marginTop: 4, lineHeight: 1.4 }}>{msg}</div>
      {(st === 'off' || st === 'save_failed') && (
        <button onClick={onEnable} disabled={busy} style={{
          marginTop: 12, width: '100%', border: 'none', padding: '13px 16px', borderRadius: 12, minHeight: 48,
          background: theme.accentGrad || theme.blue, color: '#fff', fontFamily: 'inherit',
          fontSize: 15, fontWeight: 600, cursor: 'pointer', boxShadow: '0 8px 20px rgba(95,90,240,0.40)',
        }}>{busy ? 'Enabling…' : 'Enable on this device'}</button>
      )}
    </Card>
  );
}

window.RemindersScreen = RemindersScreen;
