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

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

  // Status is the bucket: red = hot lead, blue = nurturing (shows nurturing controls
  // + lands them in the Nurturing tab), grey = other. Switching to anything but blue
  // turns nurturing off so they leave the Nurturing tab.
  const setStatus = (status) => onUpdate(status === 'blue'
    ? { status, nurturing: true }
    : { status, nurturing: false });
  const setStage  = (stage)  => onUpdate({stage });
  const setJourney = (journey) => onUpdate({journey });
  const setFinance = (finance) => onUpdate({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) => {
    let next;
    if (opt === 'Unknown') {
      next = ['Unknown'];                                   // Unknown clears the rest
    } else if (financeArr.includes(opt)) {
      next = financeArr.filter(x => x !== opt);             // toggle off
    } else {
      next = [...financeArr.filter(x => x !== 'Unknown'), opt]; // adding a real value drops Unknown
    }
    if (next.length === 0) next = ['Unknown'];
    onUpdate({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: 44, height: 44,
            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 — dials via tel: when a number is stored */}
          {c.phone ? (
            <a href={'tel:' + String(c.phone).replace(/\s+/g, '')} style={{
              width: 48, height: 48, borderRadius: 99,
              background: theme.blue, color: '#fff', textDecoration: 'none',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '0 4px 12px rgba(0,0,0,0.18)', flexShrink: 0,
            }}>
              <Icon name="phone" size={20} stroke={2}/>
            </a>
          ) : null}
        </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 }}>
          <EditRow theme={theme} icon="car" label="Car" value={c.car || ''}
            placeholder="e.g. Compact SUV · slate" onCommit={v => onUpdate({ car: v.trim() })} />
          <Divider theme={theme}/>
          <EditRow theme={theme} icon="pin" label="Location" value={c.location || ''}
            placeholder="Suburb" onCommit={v => onUpdate({ location: v.trim() })} />
          <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>

        {/* Trade-in — current vehicle they'd hand over */}
        {(() => {
          const t = c.tradeIn || {};
          const patchTrade = (k, v) => onUpdate((cur) => ({ tradeIn: { ...(cur.tradeIn || {}), [k]: v } }));
          return (
            <Card theme={theme} style={{ marginBottom: 10 }}>
              <div style={{
                fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase',
                color: theme.textMute, marginBottom: 2, paddingLeft: 4,
              }}>Trade-in</div>
              <EditRow theme={theme} icon="car" label="Vehicle (make / model)" value={t.vehicle || ''}
                placeholder="e.g. Toyota Hilux SR5" onCommit={v => patchTrade('vehicle', v.trim())} />
              <Divider theme={theme}/>
              <EditRow theme={theme} icon="tag" label="Year" type="tel" value={t.year || ''}
                placeholder="2019" onCommit={v => patchTrade('year', v.trim())} />
              <Divider theme={theme}/>
              <EditRow theme={theme} icon="tag" label="Rego" value={t.rego || ''}
                placeholder="ABC123" onCommit={v => patchTrade('rego', v.trim())} />
              <Divider theme={theme}/>
              <EditRow theme={theme} icon="pin" label="Odometer (kms)" type="tel" value={t.kms || ''}
                placeholder="85,000" onCommit={v => patchTrade('kms', v.trim())} />
            </Card>
          );
        })()}

        {/* Contact + schedule */}
        <Card theme={theme} style={{ marginBottom: 10 }}>
          <EditRow theme={theme} icon="phone" label="Phone (optional)" type="tel"
            value={c.phone || ''} placeholder="04xx xxx xxx"
            onCommit={v => onUpdate({phone: v.trim() })} />
          <Divider theme={theme}/>
          <EditRow theme={theme} icon="phone" label="Callback" type="datetime-local"
            value={c.callbackAt || ''} onCommit={v => onUpdate({callbackAt: v || null })}
            onClear={() => onUpdate({ callbackAt: null })} />
          {c.callbackAt && (
            <React.Fragment>
              <Divider theme={theme}/>
              <EditRow theme={theme} icon="tag" label="Callback label" value={c.callbackLabel || ''}
                placeholder="e.g. Follow up on finance" onCommit={v => onUpdate({ callbackLabel: v.trim() })} />
            </React.Fragment>
          )}
          <Divider theme={theme}/>
          <EditRow theme={theme} icon="calendar" label="Appointment" type="datetime-local"
            value={c.appointmentAt || ''} onCommit={v => onUpdate({appointmentAt: v || null })}
            onClear={() => onUpdate({ appointmentAt: null })} />
          {c.appointmentAt && (
            <React.Fragment>
              <Divider theme={theme}/>
              <EditRow theme={theme} icon="tag" label="Appointment label" value={c.appointmentLabel || ''}
                placeholder="e.g. Test drive" onCommit={v => onUpdate({ appointmentLabel: v.trim() })} />
            </React.Fragment>
          )}
        </Card>

        {/* Nurturing controls — shown when status = Nurturing (blue).
            Choose a ready-date OR park them on the cars-wanted list (no date). */}
        {c.nurturing && (() => {
          const mode = c.carsWanted ? 'cars' : 'date';
          return (
            <Card theme={theme} style={{ marginBottom: 10 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 9, background: theme.greenSoft, color: theme.greenInk,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}>
                  <Icon name="sprout" size={16} stroke={2}/>
                </div>
                <div style={{ fontSize: 15, color: theme.text, fontWeight: 500, letterSpacing: -0.2 }}>Nurturing</div>
              </div>

              {/* mode segmented control */}
              <div style={{
                display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6,
                padding: 4, borderRadius: 12, background: theme.chip, marginBottom: mode === 'date' ? 12 : 0,
              }}>
                {[
                  { key: 'date', label: 'Ready date' },
                  { key: 'cars', label: 'Cars wanted' },
                ].map(o => {
                  const active = mode === o.key;
                  return (
                    <button key={o.key} onClick={() => onUpdate(o.key === 'cars'
                      ? { carsWanted: true, readyDate: null }
                      : { carsWanted: false })} style={{
                      border: 'none', borderRadius: 9, padding: '11px 4px', minHeight: 44,
                      background: active ? theme.surface : 'transparent',
                      color: active ? theme.text : theme.textMute,
                      fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer', letterSpacing: -0.1,
                      boxShadow: active ? '0 1px 3px rgba(0,0,0,0.08)' : 'none',
                    }}>{o.label}</button>
                  );
                })}
              </div>

              {mode === 'date' ? (
                <div>
                  <div style={{ fontSize: 12, color: theme.textMute, marginBottom: 4 }}>Ready / come-back date</div>
                  <input type="date" value={c.readyDate || ''}
                    onChange={e => onUpdate({ readyDate: e.target.value || null })}
                    style={{
                      width: '100%', border: `0.5px solid ${theme.borderStrong}`, borderRadius: 10,
                      background: theme.surfaceAlt || theme.chip, padding: '10px 12px', minHeight: 44,
                      fontFamily: 'inherit', fontSize: 15, color: theme.text, outline: 'none', colorScheme: 'dark',
                    }} />
                </div>
              ) : (
                <div style={{
                  marginTop: 12, fontSize: 13, color: theme.textMute, lineHeight: 1.45, letterSpacing: -0.05,
                }}>
                  On the cars-wanted list. They'll sit here until the right car comes in, then you reach out.
                </div>
              )}
            </Card>
          );
        })()}

        {/* Notes — append-only history: latest up front, older ones in a dropdown */}
        <NotesSection theme={theme} customer={c} onUpdate={onUpdate} />

        {/* 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((cur) => {
                  const cd = cur.delivery || { transport: false, recon: false, finance: false, settlement: false };
                  return { delivery: { ...cd, [k]: !cd[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>

        {/* Remove customer (soft delete) — two-tap confirm */}
        {onDelete && (
          <button onClick={() => { if (confirmDel) onDelete(c.id); else setConfirmDel(true); }}
            style={{
              marginTop: 8, width: '100%', border: `0.5px solid ${theme.red}`,
              background: confirmDel ? theme.red : 'transparent',
              color: confirmDel ? '#fff' : theme.red,
              padding: '13px 16px', borderRadius: 14, minHeight: 48,
              fontFamily: 'inherit', fontSize: 15, fontWeight: 600, cursor: 'pointer', letterSpacing: -0.15,
            }}>{confirmDel ? 'Tap again to remove' : 'Remove customer'}</button>
        )}

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

// editable row with an icon — commits on blur (text) or change (date/time).
// When onClear is given and a value is set, shows a clear (×) button to remove it.
function EditRow({ theme, icon, label, value, onCommit, type, placeholder, onClear }) {
  const [v, setV] = React.useState(value || '');
  React.useEffect(() => { setV(value || ''); }, [value]);
  const isDate = type === 'date' || type === 'datetime-local';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 4px' }}>
      <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, minWidth: 0 }}>
        <div style={{ fontSize: 12, color: theme.textMute, letterSpacing: -0.05 }}>{label}</div>
        <input type={type || 'text'} value={v} placeholder={placeholder}
          onChange={e => { setV(e.target.value); if (isDate) onCommit(e.target.value); }}
          onBlur={() => { if (!isDate && v !== (value || '')) onCommit(v); }}
          style={{
            width: '100%', border: 'none', background: 'transparent', fontFamily: 'inherit',
            fontSize: 15, color: theme.text, fontWeight: 500, marginTop: 2, letterSpacing: -0.2,
            outline: 'none', colorScheme: 'dark', minHeight: 24,
          }} />
      </div>
      {onClear && v && (
        <button onClick={() => { setV(''); onClear(); }} title="Remove" style={{
          flexShrink: 0, width: 32, height: 32, borderRadius: 99, cursor: 'pointer',
          border: `0.5px solid ${theme.border}`, background: theme.chip, color: theme.textMute,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="x" size={14} stroke={2.4}/>
        </button>
      )}
    </div>
  );
}

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', minHeight: 44,
                  padding: '11px 14px 11px ' + (multi ? '12px' : '14px'),
                  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, minHeight: 44,
            padding: '12px 16px', 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: '11px 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>
  );
}

