// STUDIO — Reviews tab (improvements 11–12: co-author queue, deadline escalation)
const { useState: useStRv } = React;
const TspRv = window.ArbiterTokens;

function StudioReviews() {
  const st   = window.__st;
  const data = window.STUDIO_DATA;
  const [subTab, setSubTab] = useStRv('queue');

  const urgent = data.reviews.filter(r => r.urgent && ['Pending','In Progress'].includes(r.status));

  const reviewStatusColor = (s) => ({
    'Pending':     { bg: 'rgba(180,83,9,0.08)',  color: '#B45309' },
    'In Progress': { bg: 'rgba(29,78,216,0.08)', color: '#1D4ED8' },
    'Completed':   { bg: 'rgba(5,150,105,0.08)', color: '#059669' },
    'Approved':    { bg: 'rgba(5,150,105,0.08)', color: '#059669' },
  }[s] || { bg: TspRv.color.bg.secondary, color: TspRv.color.text.secondary });

  const priorityColor = (p) => ({
    'Critical': { bg: 'rgba(185,28,28,0.08)', color: '#B91C1C' },
    'High':     { bg: 'rgba(234,88,12,0.08)', color: '#EA580C' },
    'Medium':   { bg: 'rgba(180,83,9,0.08)',  color: '#B45309' },
    'Low':      { bg: TspRv.color.bg.secondary, color: TspRv.color.text.secondary },
  }[p] || { bg: TspRv.color.bg.secondary, color: TspRv.color.text.secondary });

  const stepColor = (s) => ({
    completed: st.emerald,
    active:    st.gold,
    pending:   TspRv.color.text.tertiary,
  }[s]);

  const stepBg = (s) => ({
    completed: 'rgba(5,150,105,0.08)',
    active:    st.goldBg,
    pending:   TspRv.color.bg.secondary,
  }[s]);

  return (
    <div>
      {/* Sub-tab */}
      <div style={{ display: 'flex', gap: '0', borderBottom: `1px solid ${TspRv.color.border.light}`, marginBottom: '16px' }}>
        {[['queue', '◉ Review Queue'], ['coauthor', '◈ Co-Author Queue']].map(([id, label]) => (
          <button key={id} onClick={() => setSubTab(id)}
            style={{ padding: '8px 18px', fontSize: '12px', fontWeight: 500, cursor: 'pointer', border: 'none', background: 'transparent', color: subTab === id ? st.gold : TspRv.color.text.secondary, borderBottom: subTab === id ? `2px solid ${st.gold}` : '2px solid transparent', fontFamily: TspRv.font.family, marginBottom: '-1px' }}>
            {label}
          </button>
        ))}
      </div>

      {/* ── Review Queue ──────────────────────────────────────────── */}
      {subTab === 'queue' && (
        <div>
          {/* Deadline escalation banner */}
          {urgent.length > 0 && (
            <div style={{ padding: '12px 16px', background: 'rgba(185,28,28,0.06)', border: `1px solid rgba(185,28,28,0.2)`, borderRadius: TspRv.radius.lg, marginBottom: '14px', display: 'flex', alignItems: 'center', gap: '12px' }}>
              <span style={{ fontSize: '16px', color: st.crimson }}><Icons.Flag size={11}/></span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: '12px', fontWeight: 600, color: st.crimson, marginBottom: '2px' }}>
                  {urgent.length} review{urgent.length > 1 ? 's' : ''} due today — filing deadline at risk
                </div>
                <div style={{ fontSize: '11px', color: TspRv.color.text.secondary }}>
                  {urgent.map(r => r.doc).join(', ')} · Filing deadline Apr 25 depends on these reviews completing today
                </div>
              </div>
              <button style={{ ...st.btnSecondary, fontSize: '11px', borderColor: 'rgba(185,28,28,0.3)', color: st.crimson }}>Send Urgent Reminder</button>
              <button style={{ ...st.btnSecondary, fontSize: '11px', borderColor: 'rgba(185,28,28,0.3)', color: st.crimson }}>Escalate</button>
            </div>
          )}

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 280px', gap: '16px', alignItems: 'start' }}>
            <div>
              {[['Active Reviews', data.reviews.filter(r => ['Pending','In Progress'].includes(r.status))],
                ['Completed',      data.reviews.filter(r => ['Completed','Approved'].includes(r.status))]].map(([section, rows]) => (
                <div key={section} style={{ marginBottom: '8px' }}>
                  <div style={{ fontSize: '11px', fontWeight: 600, color: TspRv.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: '7px' }}>{section} ({rows.length})</div>
                  <div style={st.card}>
                    <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1.1fr 0.6fr 0.8fr 0.8fr', borderBottom: `1px solid ${TspRv.color.border.light}` }}>
                      {['Document', 'Reviewer', 'Due', 'Comments', 'Priority', 'Status'].map(h => <div key={h} style={st.th}>{h}</div>)}
                    </div>
                    {rows.map((r, i) => (
                      <div key={r.id} style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1.1fr 0.6fr 0.8fr 0.8fr', background: r.urgent ? 'rgba(185,28,28,0.03)' : i % 2 === 0 ? 'transparent' : TspRv.color.bg.secondary }}>
                        <div style={{ ...st.td, fontWeight: 500 }}>
                          {r.urgent && <span style={{ fontSize: '10px', color: st.crimson, fontWeight: 700, marginRight: '5px' }}><Icons.Flag size={11}/></span>}
                          {r.doc}
                        </div>
                        <div style={st.td}>{r.reviewer}</div>
                        <div style={{ ...st.td, fontSize: '11px', color: r.urgent ? st.crimson : TspRv.color.text.secondary, fontWeight: r.urgent ? 600 : 400 }}>{r.due}</div>
                        <div style={st.td}>{r.comments > 0 ? <span style={{ fontSize: '11px', color: st.amber, fontWeight: 600 }}>◉ {r.comments}</span> : <span style={{ fontSize: '11px', color: TspRv.color.text.tertiary }}>—</span>}</div>
                        <div style={st.td}><span style={{ ...st.tag, ...priorityColor(r.priority) }}>{r.priority}</span></div>
                        <div style={st.td}><span style={{ ...st.tag, ...reviewStatusColor(r.status) }}>{r.status}</span></div>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>

            {/* Right summary */}
            <div>
              <div style={st.card}>
                <div style={st.cardH}><span>Queue Summary</span></div>
                <div style={{ padding: '12px 16px' }}>
                  {[
                    ['Pending review', data.reviews.filter(r => r.status === 'Pending').length, st.amber],
                    ['In progress',    data.reviews.filter(r => r.status === 'In Progress').length, st.cobalt],
                    ['Completed',      data.reviews.filter(r => ['Completed','Approved'].includes(r.status)).length, st.emerald],
                    ['Overdue',        urgent.length, st.crimson],
                    ['Avg turnaround', '18h', TspRv.color.text.primary],
                  ].map(([k, v, c]) => (
                    <div key={k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px', paddingBottom: '10px', borderBottom: `1px solid ${TspRv.color.border.light}` }}>
                      <span style={{ fontSize: '11px', color: TspRv.color.text.secondary }}>{k}</span>
                      <span style={{ fontSize: '16px', fontWeight: 700, color: c, fontFamily: TspRv.font.mono }}>{v}</span>
                    </div>
                  ))}
                </div>
              </div>
              <div style={st.card}>
                <div style={st.cardH}><span>Actions</span></div>
                <div style={{ padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: '6px' }}>
                  {['Request new review', 'Remind all reviewers', 'Export review report', 'Escalate overdue items'].map(a => (
                    <button key={a} style={{ ...st.btnSecondary, textAlign: 'left', fontSize: '11px' }}>{a}</button>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ── Co-Author Queue ───────────────────────────────────────── */}
      {subTab === 'coauthor' && (
        <div>
          <div style={{ padding: '10px 16px', background: st.goldBg, border: `1px solid ${st.goldBorder}`, borderRadius: TspRv.radius.lg, marginBottom: '16px' }}>
            <div style={{ fontSize: '12px', fontWeight: 600, color: st.goldDeep, marginBottom: '2px' }}>◆ Sequential Co-Authoring</div>
            <div style={{ fontSize: '11px', color: TspRv.color.text.secondary }}>Documents pass automatically to the next author when each step is completed. The document is locked to others during each step.</div>
          </div>

          {data.coauthorQueue.map((queue, qi) => {
            const activeStep = queue.steps.findIndex(s => s.status === 'active');
            return (
              <div key={qi} style={{ ...st.card, marginBottom: '16px' }}>
                <div style={st.cardH}>
                  <span>{queue.doc}</span>
                  <span style={{ fontSize: '11px', color: TspRv.color.text.tertiary, fontWeight: 400 }}>Step {activeStep + 1} of {queue.steps.length}</span>
                </div>

                {/* Progress track */}
                <div style={{ padding: '16px 20px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0', position: 'relative' }}>
                    {queue.steps.map((step, si) => (
                      <React.Fragment key={si}>
                        {/* Step node */}
                        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flex: 1, position: 'relative', zIndex: 1 }}>
                          <div style={{ width: '36px', height: '36px', borderRadius: '50%', background: stepBg(step.status), border: `2px solid ${stepColor(step.status)}`, display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: '8px' }}>
                            {step.status === 'completed' && <span style={{ fontSize: '14px', color: st.emerald, fontWeight: 700 }}><Icons.Check size={11}/></span>}
                            {step.status === 'active'    && <span style={{ fontSize: '12px', color: st.gold, fontWeight: 700 }}>▶</span>}
                            {step.status === 'pending'   && <span style={{ fontSize: '12px', color: TspRv.color.text.tertiary }}>○</span>}
                          </div>
                          <div style={{ textAlign: 'center', maxWidth: '90px' }}>
                            <div style={{ fontSize: '11px', fontWeight: 600, color: stepColor(step.status), lineHeight: 1.3, marginBottom: '2px' }}>{step.user}</div>
                            <div style={{ fontSize: '10px', color: TspRv.color.text.tertiary, lineHeight: 1.3 }}>{step.role}</div>
                            <div style={{ fontSize: '10px', color: TspRv.color.text.secondary, lineHeight: 1.3, marginTop: '2px' }}>{step.task}</div>
                            {step.status === 'completed' && <div style={{ fontSize: '9px', color: st.emerald, marginTop: '3px' }}>ok {step.completedAt}</div>}
                            {step.status === 'active'    && <div style={{ fontSize: '9px', color: st.gold,   marginTop: '3px' }}>Due {step.dueAt}</div>}
                            {step.status === 'pending'   && step.dueAt && <div style={{ fontSize: '9px', color: TspRv.color.text.tertiary, marginTop: '3px' }}>Est. {step.dueAt}</div>}
                          </div>
                        </div>
                        {/* Connector line */}
                        {si < queue.steps.length - 1 && (
                          <div style={{ height: '2px', flex: 0, width: '24px', background: step.status === 'completed' ? st.emerald : TspRv.color.border.light, marginBottom: '32px', flexShrink: 0 }} />
                        )}
                      </React.Fragment>
                    ))}
                  </div>

                  {/* Active step action */}
                  {activeStep >= 0 && (
                    <div style={{ marginTop: '16px', padding: '10px 14px', background: st.goldBg, borderRadius: '7px', border: `1px solid ${st.goldBorder}`, display: 'flex', alignItems: 'center', gap: '10px' }}>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: '11px', fontWeight: 600, color: st.goldDeep }}>Waiting on: {queue.steps[activeStep].user}</div>
                        <div style={{ fontSize: '11px', color: TspRv.color.text.secondary, marginTop: '1px' }}>{queue.steps[activeStep].task} · Due {queue.steps[activeStep].dueAt}</div>
                      </div>
                      <button style={{ ...st.btnSecondary, fontSize: '11px' }}>Send Reminder</button>
                      <button style={{ ...st.btnPrimary, fontSize: '11px' }}>Mark Step Complete →</button>
                    </div>
                  )}
                </div>
              </div>
            );
          })}

          <button style={{ ...st.btnPrimary, marginTop: '4px' }}>+ Create Co-Author Queue</button>
        </div>
      )}
    </div>
  );
}

window.StudioReviews = StudioReviews;
