// Leads + Bookings + shared Contact/Ready-email pieces.
// Relies on globals from components.jsx.
const { useState: useState2 } = React;

const KindIcon = ({ kind, muted }) => {
  const c = muted ? '#3a3a3c' : '#86868b';
  return kind === 'phone'
    ? <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.1-8.7A2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1.9.3 1.8.6 2.7a2 2 0 0 1-.5 2.1L8 9.8a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.5c.9.3 1.8.5 2.7.6a2 2 0 0 1 1.7 2z"/></svg>
    : <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></svg>;
};

const ContactRow = ({ kind, value, onClick }) => {
  if (!value) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', color: '#3a3a3c', fontSize: 13 }}>
        <KindIcon kind={kind} muted />
        <span style={{ fontStyle: 'italic' }}>No {kind === 'phone' ? 'number' : 'email'} on file</span>
      </div>
    );
  }
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
      margin: '2px -12px', width: 'calc(100% + 24px)',
      background: 'transparent', border: 0, borderRadius: 10,
      cursor: 'pointer', textAlign: 'left', color: 'inherit',
    }}>
      <KindIcon kind={kind} />
      <span style={{
        flex: 1, minWidth: 0,
        fontFamily: kind === 'phone' ? 'JetBrains Mono, monospace' : 'Inter',
        fontSize: 13, color: '#fff',
        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        letterSpacing: kind === 'phone' ? '0.02em' : '-0.011em',
      }}>{value}</span>
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '6px 12px', borderRadius: 999,
        background: 'rgba(255,107,26,0.12)', color: '#FF6B1A',
        fontSize: 11, fontWeight: 600, letterSpacing: '0.02em',
      }}>
        {kind === 'phone'
          ? <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.1-8.7A2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1.9.3 1.8.6 2.7a2 2 0 0 1-.5 2.1L8 9.8a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.5c.9.3 1.8.5 2.7.6a2 2 0 0 1 1.7 2z"/></svg>
          : <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m3 7 9 6 9-6"/><rect x="3" y="5" width="18" height="14" rx="2"/></svg>}
        {kind === 'phone' ? 'Call' : 'Email'}
      </span>
    </button>
  );
};

