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

function PipelineScreen({ theme, customers, openCustomer, schedule, tomorrowSchedule }) {
  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))
    .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 deliveries = customers.filter(c => c.stage === 'Delivery');

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

      <ScrollBody>
        {/* 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>

        {/* PENDING DELIVERIES */}
        <Section theme={theme} title="Pending deliveries" count={deliveries.length}
          kicker="TRANSPORT · RECON · FINANCE · SETTLE" icon="car" tone="neutral">
          {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} onClick={() => openCustomer(c.id)}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                      <span style={{ fontSize: 16, fontWeight: 600, color: theme.text, letterSpacing: -0.2 }}>
                        {c.name}
                      </span>
                      <span style={{ fontSize: 12, fontWeight: 600, color: theme.textMute }}>
                        {done} / 4
                      </span>
                    </div>
                    <div style={{ fontSize: 12.5, color: theme.textMute, marginTop: 2 }}>
                      {c.car}
                    </div>
                    <div style={{ display: 'flex', gap: 4, marginTop: 10 }}>
                      {[
                        { k: 'transport', label: 'Transport' },
                        { k: 'recon',     label: 'Recon' },
                        { k: 'finance',   label: 'Finance' },
                        { k: 'settlement',label: 'Settle' },
                      ].map(s => (
                        <div key={s.k} style={{
                          flex: 1, padding: '5px 0', borderRadius: 6,
                          background: d[s.k] ? theme.greenSoft : theme.chip,
                          color: d[s.k] ? theme.greenInk : theme.textMute,
                          fontSize: 10.5, fontWeight: 600, textAlign: 'center', letterSpacing: -0.05,
                        }}>{s.label}</div>
                      ))}
                    </div>
                  </Card>
                );
              })}
            </div>
          )}
        </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: 52, textAlign: 'center', fontSize: 15, fontWeight: 700,
          color: theme.text, letterSpacing: -0.3, flexShrink: 0,
        }}>{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>
  );
}

window.PipelineScreen = PipelineScreen;
