/* ============================================================
   Brite Bird Coach — Today screen
   ============================================================ */

const TodayItem = ({ item, lead, onTap, onApprove, onSkip, approved, defaultExpanded }) => {
  const kind = KIND_META[item.kind];
  const draft = lead.draft;
  const [expanded, setExpanded] = React.useState(defaultExpanded);
  const [editing, setEditing] = React.useState(false);
  const [editedBody, setEditedBody] = React.useState(draft.body);
  const textareaRef = React.useRef(null);

  const toggleExpanded = (e) => {
    e.stopPropagation();
    setExpanded(v => !v);
    if (editing) setEditing(false);
  };

  const autoSize = (el) => {
    if (!el) return;
    el.style.height = 'auto';
    el.style.height = el.scrollHeight + 'px';
  };

  const enterEdit = (e) => {
    if (e && e.stopPropagation) e.stopPropagation();
    setEditing(true);
    setTimeout(() => {
      const ta = textareaRef.current;
      if (ta) { autoSize(ta); ta.focus(); ta.setSelectionRange(ta.value.length, ta.value.length); }
    }, 0);
  };

  return (
    <div style={{
      background: 'white',
      borderRadius: 'var(--radius-lg)',
      marginBottom: 10,
      boxShadow: 'var(--shadow-md)',
      overflow: 'hidden',
      position: 'relative',
      opacity: approved === 'skipped' ? 0.45 : 1,
      transition: 'opacity var(--dur-base) var(--ease-out)',
    }}>
      {/* approved overlay tag */}
      {approved === 'approved' && (
        <div style={{
          position: 'absolute', top: 12, right: 12, zIndex: 5,
          background: 'var(--bb-orange)', color: 'white',
          borderRadius: 999, padding: '5px 10px',
          fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
          display: 'inline-flex', alignItems: 'center', gap: 5,
        }}>
          <Icon name="check" size={12} stroke={3} /> Sent
        </div>
      )}

      {/* header — tap to expand/collapse */}
      <div onClick={toggleExpanded} style={{ padding: '12px 18px 8px', cursor: 'pointer' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
          <Pill color={kind.color} fg="white" icon={kind.icon}>{kind.label}</Pill>
          <span style={{ fontSize: 11, color: 'var(--bb-ink-60)', fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', flex: 1 }}>{item.ago}</span>
          <Icon name={expanded ? 'chevron-up' : 'chevron-down'} size={18} color="var(--bb-ink-40)" stroke={2.4} />
        </div>

        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
          <Avatar names={lead.names} size={42} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 19, fontWeight: 700, letterSpacing: '-0.01em', lineHeight: 1.15 }}>
              {lead.primary}
            </div>
            <div style={{ fontSize: 13, color: 'var(--bb-ink-60)', fontWeight: 100, marginTop: 1 }}>
              {lead.city} · {money(lead.quote)}
            </div>
          </div>
          <ScoreRing score={lead.score} size={42} stroke={4} />
        </div>
      </div>

      {/* last communication — only when expanded */}
      {expanded && lead.thread && lead.thread.length > 0 && (() => {
        const last = lead.thread[lead.thread.length - 1];
        const fromThem = last.from === 'them';
        return (
          <div style={{
            margin: '4px 18px 10px', padding: '10px 14px',
            background: 'var(--bb-ink-05)', borderRadius: 14,
            fontSize: 14, fontWeight: 100, color: 'var(--bb-plum)',
            lineHeight: 1.4,
          }}>
            <div style={{
              fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase',
              color: 'var(--bb-ink-60)', marginBottom: 3,
            }}>
              {fromThem ? `${lead.primary.split(' ')[0]} · ${last.t}` : `You · ${last.t}`}
            </div>
            "{last.body}"
          </div>
        );
      })()}

      {/* draft message — tap to edit, blur to exit */}
      {expanded && (
        <div style={{ padding: '0 18px 12px' }}>
          <div
            onClick={(e) => { e.stopPropagation(); if (!editing) enterEdit(e); }}
            style={{
              background: 'var(--bb-cream)',
              borderRadius: 18,
              padding: '13px 15px',
              border: editing ? '1.5px solid var(--bb-pink)' : '1.5px solid transparent',
              transition: 'border-color var(--dur-fast) var(--ease-out)',
              cursor: editing ? 'text' : 'pointer',
              position: 'relative',
            }}
          >
            {/* small pencil hint when not editing — signals tappable */}
            {!editing && (
              <div style={{
                position: 'absolute', top: 10, right: 12,
                color: 'var(--bb-ink-40)', pointerEvents: 'none',
              }}>
                <Icon name="pencil" size={11} stroke={2.4} />
              </div>
            )}
            {editing ? (
              <>
                <textarea
                  ref={textareaRef}
                  value={editedBody}
                  onChange={(e) => { setEditedBody(e.target.value); autoSize(e.target); }}
                  onClick={(e) => e.stopPropagation()}
                  onBlur={() => setEditing(false)}
                  style={{
                    width: '100%',
                    fontSize: 14.5, lineHeight: 1.45, color: 'var(--bb-plum)',
                    fontWeight: 100, fontFamily: 'var(--font-family-base)',
                    background: 'transparent', border: 0, outline: 'none', resize: 'none',
                    padding: 0, margin: 0, display: 'block',
                  }}
                />
                <SmsCounter text={editedBody} />
              </>
            ) : (
              <div style={{ fontSize: 14.5, lineHeight: 1.45, color: 'var(--bb-plum)', fontWeight: 100, paddingRight: 18 }}>
                {editedBody}
              </div>
            )}
            {draft.attaches && draft.attaches.length > 0 && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 10 }}>
                {draft.attaches.map(a => (
                  <span key={a} style={{
                    fontSize: 11, fontWeight: 700, color: 'var(--bb-plum)',
                    background: 'rgba(52,14,48,0.06)', padding: '4px 9px', borderRadius: 999,
                    display: 'inline-flex', alignItems: 'center', gap: 4,
                  }}>
                    <Icon name="paperclip" size={10} stroke={2.5} /> {a}
                  </span>
                ))}
              </div>
            )}
          </div>
        </div>
      )}

      {/* actions — only when expanded. Edit happens by tapping the bubble itself. */}
      {expanded && (
        <>
          <div style={{
            display: 'grid',
            gridTemplateColumns: '1fr auto',
            gap: 8, padding: '0 14px 10px',
          }}>
            <button onClick={() => onApprove(item.id)} style={{
              background: 'var(--bb-pink)', color: 'white',
              border: 0, borderRadius: 999,
              padding: '13px 18px',
              fontFamily: 'var(--font-family-base)', fontSize: 15, fontWeight: 700,
              cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              boxShadow: '0 4px 0 0 var(--bb-plum)',
            }}>
              <Icon name="send" size={16} stroke={2.4} /> Approve &amp; send
            </button>
            <button onClick={() => onSkip(item.id)} style={{
              width: 46, height: 46, borderRadius: 999,
              background: 'var(--bb-ink-10)', color: 'var(--bb-plum)', border: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
            }}>
              <Icon name="x" size={16} stroke={2.4} />
            </button>
          </div>

          {/* View lead link — moved here so the header tap is for expand/collapse */}
          <button onClick={(e) => { e.stopPropagation(); onTap(lead.id); }} style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4,
            margin: '0 14px 12px', padding: '8px',
            background: 'transparent', border: 0,
            fontFamily: 'var(--font-family-base)',
            fontSize: 12, fontWeight: 700, letterSpacing: '0.04em',
            color: 'var(--bb-ink-60)', cursor: 'pointer', width: 'calc(100% - 28px)',
          }}>
            View lead <Icon name="chevron-right" size={12} stroke={2.4} />
          </button>
        </>
      )}
    </div>
  );
};