// Mark-ready animated button
const MarkReadyButton = ({ onDone }) => {
  const [phase, setPhase] = useState2('idle');
  const tap = () => {
    if (phase !== 'idle') return;
    setPhase('pressing');
    setTimeout(() => setPhase('check'), 220);
    setTimeout(() => { setPhase('done'); onDone?.(); }, 1100);
  };
  const w = phase === 'pressing' ? 140 : phase === 'check' ? 180 : phase === 'done' ? 44 : 130;
  return (
    <button onClick={tap} style={{
      height: 40, width: w, flexShrink: 0,
      background: phase === 'done' ? '#30d158' : '#FF6B1A',
      color: '#000', border: 0, borderRadius: 980,
      font: '600 13px Inter', letterSpacing: '-0.011em', cursor: 'pointer',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
      overflow: 'hidden',
      transition: 'all 360ms cubic-bezier(0.25,0.1,0.25,1)',
    }}>
      {phase === 'idle' && 'Mark ready'}
      {phase === 'pressing' && <svg width="14" height="14" viewBox="0 0 50 50"><circle cx="25" cy="25" r="20" fill="none" stroke="#000" strokeWidth="4" strokeDasharray="30 100" strokeLinecap="round" style={{ transformOrigin: 'center', animation: 'spin 0.8s linear infinite' }}/></svg>}
      {phase === 'check' && <><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#000" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12 L10 18 L20 6"/></svg>Notifying…</>}
      {phase === 'done' && <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#000" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12 L10 18 L20 6"/></svg>}
    </button>
  );
};

const LeadsTab = ({ onConvert }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
    <Eyebrow>{LEADS.length} NEW · 4 UNSEEN</Eyebrow>
    {LEADS.map(l => (
      <article key={l.ref} style={{ padding: 16, background: '#0a0a0a', border: '1px solid #1a1a1a', borderRadius: 14 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <ChannelIcon c={l.channel} />
              <Mono style={{ fontSize: 11, color: '#86868b' }}>{l.ref}</Mono>
              <span style={{ fontSize: 11, color: '#86868b' }}>· {l.received}</span>
            </div>
            <div style={{ marginTop: 6, fontSize: 15, fontWeight: 500 }}>{l.name}</div>
            <div style={{ marginTop: 2, fontSize: 14, color: 'rgba(255,255,255,0.85)' }}>{l.device} — {l.issue}</div>
            <div style={{ marginTop: 8, paddingTop: 6, borderTop: '1px solid #1a1a1a' }}>
              <ContactRow kind="phone" value={l.phone} onClick={() => window.location.href = `tel:${l.phone.replace(/\s/g,'')}`} />
              <ContactRow kind="email" value={l.email} onClick={() => {}} />
            </div>
          </div>
          <div style={{ textAlign: 'right', flexShrink: 0 }}>
            <div style={{ fontSize: 10, color: '#86868b', letterSpacing: '0.1em' }}>FROM</div>
            <Mono style={{ fontSize: 20, fontWeight: 600, letterSpacing: '-0.015em' }}>£{l.starting}</Mono>
          </div>
        </div>
        <div style={{ marginTop: 12, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <button onClick={() => onConvert(l)} style={{ flex: '1 1 140px', minWidth: 120, height: 40, background: '#FF6B1A', color: '#000', border: 0, borderRadius: 10, font: '600 13px Inter', cursor: 'pointer' }}>Book it</button>
          <button style={{ flex: '0 1 auto', height: 40, padding: '0 16px', background: 'transparent', color: '#fff', border: 0, borderRadius: 10, boxShadow: 'inset 0 0 0 1px #2c2c2e', font: '500 13px Inter', cursor: 'pointer' }}>Reply</button>
          <button style={{ flex: '0 1 auto', height: 40, padding: '0 14px', background: 'transparent', color: '#86868b', border: 0, borderRadius: 10, boxShadow: 'inset 0 0 0 1px #1a1a1a', font: '500 13px Inter', cursor: 'pointer' }}>Mark lost</button>
        </div>
      </article>
    ))}
  </div>
);

// Ready-email sheet
const ReadyEmailSheet = ({ booking, onClose, onSent }) => {
  const [subject, setSubject] = useState2('');
  const [body, setBody] = useState2('');
  const [sent, setSent] = useState2(false);
  React.useEffect(() => {
    if (!booking) return;
    setSubject(`Your ${booking.device} is ready to collect — ${booking.ref}`);
    setBody(
      `Hi ${booking.name.split(' ')[0]},\n\n` +
      `Good news — your ${booking.device} (${booking.service}) is fixed and ready.\n\n` +
      `Ref:    ${booking.ref}\n` +
      `Total:  £${booking.price}\n` +
      `Shop:   The Fone Shop, Longton — open til 6pm, 10–4 Sat.\n\n` +
      `Bring this email or the ref above. Card, cash, Apple Pay all fine.\n\n` +
      `Cheers,\nMo`
    );
    setSent(false);
  }, [booking]);
  if (!booking) return null;
  const send = () => { setSent(true); setTimeout(() => { onSent?.(); onClose(); }, 900); };
  return (
    <Sheet open={!!booking} onClose={onClose} subtitle="READY EMAIL" title={`To ${booking.name}`}
      actions={[
        <PrimaryButton key="send" onClick={send} disabled={sent} tone={sent ? 'success' : 'ember'}>
          {sent ? <><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#000" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12 L10 18 L20 6"/></svg>Sent</>
                : <><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#000" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4z"/></svg>Send email</>}
        </PrimaryButton>,
        <GhostButton key="cancel" onClick={onClose}>Cancel</GhostButton>,
      ]}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        <Field label="TO"><div style={{ fontSize: 14 }}>{booking.email}</div></Field>
        <Field label="SUBJECT"><input value={subject} onChange={e => setSubject(e.target.value)} style={fieldInput} /></Field>
        <Field label="MESSAGE"><textarea value={body} onChange={e => setBody(e.target.value)} rows={9} style={{ ...fieldInput, resize: 'none', lineHeight: 1.5 }} /></Field>
      </div>
    </Sheet>
  );
};

const BookingsTab = () => {
  const [filter, setFilter] = useState2('today');
  const [done, setDone] = useState2(new Set());
  const [expanded, setExpanded] = useState2(new Set(['FS-20260418-A7K3']));
  const [composeFor, setComposeFor] = useState2(null);
  const toggleExpand = (ref) => setExpanded(s => {
    const next = new Set(s); next.has(ref) ? next.delete(ref) : next.add(ref); return next;
  });
  return (
    <div style={{ position: 'relative' }}>
      <div style={{ display: 'flex', gap: 6, marginBottom: 16 }}>
        {[['today', 'Today', 3], ['tomorrow', 'Tomorrow', 2], ['later', 'Later', 7]].map(([k, lbl, n]) => (
          <button key={k} onClick={() => setFilter(k)} style={{
            height: 36, padding: '0 14px',
            background: filter === k ? '#FF6B1A' : 'transparent',
            color: filter === k ? '#000' : '#86868b',
            border: 0, borderRadius: 980,
            boxShadow: filter === k ? 'none' : 'inset 0 0 0 1px #2c2c2e',
            font: '500 13px Inter', cursor: 'pointer',
          }}>{lbl} · {n}</button>
        ))}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {BOOKINGS.map(b => {
          const open = expanded.has(b.ref);
          const isDone = done.has(b.ref);
          return (
            <article key={b.ref} style={{ padding: 16, background: '#0a0a0a', border: '1px solid #1a1a1a', borderRadius: 14 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
                <button onClick={() => toggleExpand(b.ref)} style={{ flex: 1, minWidth: 0, background: 'transparent', border: 0, padding: 0, textAlign: 'left', cursor: 'pointer', color: 'inherit' }}>
                  <Mono style={{ fontSize: 11, color: '#86868b' }}>{b.ref}</Mono>
                  <div style={{ marginTop: 6, fontSize: 15, fontWeight: 500 }}>{b.name}</div>
                  <div style={{ marginTop: 2, fontSize: 14, color: 'rgba(255,255,255,0.85)' }}>{b.device} — {b.service}</div>
                  <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
                    <StatusPill s={isDone ? 'ready' : b.status} />
                    <span style={{ fontSize: 12, color: '#86868b' }}>Due {b.due}</span>
                    <Mono style={{ fontSize: 13, color: '#fff' }}>£{b.price}</Mono>
                  </div>
                </button>
                {b.status === 'in_progress' && !isDone && (
                  <MarkReadyButton onDone={() => {
                    setDone(prev => new Set(prev).add(b.ref));
                    if (b.email) setTimeout(() => setComposeFor(b), 500);
                  }} />
                )}
              </div>
              <div style={{
                overflow: 'hidden',
                maxHeight: open ? 220 : 0, opacity: open ? 1 : 0,
                transition: 'max-height 320ms cubic-bezier(0.25,0.1,0.25,1), opacity 220ms',
              }}>
                <div style={{ marginTop: 12, paddingTop: 8, borderTop: '1px solid #1a1a1a' }}>
                  <ContactRow kind="phone" value={b.phone} onClick={() => window.location.href = `tel:${b.phone.replace(/\s/g,'')}`} />
                  <ContactRow kind="email" value={b.email} onClick={() => setComposeFor(b)} />
                </div>
              </div>
            </article>
          );
        })}
      </div>
      <ReadyEmailSheet booking={composeFor} onClose={() => setComposeFor(null)} />
    </div>
  );
};

Object.assign(window, { LeadsTab, BookingsTab });
