// Towbook-specific patterns: status pill, call card, driver row, equipment inspection row, photo capture, signature, bottom action bar.

const { useState: useStateP } = React;

// Status pill — semantic for tow ops. Variant: 'pill' (rounded), 'tag' (square left number tag).
function TBStatusPill({ status = 'waiting', variant = 'pill', size = 'md' }) {
  const dark = typeof document !== 'undefined' && document.documentElement.getAttribute('data-theme') === 'dark';
  const palette = dark ? TBT.statusDark[status] : TBT.status[status];
  const label = TBT.status[status]?.label || status;
  const fs = size === 'sm' ? 11 : 12;
  const padY = size === 'sm' ? 2 : 3;
  const padX = size === 'sm' ? 8 : 10;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      padding: `${padY}px ${padX}px`,
      fontSize: fs, fontWeight: 600, letterSpacing: '0.02em',
      background: palette.bg, color: palette.fg,
      borderRadius: variant === 'pill' ? 999 : 4,
    }}>
      <span style={{ width: 6, height: 6, borderRadius: '50%', background: palette.solid, flexShrink: 0 }}/>
      {label}
    </span>
  );
}

// Call card — the dispatch list row. Borrows from screenshots: green/blue/amber accent strip,
// number tag, status sentence, vehicle, account, time + ETA, address(es), action bar.
function TBCallCard({ call, onEdit, onUpdateStatus, onCallContact, onClick, expanded = true }) {
  const dark = typeof document !== 'undefined' && document.documentElement.getAttribute('data-theme') === 'dark';
  const status = call.status;
  const palette = dark ? TBT.statusDark[status] : TBT.status[status];

  return (
    <div onClick={onClick} style={{
      background: 'var(--tb-surface)',
      borderTop: `3px solid ${palette.solid}`,
      borderBottom: '1px solid var(--tb-divider)',
      cursor: onClick ? 'pointer' : 'default',
    }}>
      {/* header line: number tag + status sentence */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px 6px' }}>
        <span style={{
          fontFamily: 'var(--font-sans)', fontVariantNumeric: 'tabular-nums',
          padding: '3px 8px', borderRadius: 4,
          background: palette.solid, color: 'white',
          fontSize: 13, fontWeight: 700, letterSpacing: '0.02em',
          minWidth: 52, textAlign: 'center',
        }}>{call.number}</span>
        <span style={{ fontSize: 14, fontWeight: 600, color: palette.fg, flex: 1 }}>
          {call.statusSentence}
        </span>
      </div>

      {/* call type */}
      <div style={{ padding: '0 14px 6px', fontSize: 12, color: 'var(--tb-on-surface-muted)' }}>
        {call.type}
      </div>

      {/* vehicle line */}
      <div style={{ padding: '0 14px', fontSize: 16, fontWeight: 600, color: 'var(--tb-on-surface)', letterSpacing: '-0.005em' }}>
        {call.vehicleYear} {call.vehicleMakeModel} <span style={{ color: 'var(--tb-on-surface-muted)', fontWeight: 500 }}>({call.vehicleColor})</span>
      </div>

      {/* account */}
      <div style={{ padding: '4px 14px 0', fontSize: 13, color: 'var(--tb-on-surface)', fontWeight: 500 }}>
        {call.account}
      </div>

      {/* time row */}
      <div style={{ padding: '6px 14px 0', fontSize: 13, color: 'var(--tb-on-surface-muted)', display: 'flex', gap: 6 }}>
        <span style={{ color: 'var(--tb-on-surface)', fontWeight: 600 }}>{call.receivedTime}</span>
        <span>({call.timeAgo})</span>
        {call.eta && (
          <>
            <span style={{ marginLeft: 'auto', color: 'var(--red-11)', fontWeight: 600 }}>ETA {call.eta}</span>
          </>
        )}
      </div>

      {expanded && (
        <>
          {/* addresses */}
          <div style={{ padding: '8px 14px 4px', fontSize: 13, lineHeight: '18px', color: 'var(--tb-on-surface-faint)' }}>
            <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--green-9)', marginTop: 5, flexShrink: 0 }}/>
              <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{call.pickup}</span>
            </div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start', marginTop: 4 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--red-9)', marginTop: 5, flexShrink: 0 }}/>
              <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{call.dropoff}</span>
            </div>
          </div>

          {/* action bar */}
          <div style={{
            display: 'flex', borderTop: '1px solid var(--tb-divider)',
            marginTop: 10,
          }}>
            <CardAction icon={I.Edit} label="Edit Call" onClick={(e) => { e.stopPropagation(); onEdit?.(call); }}/>
            <CardAction icon={I.Refresh} label="Update Status" onClick={(e) => { e.stopPropagation(); onUpdateStatus?.(call); }}/>
            {onCallContact && <CardAction icon={I.Phone} label="Call Contact" onClick={(e) => { e.stopPropagation(); onCallContact?.(call); }}/>}
          </div>
        </>
      )}
    </div>
  );
}

