// screen-customer.jsx — one customer card with all the fields he tracks.

function CustomerScreen({ theme, dark, customer, onBack, onUpdate }) {
  if (!customer) return null;
  const c = customer;
  const [editing, setEditing] = React.useState(null); // 'name' | 'notes' | null
  const [draft, setDraft] = React.useState('');
  React.useEffect(() => { setEditing(null); }, [c.id]);
  const startEdit = (field, val) => { setDraft(val || ''); setEditing(field); };
  const saveEdit = () => {
    if (editing === 'name') onUpdate({ ...c, name: draft.trim() || c.name });
    else if (editing === 'notes') onUpdate({ ...c, notes: draft });
    setEditing(null);
  };

  const setStatus = (status) => onUpdate({ ...c, status });
  const setStage  = (stage)  => onUpdate({ ...c, stage });
  const setJourney = (journey) => onUpdate({ ...c, journey });
  const setFinance = (finance) => onUpdate({ ...c, finance });

  // Finance is multi-select — coerce string ↔ array for backwards-compat
  const financeArr = Array.isArray(c.finance) ? c.finance : (c.finance ? [c.finance] : []);
  const toggleFinance = (opt) => {
    const next = financeArr.includes(opt)
      ? financeArr.filter(x => x !== opt)
      : [...financeArr, opt];
    onUpdate({ ...c, finance: next });
  };

  return (
    <React.Fragment>
      <TopBar theme={theme} onBack={onBack} title="Customer"
        trailing={
          <button onClick={() => startEdit('name', c.name)} style={{
            border: 'none', background: theme.surface, width: 36, height: 36,
            borderRadius: 99, color: theme.text, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            border: `0.5px solid ${theme.border}`,
          }}>
            <Icon name="edit" size={16}/>
          </button>
        }
      />

      <ScrollBody>
        {/* Identity header */}
        <div style={{ display: 'flex', gap: 14, alignItems: 'center', padding: '8px 4px 16px' }}>
          <Avatar name={c.name} theme={theme} size={64}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            {editing === 'name' ? (
              <input value={draft} autoFocus
                onChange={e => setDraft(e.target.value)}
                onBlur={saveEdit}
                onKeyDown={e => { if (e.key === 'Enter') saveEdit(); }}
                style={{
                  width: '100%', fontSize: 22, fontWeight: 700, color: theme.text, letterSpacing: -0.5,
                  background: theme.surface, border: `0.5px solid ${theme.borderStrong}`,
                  borderRadius: 10, padding: '6px 10px', outline: 'none', fontFamily: 'inherit',
                }} />
            ) : (
              <div onClick={() => startEdit('name', c.name)} style={{
                fontSize: 24, fontWeight: 700, color: theme.text, letterSpacing: -0.5, cursor: 'pointer',
              }}>{c.name || 'Unnamed'}</div>
            )}
            <div style={{ fontSize: 13, color: theme.textMute, marginTop: 2, letterSpacing: -0.1 }}>
              {c.source}
            </div>
          </div>
          {/* CALL button — taps name → Contacts app, the brief is explicit */}
          <button style={{
            width: 48, height: 48, borderRadius: 99,
            background: theme.blue, color: '#fff', border: 'none',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 4px 12px rgba(0,0,0,0.18)', cursor: 'pointer',
          }}>
            <Icon name="phone" size={20} stroke={2}/>
          </button>
        </div>

        {/* Status toggle — Alex's pen-code, one-tap */}
        <div style={{ marginBottom: 18 }}>
          <div style={{
            fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase',
            color: theme.textMute, marginBottom: 6, paddingLeft: 4,
          }}>Status</div>
          <StatusToggle status={c.status} onChange={setStatus} theme={theme} />
        </div>

        {/* Pipeline stage horizontal scroller */}
        <div style={{ marginBottom: 18 }}>
          <div style={{
            fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase',
            color: theme.textMute, marginBottom: 6, paddingLeft: 4,
          }}>Pipeline stage</div>
          <StageScroller stage={c.stage} setStage={setStage} theme={theme} />
        </div>

        {/* Car detail */}
        <Card theme={theme} style={{ marginBottom: 10 }}>
          <FieldRow icon="car" label="Car" value={c.car} theme={theme} />
          <Divider theme={theme}/>
          <FieldRow icon="pin" label="Location" value={c.location} theme={theme} />
          <Divider theme={theme}/>
          <FieldRow icon="dollar" label="Finance" theme={theme}
            value={financeArr.length ? financeArr.join(' · ') : 'Unknown'}
            options={FINANCE} multi multiValue={financeArr} onToggle={toggleFinance} />
          <Divider theme={theme}/>
          <FieldRow icon="tag" label="Journey" value={c.journey} theme={theme}
            options={JOURNEY} onChange={setJourney} />
        </Card>

        {/* Nurturing — only if applicable */}
        {c.nurturing && (
          <Card theme={theme} style={{ marginBottom: 10 }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
              <div style={{
                width: 38, height: 38, borderRadius: 11,
                background: theme.greenSoft, color: theme.greenInk,
                display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              }}>
                <Icon name="sprout" size={18} stroke={2}/>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 0.8, textTransform: 'uppercase', color: theme.greenInk }}>
                  Nurturing
                </div>
                <div style={{ fontSize: 14, fontWeight: 600, color: theme.text, marginTop: 2, letterSpacing: -0.15 }}>
                  Resurfaces {humanDate(c.readyDate)}
                </div>
                <div style={{ fontSize: 12, color: theme.textMute, marginTop: 2 }}>
                  Wants {c.car.toLowerCase()}
                </div>
              </div>
            </div>
          </Card>
        )}

        {/* Notes */}
        <Card theme={theme} style={{ marginBottom: 10 }}>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6,
          }}>
            <span style={{
              fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase',
              color: theme.textMute,
            }}>Notes</span>
            <button onClick={() => editing === 'notes' ? saveEdit() : startEdit('notes', c.notes)} style={{
              border: 'none', background: 'transparent', color: theme.blue,
              fontFamily: 'inherit', fontSize: 13, fontWeight: 600, padding: 0, cursor: 'pointer',
            }}>{editing === 'notes' ? 'Save' : 'Edit'}</button>
          </div>
          {editing === 'notes' ? (
            <textarea value={draft} autoFocus
              onChange={e => setDraft(e.target.value)}
              placeholder="Add a note…"
              style={{
                width: '100%', minHeight: 90, resize: 'none', fontFamily: 'inherit',
                fontSize: 15, color: theme.text, lineHeight: 1.45, letterSpacing: -0.15,
                background: theme.surfaceAlt || theme.chip, border: `0.5px solid ${theme.borderStrong}`,
                borderRadius: 10, padding: '10px 12px', outline: 'none',
              }} />
          ) : (
            <div style={{ fontSize: 15, color: c.notes ? theme.text : theme.textDim, lineHeight: 1.45, letterSpacing: -0.15 }}>
              {c.notes || 'No notes yet. Tap Edit to add one.'}
            </div>
          )}
        </Card>

        {/* Delivery sub-steps — only when the deal is at the Delivery stage */}
        {c.stage === 'Delivery' && (() => {
          const dlv = c.delivery || { transport: false, recon: false, finance: false, settlement: false };
          return (
            <Card theme={theme} style={{ marginBottom: 10 }}>
              <div style={{
                fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase',
                color: theme.textMute, marginBottom: 8,
              }}>Delivery progress</div>
              <DeliveryChecks delivery={dlv} theme={theme}
                onToggle={(k) => onUpdate({ ...c, delivery: { ...dlv, [k]: !dlv[k] } })}
              />
            </Card>
          );
        })()}

        {/* History */}
        <Card theme={theme} style={{ marginBottom: 10 }}>
          <div style={{
            fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase',
            color: theme.textMute, marginBottom: 10,
          }}>History</div>
          <HistoryTimeline history={c.history || []} theme={theme} />
        </Card>

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

