// screen-nurturing.jsx — the most important feature.
// Auto-sorted list. Resurfaces customers on their ready-date.

function NurturingScreen({ theme, customers, openCustomer, setTab, onAdd }) {
  // date-based nurturing customers, and the cars-wanted list (no date — waiting on stock)
  const dated = customers.filter(c => c.nurturing && c.readyDate && !c.carsWanted);
  const carsWanted = customers.filter(c => c.nurturing && c.carsWanted);

  // group by readiness (dates resolved live, null-safe; LOCAL dates)
  const today = todayISO();
  const d = new Date();
  const eom = isoDate(new Date(d.getFullYear(), d.getMonth() + 1, 0));
  const byDate = (a, b) => (a.readyDate || '').localeCompare(b.readyDate || '');
  const byName = (a, b) => (a.name || '').localeCompare(b.name || '');
  const groups = [
    {
      key: 'ready', label: 'Ready now', tone: 'green', kicker: 'RESURFACED',
      items: dated.filter(c => c.readyDate <= today).sort(byDate),
    },
    {
      key: 'soon', label: 'This month', tone: 'blue', kicker: 'COMING UP',
      items: dated.filter(c => c.readyDate > today && c.readyDate <= eom).sort(byDate),
    },
    {
      key: 'cars', label: 'Cars wanted', tone: 'neutral', kicker: 'WAITING ON THE RIGHT CAR',
      items: carsWanted.slice().sort(byName), carsWanted: true,
    },
    {
      key: 'later', label: 'Later', tone: 'neutral', kicker: 'PARKED',
      items: dated.filter(c => c.readyDate > eom).sort(byDate),
    },
  ];
  const total = dated.length + carsWanted.length;

  return (
    <React.Fragment>
      <TopBar theme={theme} large
        kicker="Auto-resurfaces on ready-date"
        title="Nurturing"
        trailing={
          <button onClick={onAdd} style={{
            border: 'none', background: theme.surface, width: 44, height: 44,
            borderRadius: 99, color: theme.text, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            border: `0.5px solid ${theme.border}`,
          }}>
            <Icon name="plus" size={18}/>
          </button>
        }
      />

      <ScrollBody>
        {/* Hero ready-now banner */}
        {groups[0].items.length > 0 && (
          <div style={{
            background: `linear-gradient(135deg, ${theme.greenSoft}, ${theme.surface})`,
            borderRadius: 18, padding: '14px 16px', marginBottom: 14,
            border: `0.5px solid ${theme.border}`,
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{
              width: 42, height: 42, borderRadius: 12,
              background: theme.green, color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            }}>
              <Icon name="sprout" size={22}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 15, fontWeight: 600, color: theme.text, letterSpacing: -0.2 }}>
                {groups[0].items.length} customer{groups[0].items.length > 1 ? 's' : ''} ready now
              </div>
              <div style={{ fontSize: 12.5, color: theme.textMute, marginTop: 2, letterSpacing: -0.05 }}>
                Their wait-date hit — time to reach out.
              </div>
            </div>
          </div>
        )}

        {total === 0 && (
          <div style={{
            background: theme.surface, borderRadius: 14, border: `0.5px solid ${theme.border}`,
            padding: '18px 16px', textAlign: 'center', color: theme.textMute, fontSize: 13.5,
            lineHeight: 1.5, letterSpacing: -0.1, marginTop: 8,
          }}>
            No one parked yet. Set a customer's status to <strong style={{ color: theme.text }}>Nurturing</strong>,
            then give them a ready-date or add them to the cars-wanted list.
          </div>
        )}

        {groups.map(g => g.items.length === 0 ? null : (
          <div key={g.key} style={{ marginTop: 10 }}>
            <SectionHeader theme={theme} title={g.label} count={g.items.length}
              kicker={g.kicker} />
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {g.items.map(c => (
                <NurturingCard key={c.id} c={c} theme={theme} tone={g.tone}
                  carsWanted={g.carsWanted} onClick={() => openCustomer(c.id)} />
              ))}
            </div>
          </div>
        ))}

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

function NurturingCard({ c, theme, tone, carsWanted, onClick }) {
  const isReady = tone === 'green';
  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={carsWanted ? 'neutral' : tone} icon={carsWanted ? 'car' : undefined}>
              {carsWanted ? 'Cars wanted' : (isReady ? 'Ready' : humanDate(c.readyDate))}
            </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 }}>
            {(Array.isArray(c.finance) ? c.finance.join(' · ') : (c.finance || 'Unknown'))} · {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>
      </div>
    </Card>
  );
}

window.NurturingScreen = NurturingScreen;
