// Requests tab — list with filters. Click to open detail page.

function RequestsTab({ pal, go }) {
  const t = useTweaks();
  const jm = window.JOY_MOVE;
  const filler = t.demo !== 'clean';
  const [filter, setFilter] = React.useState('all');
  const [q, setQ] = React.useState('');

  const all = filler ? jm.requests : [];
  const filters = [
    ['all', 'All', all.length],
    ['open', 'Open', all.filter(r => r.status !== 'Done').length],
    ['awaiting', 'Awaiting you', all.filter(r => r.status === 'Awaiting you').length],
    ['done', 'Completed', all.filter(r => r.status === 'Done').length],
  ];

  let shown = all;
  if (filter === 'open') shown = shown.filter(r => r.status !== 'Done');
  if (filter === 'awaiting') shown = shown.filter(r => r.status === 'Awaiting you');
  if (filter === 'done') shown = shown.filter(r => r.status === 'Done');
  if (q.trim()) shown = shown.filter(r => (r.title + ' ' + r.id).toLowerCase().includes(q.toLowerCase()));

  return (
    <Page pal={pal}
      kicker="Work"
      title="Requests"
      sub="Every update, bug, and small project — filed, estimated, and tracked against your monthly hours."
      actions={<BtnPrimary pal={pal} onClick={go.newRequest}>+ New request</BtnPrimary>}
    >
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20, gap: 16, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 8 }}>
          {filters.map(([k, label, n]) => (
            <Pill key={k} pal={pal} active={filter === k} onClick={() => setFilter(k)}>
              {label} <span style={{ opacity: 0.7, marginLeft: 4 }}>{n}</span>
            </Pill>
          ))}
        </div>
        <div style={{ width: 260 }}>
          <Input pal={pal} placeholder="Search requests…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
      </div>

      <Card pal={pal}>
        {shown.length === 0 ? (
          <EmptyState pal={pal} icon="⊞"
            title={filler ? "Nothing matches" : "No requests yet"}
            body={filler ? "Try another filter or clear your search." : `The first time you need a change, file it here. We'll estimate, confirm, and get to work.`}
            action={!filler ? "+ File your first request" : null}
            onAction={go.newRequest}
          />
        ) : (
          <>
            <div style={{
              display: 'grid', gridTemplateColumns: '90px 1fr 140px 110px 110px 110px',
              padding: '14px 24px', borderBottom: `1px solid ${pal.border}`,
              fontSize: 10, fontWeight: 700, letterSpacing: '0.1em',
              textTransform: 'uppercase', color: pal.muted,
            }}>
              <div>ID</div>
              <div>Title</div>
              <div>Status</div>
              <div>Opened</div>
              <div>Updated</div>
              <div style={{ textAlign: 'right' }}>Hours</div>
            </div>
            {shown.map(r => (
              <div key={r.id} onClick={() => go.request(r.id)} style={{
                display: 'grid', gridTemplateColumns: '90px 1fr 140px 110px 110px 110px',
                padding: '18px 24px', cursor: 'pointer',
                borderBottom: `1px solid ${pal.border}`,
                alignItems: 'center',
                transition: 'background 0.12s',
              }}
                onMouseEnter={e => e.currentTarget.style.background = pal.warm}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
              >
                <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: pal.muted }}>{r.id}</div>
                <div>
                  <div style={{ fontSize: 14, color: pal.textStrong, fontWeight: 500, marginBottom: 3 }}>{r.title}</div>
                  <div style={{ fontSize: 11, color: pal.muted }}>{r.category} · {r.priority}</div>
                </div>
                <div><StatusChip pal={pal} s={r.status} /></div>
                <div style={{ fontSize: 12, color: pal.muted }}>{r.opened}</div>
                <div style={{ fontSize: 12, color: pal.muted }}>{r.updated}</div>
                <div style={{ textAlign: 'right', fontSize: 13, color: pal.textStrong, fontWeight: 600, fontFamily: "'JetBrains Mono', monospace" }}>{r.est.toFixed(2)}</div>
              </div>
            ))}
            {/* Summary strip */}
            <div style={{ padding: '14px 24px', display: 'flex', justifyContent: 'space-between', fontSize: 12, color: pal.muted, background: pal.warm }}>
              <span>{shown.length} request{shown.length === 1 ? '' : 's'}</span>
              <span>Total estimated: <strong style={{ color: pal.textStrong }}>{shown.reduce((s, r) => s + r.est, 0).toFixed(2)}h</strong></span>
            </div>
          </>
        )}
      </Card>
    </Page>
  );
}