// Notes history: each save adds a new note (never overwrites). Latest shows up front;
// older ones live behind a "Previous notes" dropdown. Back-compat: a customer with the
// old single `notes` string is treated as one existing note.
function noteWhen(t) {
  if (!t) return 'earlier';
  try { return new Date(t).toLocaleString('en-AU', { day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit' }); }
  catch { return ''; }
}

function NotesSection({ theme, customer, onUpdate }) {
  const c = customer;
  const [adding, setAdding] = React.useState(false);
  const [draft, setDraft] = React.useState('');
  const [showPrev, setShowPrev] = React.useState(false);
  React.useEffect(() => { setAdding(false); setDraft(''); setShowPrev(false); }, [c.id]);

  const log = (Array.isArray(c.noteLog) && c.noteLog.length)
    ? c.noteLog
    : (c.notes ? [{ t: null, text: c.notes }] : []);
  const current = log[0];
  const previous = log.slice(1);

  const save = () => {
    const text = draft.trim();
    if (!text) { setAdding(false); setDraft(''); return; }
    onUpdate((cur) => {
      const existing = (Array.isArray(cur.noteLog) && cur.noteLog.length)
        ? cur.noteLog
        : (cur.notes ? [{ t: null, text: cur.notes }] : []);
      return { noteLog: [{ t: new Date().toISOString(), text }, ...existing], notes: text };
    });
    setDraft(''); setAdding(false);
  };

  return (
    <Card theme={theme} style={{ marginBottom: 10 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
        <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase', color: theme.textMute }}>Notes</span>
        <button onClick={() => { setAdding(a => !a); setDraft(''); }} style={{
          border: 'none', background: 'transparent', color: theme.blue, fontFamily: 'inherit',
          fontSize: 14, fontWeight: 600, padding: '10px 12px', margin: '-10px -12px', cursor: 'pointer',
        }}>{adding ? 'Cancel' : '+ Add note'}</button>
      </div>

      {adding && (
        <div style={{ marginBottom: current ? 14 : 0 }}>
          <textarea value={draft} autoFocus onChange={e => setDraft(e.target.value)}
            placeholder="New note…"
            style={{
              width: '100%', minHeight: 84, 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',
            }} />
          <button onClick={save} disabled={!draft.trim()} style={{
            marginTop: 10, width: '100%', border: 'none', padding: '12px 16px', borderRadius: 12, minHeight: 46,
            background: draft.trim() ? (theme.accentSolid || theme.blue) : theme.chip,
            color: draft.trim() ? '#fff' : theme.textDim, fontFamily: 'inherit', fontSize: 15, fontWeight: 600,
            cursor: draft.trim() ? 'pointer' : 'default', letterSpacing: -0.15,
          }}>Save note</button>
        </div>
      )}

      {/* current (latest) note */}
      {current ? (
        <div>
          <div style={{ fontSize: 15, color: theme.text, lineHeight: 1.45, letterSpacing: -0.15, whiteSpace: 'pre-wrap' }}>
            {current.text}
          </div>
          <div style={{ fontSize: 11.5, color: theme.textDim, marginTop: 5 }}>{noteWhen(current.t)}</div>
        </div>
      ) : (!adding && (
        <div style={{ fontSize: 15, color: theme.textDim, lineHeight: 1.45 }}>No notes yet. Tap “+ Add note”.</div>
      ))}

      {/* previous notes dropdown */}
      {previous.length > 0 && (
        <div style={{ marginTop: 12, borderTop: `0.5px solid ${theme.border}`, paddingTop: 10 }}>
          <button onClick={() => setShowPrev(s => !s)} style={{
            border: 'none', background: 'transparent', color: theme.textMute, fontFamily: 'inherit',
            fontSize: 13, fontWeight: 600, cursor: 'pointer', padding: '4px 0', display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <Icon name="chevron-down" size={15} stroke={2}
              style={{ transform: showPrev ? 'none' : 'rotate(-90deg)', transition: 'transform 0.15s' }}/>
            Previous notes ({previous.length})
          </button>
          {showPrev && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 8 }}>
              {previous.map((n, i) => (
                <div key={i} style={{ background: theme.surfaceAlt || theme.chip, borderRadius: 10, padding: '10px 12px' }}>
                  <div style={{ fontSize: 14, color: theme.textMute, lineHeight: 1.45, letterSpacing: -0.1, whiteSpace: 'pre-wrap' }}>
                    {n.text}
                  </div>
                  <div style={{ fontSize: 11, color: theme.textDim, marginTop: 5 }}>{noteWhen(n.t)}</div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </Card>
  );
}

function humanDate(iso) {
  if (!iso) return '';
  const today = todayISO();
  if (iso === today) return 'today';
  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 === -1) return 'yesterday';
  if (days > 1 && days < 7) return `in ${days} days`;
  return d.toLocaleDateString('en-AU', { day: 'numeric', month: 'short' });
}

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