function CardAction({ icon, label, onClick }) {
  const [pressed, setPressed] = useStateP(false);
  return (
    <button onClick={onClick}
      onMouseDown={() => setPressed(true)} onMouseUp={() => setPressed(false)} onMouseLeave={() => setPressed(false)}
      style={{
        flex: 1, height: 44, border: 0,
        background: pressed ? 'var(--blue-a3)' : 'transparent',
        color: 'var(--blue-11)',
        fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        cursor: 'pointer',
        transition: 'background 80ms var(--ease-in)',
      }}>
      {React.createElement(icon, { size: 16 })} {label}
    </button>
  );
}

// Driver row — for assignment / map driver list.
function TBDriverRow({ name, unit, status, onClick, distance }) {
  return (
    <TBListItem
      leading={<div style={{
        width: 36, height: 36, borderRadius: '50%',
        background: 'var(--blue-3)', color: 'var(--blue-11)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 13, fontWeight: 600,
      }}>{(name || '').split(' ').map(s => s[0]).join('').slice(0,2)}</div>}
      headline={name}
      supporting={`Unit ${unit}${distance ? ' · ' + distance : ''}`}
      trailing={<TBStatusPill status={status || 'waiting'} size="sm"/>}
      onClick={onClick}
    />
  );
}

// Equipment inspection row — checklist with Pass / Fail / N/A + camera.
function TBInspectionRow({ label, value, onChange, photoCount = 0, onPhoto }) {
  const opts = [
    { key: 'pass', label: 'Pass', activeBg: 'var(--green-3)', activeFg: 'var(--green-11)' },
    { key: 'fail', label: 'Fail', activeBg: 'var(--red-3)',   activeFg: 'var(--red-11)' },
    { key: 'na',   label: 'N/A',  activeBg: 'var(--slate-3)', activeFg: 'var(--slate-12)' },
  ];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '12px 14px', borderBottom: '1px solid var(--tb-divider)',
    }}>
      <div style={{ flex: 1, fontSize: 14, fontWeight: 500, color: 'var(--tb-on-surface)' }}>{label}</div>
      <div style={{ display: 'inline-flex', borderRadius: 8, overflow: 'hidden', border: '1px solid var(--tb-border-strong)' }}>
        {opts.map((o, i) => {
          const active = value === o.key;
          return (
            <button key={o.key}
              onClick={() => onChange?.(active ? null : o.key)}
              style={{
                height: 32, padding: '0 10px',
                border: 0,
                borderLeft: i > 0 ? '1px solid var(--tb-border)' : 'none',
                background: active ? o.activeBg : 'transparent',
                color: active ? o.activeFg : 'var(--tb-on-surface-muted)',
                fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 600,
                cursor: 'pointer',
              }}>{o.label}</button>
          );
        })}
      </div>
      <button onClick={onPhoto} style={{
        position: 'relative',
        width: 36, height: 36,
        border: '1px solid var(--tb-border-strong)',
        borderRadius: 8, background: 'transparent',
        color: 'var(--tb-on-surface-muted)',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        cursor: 'pointer',
      }}>
        <I.Camera size={18}/>
        {photoCount > 0 && (
          <span style={{
            position: 'absolute', top: -4, right: -4,
            background: 'var(--red-9)', color: 'white',
            fontSize: 10, fontWeight: 700,
            minWidth: 16, height: 16, padding: '0 4px',
            borderRadius: 99,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>{photoCount}</span>
        )}
      </button>
    </div>
  );
}