function RequestDetail({ pal, go, id }) {
  const jm = window.JOY_MOVE;
  const r = jm.requests.find(x => x.id === id);
  const [reply, setReply] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [sentMsg, setSentMsg] = React.useState(null);
  // Track local thread state so new replies appear immediately
  const [localThread, setLocalThread] = React.useState((r && r.thread) || []);

  const sendReply = async () => {
    if (!reply.trim()) return;
    setSending(true);
    const replyText = reply;
    try {
      const params = window.getPortalParams();
      const slug = params.slug;
      const isAdmin = !!params.adminKey;
      const role = isAdmin ? 'agency' : 'client';
      const fromName = isAdmin ? 'Lance' : ((jm.brand && jm.brand.contact) || 'You');
      await window.Portal.submitReply(slug, id, replyText, { role, fromName });
      // Optimistically append the new message to the visible thread
      const now = new Date();
      const timeLabel = now.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
      const newMessage = {
        from: fromName,
        role,
        when: timeLabel,
        body: replyText,
      };
      setLocalThread(prev => [...prev, newMessage]);
      // Also update the underlying record so a later re-render still has it
      if (r) r.thread = [...(r.thread || []), newMessage];
      setSentMsg('Reply sent.');
      setReply('');
      setTimeout(() => setSentMsg(null), 3000);
    } catch (e) {
      setSentMsg('Could not send — try again.');
    } finally {
      setSending(false);
    }
  };

  if (!r) {
    return <Page pal={pal} title="Request not found" actions={<BtnGhost pal={pal} onClick={() => go.to('requests')}>← All requests</BtnGhost>} />;
  }

  return (
    <div style={{ padding: '28px 48px 80px', maxWidth: 1200, margin: '0 auto' }}>
      {/* Breadcrumb */}
      <div style={{ marginBottom: 20, fontSize: 12, color: pal.muted }}>
        <a onClick={() => go.to('requests')} style={{ color: pal.muted, cursor: 'pointer' }}>Requests</a>
        <span style={{ margin: '0 8px' }}>/</span>
        <span style={{ fontFamily: "'JetBrains Mono', monospace" }}>{r.id}</span>
      </div>

      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 28, gap: 24, flexWrap: 'wrap' }}>
        <div style={{ flex: 1, minWidth: 320 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
            <StatusChip pal={pal} s={r.status} size="lg" />
            <span style={{ fontSize: 12, color: pal.muted }}>· Priority: <strong style={{ color: pal.textStrong, fontWeight: 600 }}>{r.priority}</strong></span>
            <span style={{ fontSize: 12, color: pal.muted }}>· {r.category}</span>
          </div>
          <Display pal={pal} size={32} style={{ maxWidth: 760 }}>{r.title}</Display>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <BtnGhost pal={pal} onClick={() => go.to('requests')}>← Back</BtnGhost>
          {r.status !== 'Done' && <BtnGhost pal={pal}>Mark done</BtnGhost>}
        </div>
      </div>

      {/* Two-column layout */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: 24 }}>
        <div>
          {/* Description */}
          <Card pal={pal} padding={24} style={{ marginBottom: 20 }}>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: pal.muted, marginBottom: 10 }}>Description</div>
            <div style={{ fontSize: 14, color: pal.textStrong, lineHeight: 1.65 }}>{r.description}</div>
            {r.attachments.length > 0 && (
              <div style={{ marginTop: 18, paddingTop: 16, borderTop: `1px solid ${pal.border}` }}>
                <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: pal.muted, marginBottom: 10 }}>Attachments</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {r.attachments.map(a => (
                    <div key={a} style={{
                      padding: '8px 12px', background: pal.warm, border: `1px solid ${pal.border}`,
                      borderRadius: 8, fontSize: 12, color: pal.textStrong, display: 'flex', gap: 8, alignItems: 'center',
                    }}>
                      <span style={{ color: pal.accent }}>⎙</span> {a}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </Card>

          {/* Thread */}
          <Card pal={pal}>
            <CardHead pal={pal} label={`Conversation · ${localThread.length} ${localThread.length === 1 ? 'message' : 'messages'}`} />
            <div style={{ borderTop: `1px solid ${pal.border}` }} />
            {localThread.length === 0 ? (
              <div style={{ padding: '32px 24px', textAlign: 'center', fontSize: 13, color: pal.muted, fontStyle: 'italic' }}>
                This request wrapped up without any back-and-forth.
              </div>
            ) : (
              <div style={{ padding: '8px 0' }}>
                {localThread.map((m, i) => (
                  <div key={i} style={{
                    padding: '18px 24px',
                    borderTop: i === 0 ? 'none' : `1px solid ${pal.border}`,
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                      <div style={{
                        width: 28, height: 28, borderRadius: '50%',
                        background: m.role === 'agency' ? pal.accent : pal.warm,
                        color: m.role === 'agency' ? pal.onAccent : pal.textStrong,
                        display: 'grid', placeItems: 'center',
                        fontSize: 10, fontWeight: 700,
                        border: m.role === 'client' ? `1px solid ${pal.border}` : 'none',
                      }}>{m.from.split(' ').map(s => s[0]).join('').slice(0, 2)}</div>
                      <div style={{ fontSize: 13, fontWeight: 600, color: pal.textStrong }}>{m.from}</div>
                      <div style={{ fontSize: 11, color: pal.muted }}>· {m.when}</div>
                    </div>
                    <div style={{ fontSize: 14, color: pal.text, lineHeight: 1.6, paddingLeft: 38 }}>{m.body}</div>
                  </div>
                ))}
              </div>
            )}
            {/* Reply box */}
            <div style={{ padding: 20, borderTop: `1px solid ${pal.border}`, background: pal.warm }}>
              <Textarea pal={pal} placeholder="Write a reply…" value={reply} onChange={e => setReply(e.target.value)} />
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, alignItems: 'center' }}>
                <span style={{ fontSize: 11, color: pal.muted, fontStyle: 'italic' }}>File attachments coming soon</span>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  {sentMsg && <span style={{ fontSize: 11, color: pal.accent, fontStyle: 'italic' }}>{sentMsg}</span>}
                  <BtnPrimary pal={pal} disabled={!reply.trim() || sending} onClick={sendReply}>{sending ? 'Sending…' : 'Send reply'}</BtnPrimary>
                </div>
              </div>
            </div>
          </Card>
        </div>

        {/* Sidebar */}
        <div>
          <Card pal={pal} padding={20} style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: pal.muted, marginBottom: 14 }}>Details</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <KV pal={pal} label="Request ID" v={r.id} mono />
              <KV pal={pal} label="Opened" v={r.opened} />
              <KV pal={pal} label="Last update" v={r.updated} />
              <KV pal={pal} label="Priority" v={r.priority} />
              <KV pal={pal} label="Category" v={r.category} />
              <KV pal={pal} label="Estimated hours" v={`${r.est.toFixed(2)} hrs`} mono />
              <KV pal={pal} label="Assigned" v={r.assigned} />
            </div>
          </Card>
          <Card pal={pal} padding={20}>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: pal.muted, marginBottom: 10 }}>What happens next</div>
            <div style={{ fontSize: 12, color: pal.text, lineHeight: 1.6 }}>
              {r.status === 'In progress' && 'We\'re working on it. Expect a preview link or resolution within your plan\'s response window.'}
              {r.status === 'Awaiting you' && 'We\'re paused until you reply above — once you do, we\'ll pick it back up.'}
              {r.status === 'Done' && 'This request is complete. Let us know if anything needs adjustment.'}
              {r.status === 'Queued' && 'In queue — we\'ll start this within your plan\'s response window.'}
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

window.RequestsTab = RequestsTab;
window.RequestDetail = RequestDetail;
