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

function TodayScreen({ theme, dark, customers, schedule, openCustomer, setTab }) {
  const byId = Object.fromEntries(customers.map(c => [c.id, c]));
  const now = { h: 9, m: 12 }; // mocked "now"
  const nowMinutes = now.h * 60 + now.m;

  // 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 <= '2026-05-24');

  // Hot leads — red status, not in today's schedule
  const inSchedule = new Set(schedule.map(s => s.customerId));
  const hotLeads = customers.filter(c => c.status === 'red' && !inSchedule.has(c.id));

  return (
    <React.Fragment>
      <TopBar theme={theme} large
        kicker="Sun · 24 May"
        title="Good morning, Alex"
      />

      <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 }}>
          <SectionHeader theme={theme} title="Schedule" count={schedule.length}
            kicker="TODAY" />
          <Timeline theme={theme} schedule={schedule} byId={byId}
            nowMinutes={nowMinutes} openCustomer={openCustomer} />
        </div>

        {/* READY NOW — most important feature */}
        {readyNow.length > 0 && (
          <div style={{ marginTop: 22 }}>
            <SectionHeader theme={theme} title="Ready now" count={readyNow.length}
              kicker="NURTURING"
              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>
          </div>
        )}

        {/* HOT LEADS */}
        {hotLeads.length > 0 && (
          <div style={{ marginTop: 22 }}>
            <SectionHeader theme={theme} title="Hot leads" count={hotLeads.length}
              kicker="STILL TO WORK" />
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {hotLeads.map(c => (
                <HotLeadCard key={c.id} c={c} theme={theme} onClick={() => openCustomer(c.id)} />
              ))}
            </div>
          </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 }) {
  // 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);
  return (
    <div style={{ position: 'relative', paddingLeft: 70 }}>
      {/* 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)} />
          );
        })}
        {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)} />
          );
        })}
      </div>
    </div>
  );
}

function TimelineRow({ theme, item, c, isPast, isNext, untimed, onClick }) {
  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 (leftmost column) */}
      <div style={{
        position: 'absolute', left: -68, 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 */}
      <div style={{
        position: 'absolute', left: -52, top: 14, width: 44,
        fontSize: untimed ? 11 : 13,
        fontWeight: untimed ? 500 : 600,
        color: untimed ? theme.textDim : (isPast ? theme.textDim : theme.text),
        letterSpacing: -0.2,
        textTransform: untimed ? 'uppercase' : 'none',
      }}>{untimed ? 'Anytime' : item.time}</div>
      <Card theme={theme} onClick={onClick} status={c.status}
        style={{ opacity: isPast ? 0.55 : 1 }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          <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>
            <div style={{
              fontSize: 13, color: theme.textMute, marginTop: 2,
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', letterSpacing: -0.1,
            }}>{item.label}</div>
            <div style={{
              fontSize: 12, color: theme.textDim, marginTop: 4, letterSpacing: -0.05,
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            }}>{c.car} · {c.location}</div>
          </div>
        </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.toLowerCase()}
          </div>
          <div style={{ fontSize: 12, color: theme.textDim, marginTop: 3 }}>
            Parked {readyAgo(c)} · {c.location}
          </div>
        </div>
      </div>
    </Card>
  );
}

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 }) {
  return (
    <Card theme={theme} onClick={onClick} status={c.status}>
      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <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>
        </div>
      </div>
    </Card>
  );
}

window.TodayScreen = TodayScreen;