// Photo capture tile (used in call detail / inspection)
function TBPhotoTile({ src, label, onClick, count }) {
  return (
    <button onClick={onClick} style={{
      width: 88, height: 88, borderRadius: 12,
      background: src ? `center/cover no-repeat url(${src}), var(--slate-3)` : 'var(--slate-3)',
      border: '1px dashed var(--tb-border-strong)',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      flexDirection: 'column', gap: 4,
      color: 'var(--tb-on-surface-muted)',
      cursor: 'pointer', flexShrink: 0,
      position: 'relative',
    }}>
      {!src && <I.Camera size={22}/>}
      {!src && label && <span style={{ fontSize: 11, fontWeight: 500 }}>{label}</span>}
      {count !== undefined && (
        <span style={{
          position: 'absolute', top: 6, right: 6,
          background: 'rgba(0,0,0,0.65)', color: 'white',
          fontSize: 10, fontWeight: 700, padding: '2px 6px', borderRadius: 999,
        }}>{count}</span>
      )}
    </button>
  );
}

// Bottom action bar (used in call detail — Change Status / Add Photo / Show Map / More)
function TBBottomActionBar({ items }) {
  return (
    <div style={{
      display: 'flex',
      background: 'var(--tb-surface)',
      borderTop: '1px solid var(--tb-divider)',
      padding: '4px 0',
      flexShrink: 0,
    }}>
      {items.map((it, i) => (
        <button key={i} onClick={it.onClick} style={{
          flex: 1, padding: '8px 4px',
          border: 0, background: 'transparent',
          display: 'inline-flex', flexDirection: 'column',
          alignItems: 'center', gap: 4,
          color: 'var(--tb-on-surface-muted)',
          cursor: 'pointer',
          fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 500,
        }}>
          {React.createElement(it.icon, { size: 22 })}
          <span>{it.label}</span>
        </button>
      ))}
    </div>
  );
}

// Section header — in detail screens
function TBSectionHeader({ children, action }) {
  return (
    <div style={{
      padding: '14px 16px 6px',
      fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
      color: 'var(--tb-on-surface-faint)',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    }}>
      <span>{children}</span>
      {action}
    </div>
  );
}

// Detail row — label / value pair used in call detail
function TBDetailRow({ icon, label, value, action }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '10px 16px', minHeight: 44,
      borderBottom: '1px solid var(--tb-divider)',
    }}>
      {icon && <div style={{ color: 'var(--tb-on-surface-faint)', display: 'flex' }}>{React.createElement(icon, { size: 18 })}</div>}
      <div style={{ flex: 1, minWidth: 0 }}>
        {label && <div style={{ fontSize: 11, color: 'var(--tb-on-surface-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>{label}</div>}
        <div style={{ fontSize: 14, color: 'var(--tb-on-surface)', fontWeight: 500 }}>{value}</div>
      </div>
      {action}
    </div>
  );
}

// Pull-to-refresh indicator (visual only; logic shown via tweak/animation)
function TBPullToRefresh({ pulling = false, refreshing = false }) {
  return (
    <div style={{
      height: refreshing ? 56 : (pulling ? 40 : 0),
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      transition: 'height 200ms var(--ease-in)', overflow: 'hidden',
      background: 'var(--tb-surface-1)',
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: '50%',
        background: 'var(--tb-surface)',
        boxShadow: 'var(--tb-elev-1)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: 'var(--tb-primary)',
      }}>
        <TBSpinner size={20}/>
      </div>
    </div>
  );
}

Object.assign(window, {
  TBStatusPill, TBCallCard, TBDriverRow, TBInspectionRow,
  TBPhotoTile, TBBottomActionBar, TBSectionHeader, TBDetailRow,
  TBPullToRefresh,
});