const PipelineHero = () => {
  const date = new Date(2026, 9, 8); // Oct 8, 2026 — Thursday
  const dayLabel = date.toLocaleDateString('en-US', { weekday: 'short' });
  const dateLabel = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });

  return (
    <div style={{
      margin: '8px 16px 16px',
      padding: '14px 18px',
      borderRadius: 'var(--radius-lg)',
      background: 'var(--bb-plum)',
      color: 'white',
      position: 'relative',
      display: 'flex', alignItems: 'center', gap: 14,
      boxShadow: '0 6px 14px -4px rgba(52,14,48,0.22), inset 0 1px 0 rgba(255,255,255,0.08)',
    }}>
      {/* Ray on the left */}
      <img src="shared-assets/logos/primary-3d/logomark/logomark-core.png" alt=""
        style={{ width: 48, height: 48, flex: 'none' }}
      />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.55)', marginBottom: 4 }}>
          {dayLabel} · {dateLabel}
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontSize: 18, fontWeight: 700, color: 'white', letterSpacing: '-0.01em' }}>
            23 active
          </span>
          <span style={{ fontSize: 16, fontWeight: 700, color: 'var(--bb-yellow)', letterSpacing: '-0.005em' }}>
            · 4 hot
          </span>
        </div>
      </div>
      <Icon name="chevron-right" size={18} color="rgba(255,255,255,0.5)" />
    </div>
  );
};