function FieldRow({ icon, label, value, theme, options, onChange, multi, multiValue, onToggle }) {
  const [open, setOpen] = React.useState(false);
  const editable = !!options;
  return (
    <div>
      <div onClick={() => editable && setOpen(o => !o)} style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '12px 4px', cursor: editable ? 'pointer' : 'default',
      }}>
        <div style={{
          width: 32, height: 32, borderRadius: 9, background: theme.chip,
          color: theme.chipInk, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <Icon name={icon} size={16} stroke={2}/>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12, color: theme.textMute, letterSpacing: -0.05 }}>{label}</div>
          <div style={{ fontSize: 15, color: theme.text, fontWeight: 500, marginTop: 1, letterSpacing: -0.2 }}>
            {value}
          </div>
        </div>
        {editable && <Icon name="chevron-down" size={16} stroke={2} style={{ color: theme.textDim, transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 0.15s' }}/>}
      </div>
      {open && options && (
        <div style={{ padding: '0 4px 12px' }}>
          {multi && (
            <div style={{
              fontSize: 11, color: theme.textDim, padding: '0 4px 6px', letterSpacing: -0.05,
            }}>Tap to add or remove — multiple OK</div>
          )}
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {options.map(o => {
              const active = multi
                ? (multiValue || []).includes(o)
                : o === value;
              return (
                <button key={o} onClick={() => {
                  if (multi) onToggle(o);
                  else { onChange(o); setOpen(false); }
                }} style={{
                  border: 'none',
                  padding: '7px 12px 7px ' + (multi ? '10px' : '12px'),
                  borderRadius: 99,
                  background: active ? theme.text : theme.chip,
                  color: active ? theme.bg : theme.chipInk,
                  fontFamily: 'inherit', fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
                  letterSpacing: -0.05,
                  display: 'inline-flex', alignItems: 'center', gap: 5,
                }}>
                  {multi && (
                    <span style={{
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      width: 14, height: 14, borderRadius: 99,
                      background: active ? theme.bg : 'transparent',
                      color: active ? theme.text : theme.chipInk,
                      border: active ? 'none' : `1.2px solid ${theme.borderStrong}`,
                    }}>
                      <Icon name={active ? 'check' : 'plus'} size={9} stroke={3}/>
                    </span>
                  )}
                  {o}
                </button>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

function Divider({ theme }) {
  return <div style={{ height: 0.5, background: theme.border, marginLeft: 44 }} />;
}

function StageScroller({ stage, setStage, theme }) {
  const idx = STAGES.indexOf(stage);
  return (
    <div style={{
      display: 'flex', gap: 6, overflowX: 'auto', padding: '4px 0 4px 4px',
      scrollbarWidth: 'none',
    }}>
      {STAGES.map((s, i) => {
        const active = s === stage;
        const past = i < idx;
        return (
          <button key={s} onClick={() => setStage(s)} style={{
            border: 'none', flexShrink: 0,
            padding: '8px 14px', borderRadius: 99,
            background: active ? theme.text : past ? theme.chip : 'transparent',
            color: active ? theme.bg : past ? theme.chipInk : theme.textMute,
            fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer',
            border: !active && !past ? `0.5px solid ${theme.border}` : 'none',
            letterSpacing: -0.1,
          }}>{s}</button>
        );
      })}
      <div style={{ width: 4, flexShrink: 0 }} />
    </div>
  );
}

function DeliveryChecks({ delivery, theme, onToggle }) {
  const steps = [
    { k: 'transport', label: 'Transport booked' },
    { k: 'recon',     label: 'Recon complete' },
    { k: 'finance',   label: 'Finance approved' },
    { k: 'settlement',label: 'Settlement scheduled' },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      {steps.map(s => {
        const done = delivery[s.k];
        return (
          <button key={s.k} onClick={() => onToggle(s.k)} style={{
            border: 'none', background: 'transparent', padding: '8px 4px',
            display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
            fontFamily: 'inherit',
          }}>
            <span style={{
              width: 22, height: 22, borderRadius: 99,
              background: done ? theme.green : 'transparent',
              border: done ? 'none' : `1.5px solid ${theme.borderStrong}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#fff',
            }}>
              {done && <Icon name="check" size={14} stroke={3}/>}
            </span>
            <span style={{
              flex: 1, textAlign: 'left',
              fontSize: 14.5, color: done ? theme.textMute : theme.text,
              textDecoration: done ? 'line-through' : 'none',
              letterSpacing: -0.15,
            }}>{s.label}</span>
          </button>
        );
      })}
    </div>
  );
}

function HistoryTimeline({ history, theme }) {
  return (
    <div style={{ position: 'relative', paddingLeft: 18 }}>
      <div style={{
        position: 'absolute', left: 5, top: 6, bottom: 6, width: 1, background: theme.border,
      }} />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {history.map((h, i) => (
          <div key={i} style={{ position: 'relative' }}>
            <div style={{
              position: 'absolute', left: -18, top: 4,
              width: 11, height: 11, borderRadius: 99,
              background: h.status === 'red' ? theme.red : h.status === 'blue' ? theme.blue : theme.textDim,
              border: `2px solid ${theme.surface}`,
              boxShadow: `0 0 0 1px ${theme.border}`,
            }} />
            <div style={{ fontSize: 12, fontWeight: 600, color: theme.textMute, letterSpacing: -0.05 }}>{h.d}</div>
            <div style={{ fontSize: 14, color: theme.text, marginTop: 1, lineHeight: 1.4, letterSpacing: -0.1 }}>
              {h.text}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function humanDate(iso) {
  if (!iso) return '';
  const today = '2026-05-24';
  if (iso === today) return 'today';
  if (iso < today) return 'today (overdue)';
  const d = new Date(iso + 'T00:00:00');
  const days = Math.round((d - new Date(today + 'T00:00:00')) / 86400000);
  if (days === 1) return 'tomorrow';
  if (days < 7) return `in ${days} days`;
  return d.toLocaleDateString('en-AU', { day: 'numeric', month: 'short' });
}

window.CustomerScreen = CustomerScreen;
window.humanDate = humanDate;
