// ============================================================
// ShieldTech Secret Weapon — Operations screens
// Assistant Chat · Pipeline · Follow-ups · Approvals
// ============================================================

// ─────────────────────────────────────────────────────────────
// ASSISTANT CHAT
// ─────────────────────────────────────────────────────────────
function ScreenAssistant({ goto }) {
  const [msgs, setMsgs] = React.useState(ASSISTANT_THREAD);
  const [input, setInput] = React.useState('');
  const [thinking, setThinking] = React.useState(false);

  const send = async () => {
    if (!input.trim()) return;
    const message = input;
    setMsgs(m => [...m, { who: 'me', text: message }]);
    setInput('');
    setThinking(true);
    try {
      const data = await window.ShieldTechApi?.assistantChat?.(message, { route: 'assistant' });
      setMsgs(m => [...m, { who: 'ai', text: data?.message || 'I saved the note, but no assistant text came back.' }]);
    } catch (error) {
      window.dispatchEvent(new CustomEvent('stw:api-error', { detail: { message: error.message, code: error.code || 'ASSISTANT_FAILED' } }));
      setMsgs(m => [...m, { who: 'ai', text: `Assistant setup needs attention: ${error.message}` }]);
    } finally {
      setThinking(false);
    }
  };

  return (
    <div className="slide-up" style={{ padding: '0 0 180px', color: C.fg1, height: '100%', display: 'flex', flexDirection: 'column' }}>
      <MobileHeader subtitle="ASSISTANT" title="What’s on your mind?"
        leading={
          <div className="glow-purple" style={{
            width: 40, height: 40, borderRadius: 12,
            background: 'rgba(168,85,247,0.14)', border: '1px solid rgba(168,85,247,0.40)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="sparkles" size={20} color={C.assistantSoft}/>
          </div>
        }
        trailing={
          <IconButton icon="history" size={36} color={C.fgMuted} onClick={() => window.ShieldTechApi?.hydrateGlobals?.()}/>
        }
      />

      {/* Context card (if invoked from a task) */}
      <div style={{ padding: '4px 16px 8px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '8px 12px', background: 'rgba(0,163,255,0.06)',
          border: '1px solid rgba(0,163,255,0.18)', borderRadius: 14,
        }}>
          <Icon name="target" size={14} color={C.blueElectric}/>
          <span style={{ font: '500 12px/16px Inter, system-ui, sans-serif', color: C.fg2, flex: 1 }}>
            Context: <span style={{ color: C.blueElectric, fontWeight: 600 }}>Penn Valley SD</span> · follow-up call
          </span>
          <button type="button" style={{ background: 'transparent', border: 0, color: C.fgMuted, cursor: 'pointer', padding: 4 }}>
            <Icon name="x" size={14}/>
          </button>
        </div>
      </div>

      {/* Messages */}
      <div style={{ flex: 1, padding: '4px 16px 0', display: 'flex', flexDirection: 'column', gap: 10, overflowY: 'auto' }}>
        {msgs.map((m, i) => (
          <ChatBubble key={i} who={m.who} text={m.text}/>
        ))}
        {thinking && (
          <ChatBubble who="ai" text={
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              <span className="ai-shimmer" style={{ font: 'inherit' }}>Thinking</span>
              <TypingDots/>
            </span>
          }/>
        )}
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 4 }}>
          {['Yes, schedule it', 'Show pipeline', 'What’s next?', 'Draft an email'].map(s => (
            <button key={s} onClick={() => { setInput(s); }} type="button" style={{
              padding: '8px 14px', borderRadius: 999, background: C.cardElev, color: C.fg2,
              border: `1px solid ${C.border}`, font: '500 13px/1 Inter, system-ui, sans-serif', cursor: 'pointer',
            }}>{s}</button>
          ))}
        </div>
      </div>

      {/* Composer */}
      <div style={{ position: 'absolute', left: 16, right: 16, bottom: 92, padding: '0 0 8px' }}>
        <div style={{
          background: 'rgba(11,17,24,0.86)', border: `1px solid ${C.border}`, borderRadius: 20,
          padding: 8, display: 'flex', alignItems: 'center', gap: 8,
          backdropFilter: 'blur(18px)', WebkitBackdropFilter: 'blur(18px)',
        }}>
          <input value={input} onChange={e => setInput(e.target.value)} placeholder="Ask anything…"
            onKeyDown={e => e.key === 'Enter' && send()}
            style={{ flex: 1, background: 'transparent', border: 0, outline: 'none', color: C.fg1, font: '400 15px/1 Inter, system-ui, sans-serif', padding: '10px 8px' }}/>
          <button type="button" style={{ width: 40, height: 40, borderRadius: 12, background: 'rgba(168,85,247,0.14)', border: '1px solid rgba(168,85,247,0.36)', color: C.assistantSoft, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
            <Icon name="mic" size={18} color={C.assistantSoft}/>
          </button>
          <button onClick={send} type="button" style={{ width: 40, height: 40, borderRadius: 12, background: 'linear-gradient(135deg,#00A3FF,#29C7FF)', border: 0, color: '#03182A', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', boxShadow: '0 0 16px rgba(0,163,255,0.28)' }}>
            <Icon name="send" size={16} color="#03182A" strokeWidth={2.25}/>
          </button>
        </div>
      </div>
    </div>
  );
}

function ChatBubble({ who, text }) {
  const me = who === 'me';
  return (
    <div className="fade-in" style={{ display: 'flex', justifyContent: me ? 'flex-end' : 'flex-start' }}>
      <div style={{
        maxWidth: '82%', padding: '12px 14px',
        borderRadius: me ? '18px 18px 4px 18px' : '18px 18px 18px 4px',
        background: me ? 'linear-gradient(135deg,#0369A1,#00A3FF)' : C.card,
        color: me ? '#F0F9FF' : C.fg1,
        border: me ? 'none' : `1px solid ${C.border}`,
        font: '400 15px/22px Inter, system-ui, sans-serif',
        boxShadow: me ? '0 0 18px rgba(0,163,255,0.22)' : 'none',
      }}>{text}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// PIPELINE
// ─────────────────────────────────────────────────────────────
function ScreenPipeline({ goto }) {
  const tabs = ['All', 'Hot', 'Warm', 'Nurture', 'Dead'];
  const [tab, setTab] = React.useState('All');
  const [query, setQuery] = React.useState('');

  const filtered = PIPELINE.filter(l => {
    if (tab !== 'All' && l.lead.toLowerCase() !== tab.toLowerCase()) return false;
    if (query && !l.name.toLowerCase().includes(query.toLowerCase())) return false;
    return true;
  });

  const counts = {
    All: PIPELINE.length,
    Hot: PIPELINE.filter(l => l.lead === 'hot').length,
    Warm: PIPELINE.filter(l => l.lead === 'warm').length,
    Nurture: PIPELINE.filter(l => l.lead === 'nurture').length,
    Dead: PIPELINE.filter(l => l.lead === 'dead').length,
  };

  return (
    <div className="slide-up" style={{ padding: '0 0 140px' }}>
      <MobileHeader subtitle="PIPELINE" title={`${PIPELINE.length} leads · ${counts.Hot} hot`}
        trailing={null}/>

      {/* Search */}
      <div style={{ padding: '4px 20px 8px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px', background: C.card, border: `1px solid ${C.border}`, borderRadius: 14 }}>
          <Icon name="search" size={16} color={C.fgMuted}/>
          <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search company or contact"
            style={{ flex: 1, background: 'transparent', border: 0, outline: 'none', color: C.fg1, font: '400 14px/1 Inter, system-ui, sans-serif' }}/>
        </div>
      </div>

      {/* Tabs */}
      <div className="no-scrollbar" style={{ padding: '0 20px 8px', display: 'flex', gap: 6, overflowX: 'auto' }}>
        {tabs.map(s => {
          const on = tab === s;
          return (
            <button key={s} onClick={() => setTab(s)} type="button" style={{
              padding: '8px 14px', borderRadius: 999,
              background: on ? C.cardElev : 'transparent',
              color: on ? C.fg1 : C.fgMuted,
              border: `1px solid ${on ? C.borderStrong : C.border}`,
              font: '600 13px/1 Inter, system-ui, sans-serif', cursor: 'pointer', flex: 'none',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              {s}
              <span style={{ font: '500 11px/1 Inter, system-ui, sans-serif', color: C.fgMuted, opacity: 0.7 }}>{counts[s]}</span>
            </button>
          );
        })}
      </div>

      {/* Lead list */}
      <div style={{ padding: '4px 20px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {filtered.length === 0 ? (
          <EmptyState icon="branch" title="No leads here" body="Adjust your filter or add a new prospect from the top-right."/>
        ) : filtered.map(l => (
          <PipelineLeadCard key={l.id} lead={l}/>
        ))}
      </div>
    </div>
  );
}

function PipelineLeadCard({ lead: l }) {
  return (
    <Card hover style={{ padding: 14 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <Avatar initials={l.init} size={42}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ font: '700 15px/1.2 Inter, system-ui, sans-serif', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', flex: 1 }}>{l.name}</div>
            <StatusPill kind={l.lead} size="sm">{cap(l.lead)}</StatusPill>
          </div>
          <div style={{ font: '500 11px/16px Inter, system-ui, sans-serif', color: C.fgMuted, letterSpacing: '0.04em', textTransform: 'uppercase', marginTop: 2 }}>
            {l.type} · {l.territory}
          </div>
        </div>
      </div>
      <div style={{ marginTop: 10, padding: '10px 12px', background: C.cardElev, borderRadius: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <Caption>Next action</Caption>
          {l.broken ? (
            <div style={{ font: '600 13px/18px Inter, system-ui, sans-serif', color: '#FCA5A5', marginTop: 2, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <Icon name="alertTriangle" size={14} color="#FCA5A5"/> Missing next action
            </div>
          ) : (
            <div style={{ font: '600 13px/18px Inter, system-ui, sans-serif', color: C.fg1, marginTop: 2 }}>
              {l.next}<span style={{ color: C.fgMuted, fontWeight: 500 }}> · {l.nextDate}</span>
            </div>
          )}
        </div>
        <div style={{ textAlign: 'right', flex: 'none' }}>
          <Caption>Score</Caption>
          <div className="tabular" style={{ font: '700 18px/1 Rajdhani, "Inter", system-ui, sans-serif', color: C.fg1, marginTop: 2 }}>{l.score}</div>
        </div>
      </div>
      <div style={{ marginTop: 8, font: '400 12px/16px Inter, system-ui, sans-serif', color: C.fgMuted, display: 'flex', alignItems: 'center', gap: 6 }}>
        <Icon name="history" size={12} color={C.fgMuted}/> {l.last}
      </div>
    </Card>
  );
}

// ─────────────────────────────────────────────────────────────
// FOLLOW-UP QUEUE
// ─────────────────────────────────────────────────────────────
function ScreenFollowups({ goto }) {
  const groups = [
    { label: 'Overdue', items: FOLLOWUPS.overdue, tint: '#7F1D1D' },
    { label: 'Today', items: FOLLOWUPS.today, tint: C.blue },
    { label: 'Tomorrow', items: FOLLOWUPS.tomorrow, tint: '#92400E' },
    { label: 'Later', items: FOLLOWUPS.later, tint: C.borderStrong },
  ];
  return (
    <div className="slide-up" style={{ padding: '0 0 140px' }}>
      <MobileHeader subtitle="FOLLOW-UPS" title="The queue"
        trailing={null}/>

      <div style={{ padding: '4px 20px 0', font: '400 14px/20px Inter, system-ui, sans-serif', color: C.fg2 }}>
        {FOLLOWUPS.overdue.length} overdue · {FOLLOWUPS.today.length} today · {FOLLOWUPS.tomorrow.length} tomorrow
      </div>

      {groups.map(g => (
        <div key={g.label} style={{ padding: '14px 20px 0' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 0 10px' }}>
            <span style={{ width: 4, height: 14, background: g.tint, borderRadius: 2 }}/>
            <Caption>{g.label}</Caption>
            <span style={{ font: '500 11px/1 Inter, system-ui, sans-serif', color: C.fgMuted, opacity: 0.7 }}>· {g.items.length}</span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {g.items.map(f => (
              <FollowUpCard key={f.id} f={f}/>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function FollowUpCard({ f }) {
  const kindIcon = { Call: 'phone', Email: 'mail', Bid: 'gavel', Vendor: 'inbox', Admin: 'fileText' }[f.kind] || 'check';
  const [busy, setBusy] = React.useState('');
  const act = async (name, fn) => {
    setBusy(name);
    try {
      await fn(f.id);
    } catch (error) {
      window.dispatchEvent(new CustomEvent('stw:api-error', { detail: { message: error.message, code: error.code || 'FOLLOWUP_ACTION_FAILED' } }));
    } finally {
      setBusy('');
    }
  };
  return (
    <Card hover style={{ padding: 14 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ width: 36, height: 36, borderRadius: 10, background: C.cardElev, border: `1px solid ${C.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: C.blueElectric, flex: 'none' }}>
          <Icon name={kindIcon} size={16}/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ font: '700 14px/1.2 Inter, system-ui, sans-serif', flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{f.company}</div>
            <PriorityPill level={f.priority} size="sm"/>
          </div>
          <div style={{ font: '400 13px/18px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 2 }}>{f.detail}</div>
        </div>
      </div>
      <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
        <span style={{ font: '600 11px/1 Inter, system-ui, sans-serif', color: f.due.startsWith('Overdue') ? '#FCA5A5' : C.fg2, padding: '4px 9px', borderRadius: 999, background: f.due.startsWith('Overdue') ? '#3B0D0D' : C.cardElev, border: `1px solid ${f.due.startsWith('Overdue') ? '#7F1D1D' : C.border}` }}>
          {f.due}
        </span>
        <StatusPill kind={f.lead} size="sm" dot={false}>{cap(f.lead)}</StatusPill>
        <SyncChip state={f.task} label={f.task === 'created' ? 'Task' : f.task === 'pending' ? 'Task pending' : 'Task off'} size="sm"/>
        <SyncChip state={f.cal} label={f.cal === 'created' ? 'Cal' : f.cal === 'pending' ? 'Cal pending' : 'Cal off'} size="sm"/>
      </div>
      <div style={{ marginTop: 10, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        <button type="button" disabled={Boolean(busy)} onClick={() => act('complete', window.ShieldTechApi.completeFollowup)} style={{ height: 40, borderRadius: 12, background: '#052E16', color: '#86EFAC', border: '1px solid #166534', font: '600 13px/1 Inter, system-ui, sans-serif', cursor: busy ? 'wait' : 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
          <Icon name="check" size={14}/> Complete
        </button>
        <button type="button" disabled={Boolean(busy)} onClick={() => act('snooze', window.ShieldTechApi.snoozeFollowup)} style={{ height: 40, borderRadius: 12, background: C.cardElev, color: C.fg1, border: `1px solid ${C.border}`, font: '600 13px/1 Inter, system-ui, sans-serif', cursor: busy ? 'wait' : 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
          <Icon name="snooze" size={14}/> Snooze
        </button>
      </div>
    </Card>
  );
}

// ─────────────────────────────────────────────────────────────
// APPROVAL INBOX
// ─────────────────────────────────────────────────────────────
function ScreenApprovals({ goto }) {
  return (
    <div className="slide-up" style={{ padding: '0 0 140px' }}>
      <BackRow onBack={() => goto('today')} label="Today" center={`APPROVALS · ${APPROVALS.length}`}/>

      <div style={{ padding: '8px 20px 0' }}>
        <div style={{ font: '700 28px/1.1 Rajdhani, "Inter", system-ui, sans-serif', letterSpacing: '-0.02em' }}>
          {APPROVALS.length} things need your eyes.
        </div>
        <div style={{ font: '400 15px/22px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 6 }}>
          I drafted them. You decide.
        </div>
      </div>

      <div style={{ padding: '16px 20px 0', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {APPROVALS.map((a, i) => (
          <ApprovalCard key={a.id} a={a} glow={i === 0}/>
        ))}
      </div>
    </div>
  );
}

function ApprovalCard({ a, glow }) {
  const typeIcon = { 'Email draft': 'mail', 'Bid decision': 'gavel', 'Mark dead': 'powerOff', 'Calendar invite': 'calendar' }[a.type] || 'inbox';
  const sendApprovalAction = async (action) => {
    try {
      await window.ShieldTechApi?.request?.(`/api/approvals/${encodeURIComponent(a.id)}/${action}`, { method: 'POST', body: JSON.stringify({}) });
      await window.ShieldTechApi?.hydrateGlobals?.();
    } catch (error) {
      window.dispatchEvent(new CustomEvent('stw:api-error', { detail: { message: error.message, code: error.code || 'APPROVAL_ACTION_FAILED' } }));
    }
  };
  return (
    <Card glow={glow ? 'purple' : null} style={{ padding: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <div style={{ width: 28, height: 28, borderRadius: 8, background: 'rgba(168,85,247,0.12)', border: '1px solid rgba(168,85,247,0.32)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: C.assistantSoft, flex: 'none' }}>
          <Icon name={typeIcon} size={14} color={C.assistantSoft}/>
        </div>
        <StatusPill kind="approval" size="sm" dot={false}>{a.type}</StatusPill>
        <Caption style={{ marginLeft: 'auto' }}>{a.company}</Caption>
      </div>

      <div style={{ font: '700 17px/1.25 Rajdhani, "Inter", system-ui, sans-serif' }}>{a.subject}</div>

      <div style={{ marginTop: 10, padding: 14, background: C.cardElev, borderRadius: 14, font: '400 14px/20px Inter, system-ui, sans-serif', color: C.fg2, whiteSpace: 'pre-wrap' }}>
        {a.body}
      </div>

      <div style={{ marginTop: 10, padding: '8px 12px', background: 'rgba(0,163,255,0.06)', border: '1px solid rgba(0,163,255,0.18)', borderRadius: 12, display: 'flex', alignItems: 'center', gap: 8 }}>
        <Icon name="eye" size={14} color={C.blueElectric}/>
        <span style={{ font: '500 12px/16px Inter, system-ui, sans-serif', color: C.fg2 }}>
          <span style={{ color: C.blueElectric, fontWeight: 600 }}>Approval needed:</span> {a.why}
        </span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, marginTop: 12 }}>
        <SecondaryButton full leadingIcon="edit" onClick={() => sendApprovalAction('edit')}>Edit</SecondaryButton>
        <DangerButton full leadingIcon="x" onClick={() => sendApprovalAction('reject')}>Reject</DangerButton>
        <PrimaryButton full leadingIcon="check" onClick={() => sendApprovalAction('approve')}>Approve</PrimaryButton>
      </div>
    </Card>
  );
}

Object.assign(window, {
  ScreenAssistant, ScreenPipeline, ScreenFollowups, ScreenApprovals,
  PipelineLeadCard, FollowUpCard, ApprovalCard, ChatBubble,
});
