// screen-today.jsx — Alex's day, scannable in 5 seconds.

function TodayScreen({ theme, dark, customers, schedule, openCustomer, setTab, onComplete, onHotDone, onOpenDeliveries, onOpenChat, todos, onAddTodo, onToggleTodo, onDeleteTodo }) {
  const byId = Object.fromEntries(customers.map(c => [c.id, c]));
  const nowD = new Date();
  const today = isoDate(nowD);
  const nowMinutes = nowD.getHours() * 60 + nowD.getMinutes();
  const dateLabel = nowD.toLocaleDateString('en-AU', { weekday: 'short', day: 'numeric', month: 'short' });
  const hr = nowD.getHours();
  const greeting = hr < 12 ? 'Good morning, Alex' : hr < 17 ? 'Good afternoon, Alex' : 'Good evening, Alex';

  // bucket schedule by past/now/future
  const apptItems = schedule.filter(s => s.kind === 'appt');
  const callbackItems = schedule.filter(s => s.kind === 'callback');

  // "Ready now" nurturing customers (readyDate <= today)
  const readyNow = customers.filter(c => c.nurturing && c.readyDate && c.readyDate <= today);

  // Hot leads — red status, not in today's schedule, not already ticked off for today
  const inSchedule = new Set(schedule.map(s => s.customerId));
  const hotLeads = customers.filter(c => c.status === 'red' && !inSchedule.has(c.id) && c.hotDoneOn !== today);
  const deliveryCount = customers.filter(c => c.stage === 'Delivery').length;

  return (
    <React.Fragment>
      <TopBar theme={theme} large
        kicker={dateLabel}
        title={greeting}
        trailing={
          <React.Fragment>
            <button onClick={onOpenChat} title="Alejandro" style={{
              border: `0.5px solid ${theme.border}`, background: theme.surface, padding: 0, overflow: 'hidden',
              width: 44, height: 44, borderRadius: 99, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <img src="./alejandro.jpg?v=2" alt="Alejandro" style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                onError={(e) => { e.target.style.display = 'none'; }} />
            </button>
            <button onClick={onOpenDeliveries} title="Pending deliveries" style={{
              position: 'relative', border: `0.5px solid ${theme.border}`, background: theme.surface,
              width: 44, height: 44, borderRadius: 99, color: theme.text, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name="car" size={18} stroke={2}/>
              {deliveryCount > 0 && (
                <span style={{
                  position: 'absolute', top: -3, right: -3, minWidth: 18, height: 18, padding: '0 4px',
                  borderRadius: 99, background: theme.accentSolid || theme.blue, color: '#fff',
                  fontSize: 10.5, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{deliveryCount}</span>
              )}
            </button>
          </React.Fragment>
        }
      />

      <ScrollBody>
        {/* Day summary strip */}
        <DaySummary theme={theme}
          counts={{ appts: apptItems.length, callbacks: callbackItems.length,
                    ready: readyNow.length, hot: hotLeads.length }}
        />

        {/* TIMELINE — Today's schedule */}
        <div style={{ marginTop: 22 }}>
          <CollapsibleSection theme={theme} title="Schedule" count={schedule.length}
            kicker="TODAY" storageKey="schedule">
            <Timeline theme={theme} schedule={schedule} byId={byId}
              nowMinutes={nowMinutes} openCustomer={openCustomer} onComplete={onComplete} />
          </CollapsibleSection>
        </div>

        {/* TO-DO — personal tasks, not tied to a customer */}
        <div style={{ marginTop: 22 }}>
          <CollapsibleSection theme={theme} title="To-do" count={(todos || []).filter(t => !t.done).length}
            kicker="TASKS" storageKey="todo">
            <TodoSection theme={theme} todos={todos || []} onAdd={onAddTodo} onToggle={onToggleTodo} onDelete={onDeleteTodo} />
          </CollapsibleSection>
        </div>

        {/* READY NOW — most important feature */}
        {readyNow.length > 0 && (
          <div style={{ marginTop: 22 }}>
            <CollapsibleSection theme={theme} title="Ready now" count={readyNow.length}
              kicker="NURTURING" storageKey="ready"
              action={() => setTab('nurturing')} actionLabel="See all">
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {readyNow.map(c => (
                  <ReadyNowCard key={c.id} c={c} theme={theme} onClick={() => openCustomer(c.id)} />
                ))}
              </div>
            </CollapsibleSection>
          </div>
        )}

        {/* HOT LEADS */}
        {hotLeads.length > 0 && (
          <div style={{ marginTop: 22 }}>
            <CollapsibleSection theme={theme} title="Hot leads" count={hotLeads.length}
              kicker="STILL TO WORK" storageKey="hot">
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {hotLeads.map(c => (
                  <HotLeadCard key={c.id} c={c} theme={theme} onClick={() => openCustomer(c.id)}
                    onDone={onHotDone} />
                ))}
              </div>
            </CollapsibleSection>
          </div>
        )}

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

// ─── day summary strip ─────────────────────────────────────────
function DaySummary({ theme, counts }) {
  const items = [
    { n: counts.appts, label: 'Appts', icon: 'calendar', tone: 'blue' },
    { n: counts.callbacks, label: 'Callbacks', icon: 'phone', tone: 'blue' },
    { n: counts.ready, label: 'Ready now', icon: 'sprout', tone: 'green' },
    { n: counts.hot, label: 'Hot', icon: 'flame', tone: 'red' },
  ];
  const toneInk = { blue: theme.blueInk, red: theme.redInk, green: theme.greenInk };
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginTop: 4,
    }}>
      {items.map((it, i) => (
        <div key={i} style={{
          background: theme.surface, borderRadius: 14, padding: '10px 8px',
          border: `0.5px solid ${theme.border}`,
          display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 2,
        }}>
          <span style={{ color: toneInk[it.tone], display: 'flex', alignItems: 'center', gap: 4 }}>
            <Icon name={it.icon} size={14} stroke={2}/>
          </span>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
            <span style={{ fontSize: 24, fontWeight: 700, color: theme.text, letterSpacing: -0.5, lineHeight: 1 }}>{it.n}</span>
          </div>
          <span style={{ fontSize: 11, fontWeight: 500, color: theme.textMute, letterSpacing: -0.1 }}>{it.label}</span>
        </div>
      ))}
    </div>
  );
}

// ─── timeline ─────────────────────────────────────────────────
function Timeline({ theme, schedule, byId, nowMinutes, openCustomer, onComplete }) {
  // Split: timed items first (sorted), untimed at bottom.
  const timed = schedule.filter(s => s.time).sort((a, b) => a.time.localeCompare(b.time));
  const untimed = schedule.filter(s => !s.time);
  if (schedule.length === 0) {
    return (
      <div style={{ paddingLeft: 4 }}>
        <div style={{
          background: theme.surface, borderRadius: 14, border: `0.5px solid ${theme.border}`,
          padding: '16px', textAlign: 'center', color: theme.textMute, fontSize: 13.5, letterSpacing: -0.1,
        }}>Nothing scheduled today.</div>
      </div>
    );
  }
  return (
    <div style={{ position: 'relative', paddingLeft: 74 }}>
      {/* vertical rail */}
      <div style={{
        position: 'absolute', left: 8, top: 12, bottom: 12, width: 1,
        background: theme.border,
      }} />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {timed.map((s, idx) => {
          const c = byId[s.customerId];
          const [hh, mm] = s.time.split(':').map(Number);
          const mins = hh * 60 + mm;
          const isPast = mins < nowMinutes;
          const isNext = !isPast && timed.slice(0, idx).every(p => {
            const [ph, pm] = p.time.split(':').map(Number); return ph*60+pm < nowMinutes;
          });
          return (
            <TimelineRow key={'t'+idx} theme={theme} item={s} c={c}
              isPast={isPast} isNext={isNext} onClick={() => openCustomer(c.id)}
              onComplete={onComplete} />
          );
        })}
        {untimed.map((s, idx) => {
          const c = byId[s.customerId];
          return (
            <TimelineRow key={'u'+idx} theme={theme} item={s} c={c}
              isPast={false} isNext={false} untimed onClick={() => openCustomer(c.id)}
              onComplete={onComplete} />
          );
        })}
      </div>
    </div>
  );
}

function TimelineRow({ theme, item, c, isPast, isNext, untimed, onClick, onComplete }) {
  const tint = item.kind === 'appt' ? theme.blue
    : item.kind === 'callback' ? theme.blue
    : theme.textDim;
  const iconName = item.kind === 'appt' ? 'calendar'
    : item.kind === 'callback' ? 'phone'
    : 'note';

  return (
    <div style={{ position: 'relative' }}>
      {/* dot — sits on the rail at x≈8 */}
      <div style={{
        position: 'absolute', left: -72, top: 18,
        width: 12, height: 12, borderRadius: 99,
        background: untimed ? theme.surface : (isPast ? theme.surface : tint),
        border: untimed ? `2px dashed ${theme.borderStrong}` : (isPast ? `2px solid ${theme.border}` : `2px solid ${theme.bg}`),
        boxShadow: isNext ? `0 0 0 4px ${theme.blueSoft}` : 'none',
      }} />
      {/* time label — clear of the dot, between rail and card */}
      <div style={{
        position: 'absolute', left: -54, top: 14, width: 50,
        fontSize: untimed ? 11 : 12,
        fontWeight: untimed ? 500 : 600, lineHeight: 1.15,
        color: untimed ? theme.textDim : (isPast ? theme.textDim : theme.text),
        letterSpacing: -0.2,
        textTransform: untimed ? 'uppercase' : 'none',
      }}>{untimed ? 'Anytime' : fmtTime(item.time)}</div>
      <Card theme={theme} onClick={onClick} status={c.status}
        style={{ opacity: isPast ? 0.55 : 1 }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
          <Avatar name={c.name} theme={theme} size={42}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8,
            }}>
              <span style={{ fontSize: 16, fontWeight: 600, color: theme.text, letterSpacing: -0.2 }}>
                {c.name}
              </span>
              <span style={{
                fontSize: 11.5, fontWeight: 600, color: tint, display: 'flex', alignItems: 'center', gap: 4,
              }}>
                <Icon name={iconName} size={12} stroke={2.2}/>
                {item.kind.toUpperCase()}
              </span>
            </div>
            {item.tag && (
              <div style={{ marginTop: 5 }}>
                <span style={{
                  display: 'inline-flex', alignItems: 'center', gap: 4,
                  background: theme.blueSoft, color: theme.blueInk,
                  fontSize: 11.5, fontWeight: 600, letterSpacing: -0.05,
                  padding: '3px 9px', borderRadius: 99,
                }}>
                  <Icon name="tag" size={11} stroke={2.2}/>{item.tag}
                </span>
              </div>
            )}
            <div style={{
              fontSize: 13, color: theme.textMute, marginTop: 5,
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', letterSpacing: -0.1,
            }}>{c.car || item.label} · {c.location}</div>
            {c.notes && (
              <div style={{
                fontSize: 12.5, color: theme.textMute, marginTop: 6, letterSpacing: -0.05,
                lineHeight: 1.4, display: 'flex', gap: 6,
                background: theme.chip, borderRadius: 8, padding: '6px 8px',
              }}>
                <Icon name="note" size={13} stroke={2} style={{ color: theme.textDim, flexShrink: 0, marginTop: 1 }}/>
                <span style={{ whiteSpace: 'pre-wrap', overflow: 'hidden' }}>{c.notes}</span>
              </div>
            )}
          </div>
          {/* mark done */}
          {onComplete && (
            <button onClick={(e) => { e.stopPropagation(); onComplete(c.id, item.kind); }}
              title="Mark done" style={{
              flexShrink: 0, width: 36, height: 36, borderRadius: 99, cursor: 'pointer',
              border: `1.5px solid ${theme.borderStrong}`, background: 'transparent',
              color: theme.textMute, display: 'flex', alignItems: 'center', justifyContent: 'center',
              marginTop: 2,
            }}>
              <Icon name="check" size={16} stroke={2.5}/>
            </button>
          )}
        </div>
      </Card>
    </div>
  );
}

// ─── ready-now nurturing card ─────────────────────────────────
function ReadyNowCard({ c, theme, onClick }) {
  return (
    <Card theme={theme} onClick={onClick} status="neutral" style={{ paddingLeft: 16 }}>
      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <div style={{
          width: 42, height: 42, borderRadius: 12,
          background: theme.greenSoft, color: theme.greenInk,
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <Icon name="sprout" size={20} stroke={2}/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
            <span style={{ fontSize: 16, fontWeight: 600, color: theme.text, letterSpacing: -0.2 }}>
              {c.name}
            </span>
            <Chip theme={theme} tone="green">Ready now</Chip>
          </div>
          <div style={{ fontSize: 13, color: theme.textMute, marginTop: 2, letterSpacing: -0.1,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            Wants {(c.car || 'a car').toLowerCase()}
          </div>
          <div style={{ fontSize: 12, color: theme.textDim, marginTop: 3 }}>
            Parked {readyAgo(c)} · {c.location}
          </div>
          {c.notes && <NoteLine c={c} theme={theme} />}
        </div>
      </div>
    </Card>
  );
}

// shared note chip used across Today cards
function NoteLine({ c, theme }) {
  return (
    <div style={{
      fontSize: 12.5, color: theme.textMute, marginTop: 6, letterSpacing: -0.05,
      lineHeight: 1.4, display: 'flex', gap: 6,
      background: theme.chip, borderRadius: 8, padding: '6px 8px',
    }}>
      <Icon name="note" size={13} stroke={2} style={{ color: theme.textDim, flexShrink: 0, marginTop: 1 }}/>
      <span style={{ whiteSpace: 'pre-wrap', overflow: 'hidden' }}>{c.notes}</span>
    </div>
  );
}

function readyAgo(c) {
  // tiny mock — just return a human-friendly label from history
  const first = c.history?.[0]?.d || 'earlier';
  return first.includes('Mar') ? '2 months ago'
    : first.includes('Apr') ? '5 weeks ago'
    : 'recently';
}

// ─── hot lead card ────────────────────────────────────────────
function HotLeadCard({ c, theme, onClick, onDone }) {
  return (
    <Card theme={theme} onClick={onClick} status={c.status}>
      <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        <Avatar name={c.name} theme={theme} size={42}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
            <span style={{ fontSize: 16, fontWeight: 600, color: theme.text, letterSpacing: -0.2 }}>
              {c.name}
            </span>
            <Chip theme={theme} tone="red" icon="flame">Hot</Chip>
          </div>
          <div style={{ fontSize: 13, color: theme.textMute, marginTop: 2, letterSpacing: -0.1,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {c.car}
          </div>
          <div style={{ fontSize: 12, color: theme.textDim, marginTop: 3 }}>
            {c.source}
          </div>
          {c.notes && <NoteLine c={c} theme={theme} />}
        </div>
        {/* tick off for today — reappears tomorrow */}
        {onDone && (
          <button onClick={(e) => { e.stopPropagation(); onDone(c.id); }}
            title="Done for today" style={{
            flexShrink: 0, width: 36, height: 36, borderRadius: 99, cursor: 'pointer',
            border: `1.5px solid ${theme.borderStrong}`, background: 'transparent',
            color: theme.textMute, display: 'flex', alignItems: 'center', justifyContent: 'center',
            marginTop: 2,
          }}>
            <Icon name="check" size={16} stroke={2.5}/>
          </button>
        )}
      </div>
    </Card>
  );
}

// ─── collapsible section wrapper (remembers open/closed per device) ─────────
function CollapsibleSection({ theme, title, count, kicker, action, actionLabel, storageKey, defaultOpen = true, children }) {
  const key = 'alexcrm_sec_' + storageKey;
  const [open, setOpen] = React.useState(() => {
    try { const v = localStorage.getItem(key); return v === null ? defaultOpen : v === '1'; } catch { return defaultOpen; }
  });
  const toggle = () => setOpen(o => { const n = !o; try { localStorage.setItem(key, n ? '1' : '0'); } catch {} return n; });
  return (
    <div>
      <div onClick={toggle} style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '0 4px 8px', cursor: 'pointer',
      }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          {kicker && <span style={{
            fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase', color: theme.textMute,
          }}>{kicker}</span>}
          <span style={{ fontSize: 17, fontWeight: 700, color: theme.text, letterSpacing: -0.3 }}>{title}</span>
          {count !== undefined && <span style={{ fontSize: 14, fontWeight: 500, color: theme.textDim }}>{count}</span>}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          {action && <button onClick={(e) => { e.stopPropagation(); action(); }} style={{
            border: 'none', background: 'transparent', color: theme.blue,
            fontFamily: 'inherit', fontSize: 14, fontWeight: 600, padding: '6px 8px', margin: '-6px -2px', cursor: 'pointer',
          }}>{actionLabel || 'See all'}</button>}
          <Icon name="chevron-down" size={18} stroke={2}
            style={{ color: theme.textDim, transform: open ? 'none' : 'rotate(-90deg)', transition: 'transform 0.15s' }}/>
        </div>
      </div>
      {open && children}
    </div>
  );
}

// ─── to-do list (personal tasks) ───────────────────────────────
function TodoSection({ theme, todos, onAdd, onToggle, onDelete }) {
  const [text, setText] = React.useState('');
  const submit = () => { const t = text.trim(); if (t) { onAdd(t); setText(''); } };
  const sorted = [...todos].sort((a, b) => (a.done ? 1 : 0) - (b.done ? 1 : 0));
  return (
    <div>
      <div style={{ display: 'flex', gap: 8, marginBottom: sorted.length ? 10 : 0 }}>
        <input value={text} onChange={e => setText(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') submit(); }}
          placeholder="Add a task…"
          style={{
            flex: 1, border: `0.5px solid ${theme.border}`, background: theme.surface, color: theme.text,
            borderRadius: 12, padding: '12px 14px', fontFamily: 'inherit', fontSize: 15, outline: 'none', minHeight: 44,
          }} />
        <button onClick={submit} disabled={!text.trim()} style={{
          flexShrink: 0, width: 44, height: 44, borderRadius: 99, border: 'none', cursor: 'pointer',
          background: text.trim() ? (theme.accentSolid || theme.blue) : theme.chip,
          color: text.trim() ? '#fff' : theme.textDim,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}><Icon name="plus" size={20} stroke={2.4}/></button>
      </div>
      {sorted.length === 0 ? (
        <div style={{
          background: theme.surface, borderRadius: 14, border: `0.5px solid ${theme.border}`,
          padding: '14px 16px', textAlign: 'center', color: theme.textMute, fontSize: 13.5, letterSpacing: -0.1,
        }}>Nothing on the list. Add a task above.</div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {sorted.map(t => (
            <div key={t.id} style={{
              display: 'flex', alignItems: 'center', gap: 12, background: theme.surface,
              border: `0.5px solid ${theme.border}`, borderRadius: 12, padding: '11px 12px',
            }}>
              <button onClick={() => onToggle(t.id)} style={{
                flexShrink: 0, width: 24, height: 24, borderRadius: 99, cursor: 'pointer', padding: 0,
                border: t.done ? 'none' : `1.5px solid ${theme.borderStrong}`,
                background: t.done ? theme.green : 'transparent', color: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{t.done && <Icon name="check" size={14} stroke={3}/>}</button>
              <span style={{
                flex: 1, fontSize: 15, letterSpacing: -0.15, lineHeight: 1.35,
                color: t.done ? theme.textDim : theme.text,
                textDecoration: t.done ? 'line-through' : 'none', whiteSpace: 'pre-wrap',
              }}>{t.text}</span>
              <button onClick={() => onDelete(t.id)} title="Delete" style={{
                flexShrink: 0, width: 32, height: 32, borderRadius: 99, cursor: 'pointer',
                border: 'none', background: 'transparent', color: theme.textDim,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}><Icon name="x" size={15} stroke={2.2}/></button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

window.TodayScreen = TodayScreen;
