// STUDIO — Publish tab (improvements 17–18: signature management, scheduled publishing)
const { useState: useStPb } = React;
const TspPb = window.ArbiterTokens;

function StudioPublish() {
  const st   = window.__st;
  const data = window.STUDIO_DATA;
  const [subTab, setSubTab] = useStPb('signatures');

  const signatoryStatus = (s) => ({
    Signed:  { bg: 'rgba(5,150,105,0.08)',  color: '#059669', icon: 'ok' },
    Pending: { bg: 'rgba(180,83,9,0.08)',   color: '#B45309', icon: '○' },
  }[s] || { bg: TspPb.color.bg.secondary, color: TspPb.color.text.secondary, icon: '?' });

  const scheduleStatus = (s) => ({
    Ready:   { bg: 'rgba(5,150,105,0.08)',  color: '#059669' },
    Waiting: { bg: 'rgba(29,78,216,0.08)',  color: '#1D4ED8' },
    Blocked: { bg: 'rgba(185,28,28,0.08)',  color: '#B91C1C' },
  }[s] || { bg: TspPb.color.bg.secondary, color: TspPb.color.text.secondary });

  const completionRatio = (req) => {
    const signed = req.signatories.filter(s => s.status === 'Signed').length;
    return { signed, total: req.signatories.length, pct: Math.round(signed / req.signatories.length * 100) };
  };

  return (
    <div>
      {/* Sub-tab */}
      <div style={{ display: 'flex', gap: '0', borderBottom: `1px solid ${TspPb.color.border.light}`, marginBottom: '16px' }}>
        {[['signatures',' Signature Management'],['scheduled','▶ Scheduled Publishing'],['history','◈ Publish History']].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 : TspPb.color.text.secondary, borderBottom: subTab === id ? `2px solid ${st.gold}` : '2px solid transparent', fontFamily: TspPb.font.family, marginBottom: '-1px' }}>
            {label}
          </button>
        ))}
      </div>

      {/* ── Signature Management ──────────────────────────────────── */}
      {subTab === 'signatures' && (
        <div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 260px', gap: '16px', alignItems: 'start' }}>
            <div>
              {data.signatureRequests.map(req => {
                const { signed, total, pct } = completionRatio(req);
                const allSigned = signed === total;
                return (
                  <div key={req.id} style={{ ...st.card, marginBottom: '12px' }}>
                    <div style={{ padding: '12px 16px', borderBottom: `1px solid ${TspPb.color.border.light}`, display: 'flex', alignItems: 'center', gap: '12px' }}>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: '13px', fontWeight: 600, color: TspPb.color.text.primary, marginBottom: '1px' }}>{req.doc}</div>
                        <div style={{ fontSize: '11px', color: TspPb.color.text.tertiary }}>{req.matter} · Created {req.created}</div>
                      </div>
                      <div style={{ textAlign: 'right', flexShrink: 0 }}>
                        <div style={{ fontSize: '11px', fontWeight: 700, color: allSigned ? '#059669' : st.amber, fontFamily: TspPb.font.mono }}>{signed}/{total} signed</div>
                        <div style={{ fontSize: '10px', color: TspPb.color.text.tertiary, marginTop: '1px' }}>Deadline {req.deadline}</div>
                      </div>
                      <span style={{ ...st.tag, ...(allSigned ? { background: 'rgba(5,150,105,0.08)', color: '#059669' } : { background: 'rgba(180,83,9,0.08)', color: '#B45309' }) }}>
                        {allSigned ? 'Complete' : 'In Progress'}
                      </span>
                    </div>

                    {/* Progress bar */}
                    <div style={{ padding: '10px 16px 4px' }}>
                      <div style={{ height: '4px', borderRadius: '2px', background: TspPb.color.bg.secondary, overflow: 'hidden', marginBottom: '12px' }}>
                        <div style={{ height: '100%', width: `${pct}%`, background: allSigned ? '#059669' : st.gold, borderRadius: '2px', transition: 'width 0.3s' }} />
                      </div>

                      {/* Signatory list */}
                      <div style={{ display: 'flex', flexDirection: 'column', gap: '6px', paddingBottom: '10px' }}>
                        {req.signatories.map((sig, i) => {
                          const ss = signatoryStatus(sig.status);
                          return (
                            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '8px 10px', borderRadius: '6px', background: sig.status === 'Signed' ? 'rgba(5,150,105,0.04)' : TspPb.color.bg.secondary, border: `1px solid ${sig.status === 'Signed' ? 'rgba(5,150,105,0.15)' : TspPb.color.border.light}` }}>
                              <div style={{ width: '28px', height: '28px', borderRadius: '50%', background: ss.bg, border: `1.5px solid ${ss.color}`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                                <span style={{ fontSize: '12px', color: ss.color, fontWeight: 700 }}>{ss.icon}</span>
                              </div>
                              <div style={{ flex: 1 }}>
                                <div style={{ fontSize: '12px', fontWeight: 600, color: TspPb.color.text.primary }}>{sig.name}</div>
                                <div style={{ fontSize: '10px', color: TspPb.color.text.tertiary }}>{sig.role}</div>
                              </div>
                              {sig.status === 'Signed'
                                ? <span style={{ fontSize: '10px', color: '#059669', fontWeight: 500 }}>Signed {sig.signedAt}</span>
                                : <button style={{ ...st.btnSecondary, fontSize: '10px', padding: '3px 8px' }}>Send Reminder</button>
                              }
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Right panel */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
              <div style={st.card}>
                <div style={st.cardH}><span>Signature Summary</span></div>
                <div style={{ padding: '12px 16px' }}>
                  {[
                    ['Active requests', data.signatureRequests.length, st.gold],
                    ['Signatures collected', data.signatureRequests.reduce((acc, r) => acc + r.signatories.filter(s => s.status === 'Signed').length, 0), st.emerald],
                    ['Pending signatures', data.signatureRequests.reduce((acc, r) => acc + r.signatories.filter(s => s.status === 'Pending').length, 0), st.amber],
                    ['Avg completion', '62%', TspPb.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 ${TspPb.color.border.light}` }}>
                      <span style={{ fontSize: '11px', color: TspPb.color.text.secondary }}>{k}</span>
                      <span style={{ fontSize: '16px', fontWeight: 700, color: c, fontFamily: TspPb.font.mono }}>{v}</span>
                    </div>
                  ))}
                </div>
              </div>
              <div style={st.card}>
                <div style={st.cardH}><span>Quick Actions</span></div>
                <div style={{ padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: '6px' }}>
                  {['New signature request', 'Remind all pending', 'Bulk send reminders', 'Export signing report'].map(a => (
                    <button key={a} style={{ ...st.btnSecondary, textAlign: 'left', fontSize: '11px' }}>{a}</button>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ── Scheduled Publishing ──────────────────────────────────── */}
      {subTab === 'scheduled' && (
        <div>
          <div style={{ padding: '10px 16px', background: st.goldBg, border: `1px solid ${st.goldBorder}`, borderRadius: TspPb.radius.lg, marginBottom: '16px' }}>
            <div style={{ fontSize: '12px', fontWeight: 600, color: st.goldDeep, marginBottom: '2px' }}>◆ Conditional Publishing Queue</div>
            <div style={{ fontSize: '11px', color: TspPb.color.text.secondary }}>Documents publish automatically when their conditions are met or their scheduled time arrives. Ready items can be published immediately.</div>
          </div>

          <div style={st.card}>
            <div style={{ display: 'grid', gridTemplateColumns: '2.2fr 1.5fr 1.6fr 1.2fr 0.8fr 0.9fr', borderBottom: `1px solid ${TspPb.color.border.light}` }}>
              {['Document', 'Destination', 'Scheduled For', 'Condition', 'Countdown', 'Status'].map(h => <div key={h} style={st.th}>{h}</div>)}
            </div>
            {data.scheduledPublish.map((item, i) => {
              const ss = scheduleStatus(item.status);
              return (
                <div key={item.id} style={{ display: 'grid', gridTemplateColumns: '2.2fr 1.5fr 1.6fr 1.2fr 0.8fr 0.9fr', background: i % 2 === 0 ? 'transparent' : TspPb.color.bg.secondary, alignItems: 'center' }}>
                  <div style={{ ...st.td, fontWeight: 500, fontSize: '12px', color: TspPb.color.text.primary }}>{item.doc}</div>
                  <div style={{ ...st.td, fontSize: '11px', color: TspPb.color.text.secondary }}>{item.destination}</div>
                  <div style={{ ...st.td, fontSize: '11px', color: TspPb.color.text.secondary }}>{item.scheduledFor}</div>
                  <div style={{ ...st.td, fontSize: '10px', color: TspPb.color.text.tertiary, fontStyle: 'italic' }}>{item.condition}</div>
                  <div style={{ ...st.td, fontFamily: TspPb.font.mono, fontSize: '11px', fontWeight: 600, color: item.status === 'Blocked' ? '#B91C1C' : item.countdown.startsWith('0d') ? st.amber : TspPb.color.text.primary }}>{item.countdown}</div>
                  <div style={{ ...st.td, gap: '4px', flexDirection: 'column', alignItems: 'flex-start' }}>
                    <span style={{ ...st.tag, ...ss }}>{item.status}</span>
                    {item.status === 'Ready' && <button style={{ ...st.btnPrimary, fontSize: '10px', padding: '2px 7px' }}>Publish Now</button>}
                    {item.status !== 'Ready' && <button style={{ ...st.btnGhost, fontSize: '10px', padding: '2px 7px', color: TspPb.color.text.tertiary }}>Cancel</button>}
                  </div>
                </div>
              );
            })}
          </div>

          <div style={{ display: 'flex', gap: '8px', marginTop: '10px' }}>
            <button style={{ ...st.btnPrimary, fontSize: '11px' }}>+ Schedule New Publication</button>
            <button style={{ ...st.btnSecondary, fontSize: '11px' }}>Publish All Ready</button>
            <button style={{ ...st.btnSecondary, fontSize: '11px', marginLeft: 'auto' }}>Export Schedule</button>
          </div>
        </div>
      )}

      {/* ── Publish History ───────────────────────────────────────── */}
      {subTab === 'history' && (
        <div style={st.card}>
          <div style={{ display: 'grid', gridTemplateColumns: '2.5fr 1.5fr 0.8fr 0.6fr 0.8fr 1.1fr', borderBottom: `1px solid ${TspPb.color.border.light}` }}>
            {['Document', 'Destination', 'Date', 'Format', 'Status', 'Receipt'].map(h => <div key={h} style={st.th}>{h}</div>)}
          </div>
          {data.published.map((p, i) => (
            <div key={p.id} style={{ display: 'grid', gridTemplateColumns: '2.5fr 1.5fr 0.8fr 0.6fr 0.8fr 1.1fr', background: i % 2 === 0 ? 'transparent' : TspPb.color.bg.secondary }}>
              <div style={{ ...st.td, fontWeight: 500, fontSize: '12px', color: TspPb.color.text.primary }}>{p.title}</div>
              <div style={{ ...st.td, fontSize: '11px', color: TspPb.color.text.secondary }}>{p.destination}</div>
              <div style={{ ...st.td, fontSize: '11px', color: TspPb.color.text.secondary }}>{p.date}</div>
              <div style={st.td}><span style={{ ...st.tag, background: TspPb.color.bg.secondary, color: TspPb.color.text.secondary }}>{p.format}</span></div>
              <div style={st.td}><span style={{ ...st.tag, ...(p.status === 'Confirmed' || p.status === 'Delivered' ? { background: 'rgba(5,150,105,0.08)', color: '#059669' } : { background: 'rgba(180,83,9,0.08)', color: '#B45309' }) }}>{p.status}</span></div>
              <div style={{ ...st.td, fontFamily: TspPb.font.mono, fontSize: '10px', color: TspPb.color.text.tertiary }}>{p.receipt}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

window.StudioPublish = StudioPublish;