const TodayScreen = ({ leads, items, onOpenLead, statusMap, onApprove, onSkip }) => {
  const remaining = items.filter(i => !statusMap[i.id] || statusMap[i.id] === 'pending').length;

  // Active items (still pending) come first, then handled
  const sorted = [...items].sort((a, b) => {
    const sa = statusMap[a.id] || 'pending';
    const sb = statusMap[b.id] || 'pending';
    if (sa === 'pending' && sb !== 'pending') return -1;
    if (sa !== 'pending' && sb === 'pending') return 1;
    return 0;
  });

  return (
    <div style={{ paddingBottom: 20 }}>
      <TopAppBar
        sub="Brite Bird Coach"
        title="Today"
        right={
          <div style={{ display: 'flex', gap: 8 }}>
            <IconButton icon="search" />
            <IconButton icon="bell-dot" color="var(--bb-plum)" fg="white" />
          </div>
        }
      />

      <PipelineHero />

      <div style={{ padding: '0 16px' }}>
        {remaining === 0 ? (
          <AllClearState />
        ) : (
          sorted.map((item, i) => {
            const lead = leads.find(l => l.id === item.leadId);
            // First pending card opens expanded; others collapsed by default
            const status = statusMap[item.id] || 'pending';
            const firstPendingIdx = sorted.findIndex(it => (statusMap[it.id] || 'pending') === 'pending');
            const isFirstPending = i === firstPendingIdx && status === 'pending';
            return (
              <TodayItem
                key={item.id}
                item={item}
                lead={lead}
                approved={statusMap[item.id]}
                onTap={onOpenLead}
                onApprove={onApprove}
                onSkip={onSkip}
                defaultExpanded={isFirstPending}
              />
            );
          })
        )}
      </div>
    </div>
  );
};

const AllClearState = () => (
  <div style={{
    background: 'white',
    borderRadius: 'var(--radius-lg)',
    padding: '36px 24px',
    textAlign: 'center',
    marginTop: 6,
    boxShadow: 'var(--shadow-sm)',
  }}>
    <img src="shared-assets/logos/primary-3d/logomark/logomark-core.png" alt=""
      style={{ width: 96, marginBottom: 12 }}
    />
    <div style={{
      fontSize: 22, fontWeight: 700, letterSpacing: '-0.01em', color: 'var(--bb-plum)',
      marginBottom: 6,
    }}>
      All clear.
    </div>
    <div style={{
      fontSize: 14, fontWeight: 100, lineHeight: 1.5, color: 'var(--bb-ink-60)',
      maxWidth: 280, margin: '0 auto',
    }}>
      Inbox zero. Go sell something — Coach will check in if anything heats up.
    </div>
  </div>
);

Object.assign(window, { TodayScreen });
