// screen-pipeline.jsx — simple stacked view: hot leads, appointments, pending deliveries.

function PipelineScreen({ theme, customers, openCustomer, schedule, tomorrowSchedule, onOpenDeliveries }) {
  const [q, setQ] = React.useState('');
  const ql = q.trim().toLowerCase();
  const match = c => !ql || [c.name, c.car, c.location].some(x => (x || '').toLowerCase().includes(ql));
  const byId = Object.fromEntries(customers.map(c => [c.id, c]));

  const isLost = c => c.stage === 'Lost';
  const isSold = c => c.stage === 'Won' || c.stage === 'Sold';
  const inDelivery = c => c.stage === 'Delivery';
  // every active customer (not lost/sold/in-delivery), hot ones first
  const leads = customers
    .filter(c => !isLost(c) && !isSold(c) && !inDelivery(c) && match(c))
    .sort((a, b) => (b.status === 'red' ? 1 : 0) - (a.status === 'red' ? 1 : 0));
  const todayAppts = schedule.filter(s => s.kind === 'appt');
  const tomorrowAppts = tomorrowSchedule.filter(s => s.kind === 'appt');
  const deliveryCount = customers.filter(c => c.stage === 'Delivery').length;

  return (
    <React.Fragment>
      <TopBar theme={theme} large
        kicker="Your lists"
        title="Pipeline" />

      <ScrollBody>
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search name, car, suburb…"
          style={{
            width: '100%', marginTop: 4, marginBottom: 6, padding: '12px 14px', borderRadius: 12,
            background: theme.surface, color: theme.text, border: `0.5px solid ${theme.border}`,
            fontFamily: 'inherit', fontSize: 15, outline: 'none', minHeight: 44,
          }} />

        {/* Quick link to the dedicated deliveries page */}
        <button onClick={onOpenDeliveries} style={{
          width: '100%', marginTop: 6, border: `0.5px solid ${theme.border}`, background: theme.surface,
          borderRadius: 14, padding: '14px 16px', cursor: 'pointer', fontFamily: 'inherit',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            width: 36, height: 36, borderRadius: 10, background: theme.chip, color: theme.chipInk,
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}><Icon name="car" size={18} stroke={2}/></div>
          <div style={{ flex: 1, textAlign: 'left' }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: theme.text, letterSpacing: -0.2 }}>Pending deliveries</div>
            <div style={{ fontSize: 12.5, color: theme.textMute, letterSpacing: -0.05 }}>
              {deliveryCount ? (deliveryCount + ' in progress') : 'None right now'}
            </div>
          </div>
          <Icon name="chevron" size={18} style={{ color: theme.textDim }}/>
        </button>
        {/* LEADS TO WORK — every active customer (so nothing you add can hide) */}
        <Section theme={theme} title="Leads to work" count={leads.length} kicker="YOUR BOOK" icon="flame" tone="red">
          {leads.length === 0 ? (
            <EmptyRow theme={theme} label="No leads yet — tap + to add one"/>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {leads.map(c => (
                <Card key={c.id} theme={theme} status={c.status} onClick={() => openCustomer(c.id)}>
                  <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                    <Avatar name={c.name || 'Unnamed'} 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 || 'Unnamed'}
                        </span>
                        <Chip theme={theme} tone={c.status === 'red' ? 'red' : 'neutral'}
                          icon={c.status === 'red' ? 'flame' : undefined}>
                          {c.stage || 'New lead'}
                        </Chip>
                      </div>
                      {c.car && <div style={{ fontSize: 13, color: theme.textMute, marginTop: 2, letterSpacing: -0.1,
                        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {c.car}
                      </div>}
                      {(c.nextAction || c.location) && <div style={{ fontSize: 12, color: theme.textDim, marginTop: 3 }}>
                        {c.nextAction || c.location}
                      </div>}
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          )}
        </Section>

        {/* APPOINTMENTS */}
        <Section theme={theme} title="Appointments"
          count={todayAppts.length + tomorrowAppts.length}
          kicker="TODAY & TOMORROW" icon="calendar" tone="blue">
          {todayAppts.length + tomorrowAppts.length === 0 ? (
            <EmptyRow theme={theme} label="Nothing booked"/>
          ) : (
            <React.Fragment>
              {todayAppts.length > 0 && (
                <DayGroup theme={theme} label="Today">
                  {todayAppts.map((s, i) => (
                    <ApptRow key={i} theme={theme} item={s} c={byId[s.customerId]}
                      onClick={() => openCustomer(s.customerId)} />
                  ))}
                </DayGroup>
              )}
              {tomorrowAppts.length > 0 && (
                <DayGroup theme={theme} label="Tomorrow">
                  {tomorrowAppts.map((s, i) => (
                    <ApptRow key={i} theme={theme} item={s} c={byId[s.customerId]}
                      onClick={() => openCustomer(s.customerId)} />
                  ))}
                </DayGroup>
              )}
            </React.Fragment>
          )}
        </Section>

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

// ─── section header w/ icon badge ──────────────────────────────
function Section({ theme, title, count, kicker, icon, tone, children }) {
  const toneMap = {
    red:   { bg: theme.redSoft,   ink: theme.redInk },
    blue:  { bg: theme.blueSoft,  ink: theme.blueInk },
    green: { bg: theme.greenSoft, ink: theme.greenInk },
    neutral: { bg: theme.chip,    ink: theme.chipInk },
  };
  const t = toneMap[tone] || toneMap.neutral;
  return (
    <div style={{ marginTop: 18 }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10, padding: '0 4px 10px',
      }}>
        <div style={{
          width: 26, height: 26, borderRadius: 8, background: t.bg, color: t.ink,
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <Icon name={icon} size={14} stroke={2}/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 10.5, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase',
            color: theme.textMute, lineHeight: 1.2,
          }}>{kicker}</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 1 }}>
            <span style={{
              fontSize: 18, fontWeight: 700, color: theme.text, letterSpacing: -0.3,
            }}>{title}</span>
            <span style={{
              fontSize: 14, fontWeight: 500, color: theme.textDim, letterSpacing: -0.1,
            }}>{count}</span>
          </div>
        </div>
      </div>
      {children}
    </div>
  );
}

// ─── day group sub-header (Today / Tomorrow) ───────────────────
function DayGroup({ theme, label, children }) {
  return (
    <div style={{ marginBottom: 8 }}>
      <div style={{
        fontSize: 11.5, fontWeight: 600, color: theme.textMute,
        padding: '4px 6px 6px', letterSpacing: -0.05,
      }}>{label}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {children}
      </div>
    </div>
  );
}

// ─── single appointment row ────────────────────────────────────
function ApptRow({ theme, item, c, onClick }) {
  return (
    <Card theme={theme} status={c.status} onClick={onClick} density="compact">
      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <div style={{
          width: 58, textAlign: 'center', fontSize: 12.5, fontWeight: 700, lineHeight: 1.15,
          color: theme.text, letterSpacing: -0.2, flexShrink: 0,
        }}>{fmtTime(item.time)}</div>
        <div style={{ width: 0.5, height: 32, background: theme.border }} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 15, fontWeight: 600, color: theme.text, letterSpacing: -0.2 }}>
            {c.name}
          </div>
          <div style={{ fontSize: 12, color: theme.textMute, marginTop: 1,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {item.label}
          </div>
        </div>
        <Icon name="chevron" size={16} style={{ color: theme.textDim }}/>
      </div>
    </Card>
  );
}

function EmptyRow({ theme, label }) {
  return (
    <div style={{
      background: theme.surface, borderRadius: 14,
      border: `0.5px solid ${theme.border}`,
      padding: '18px 16px', textAlign: 'center',
      color: theme.textMute, fontSize: 13.5, letterSpacing: -0.1,
    }}>{label}</div>
  );
}

// ─── dedicated Pending Deliveries page ─────────────────────────
// Stage = Delivery. Each shows the 4 aftersale steps, tappable to tick off
// without opening the customer. Tap the name to open the full card.
function DeliveriesScreen({ theme, customers, onBack, openCustomer, onPatch }) {
  const deliveries = customers.filter(c => c.stage === 'Delivery');
  const steps = [
    { k: 'transport', label: 'Transport' },
    { k: 'recon',     label: 'Recon' },
    { k: 'finance',   label: 'Finance' },
    { k: 'settlement',label: 'Settle' },
  ];
  const toggle = (id, k) => onPatch(id, (cur) => {
    const d = cur.delivery || { transport: false, recon: false, finance: false, settlement: false };
    return { delivery: { ...d, [k]: !d[k] } };
  });
  return (
    <React.Fragment>
      <TopBar theme={theme} onBack={onBack} title="Pending deliveries" />
      <ScrollBody>
        <div style={{ padding: '4px 4px 12px', fontSize: 13, color: theme.textMute, letterSpacing: -0.1 }}>
          Tick each step as it's done. Transport · Recon · Finance · Settlement.
        </div>
        {deliveries.length === 0 ? (
          <EmptyRow theme={theme} label="No pending deliveries"/>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {deliveries.map(c => {
              const d = c.delivery || { transport: false, recon: false, finance: false, settlement: false };
              const done = Object.values(d).filter(Boolean).length;
              return (
                <Card key={c.id} theme={theme} status={c.status}>
                  <div onClick={() => openCustomer(c.id)} style={{
                    display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', cursor: 'pointer',
                  }}>
                    <span style={{ fontSize: 16, fontWeight: 600, color: theme.text, letterSpacing: -0.2 }}>
                      {c.name || 'Unnamed'}
                    </span>
                    <span style={{ fontSize: 12, fontWeight: 600, color: done === 4 ? theme.greenInk : theme.textMute }}>
                      {done} / 4
                    </span>
                  </div>
                  <div onClick={() => openCustomer(c.id)} style={{ fontSize: 12.5, color: theme.textMute, marginTop: 2, cursor: 'pointer' }}>
                    {c.car || '—'}
                  </div>
                  <div style={{ display: 'flex', gap: 6, marginTop: 12 }}>
                    {steps.map(s => (
                      <button key={s.k} onClick={() => toggle(c.id, s.k)} style={{
                        flex: 1, padding: '10px 0', borderRadius: 9, border: 'none', cursor: 'pointer',
                        background: d[s.k] ? theme.green : theme.chip,
                        color: d[s.k] ? '#fff' : theme.textMute,
                        fontFamily: 'inherit', fontSize: 11, fontWeight: 600, letterSpacing: -0.05, minHeight: 40,
                        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
                      }}>
                        <Icon name={d[s.k] ? 'check' : 'plus'} size={13} stroke={2.6}/>
                        {s.label}
                      </button>
                    ))}
                  </div>
                </Card>
              );
            })}
          </div>
        )}
        <div style={{ height: 100 }} />
      </ScrollBody>
    </React.Fragment>
  );
}

window.PipelineScreen = PipelineScreen;
window.DeliveriesScreen = DeliveriesScreen;
