// STUDIO — Templates tab (improvements 7–8: merge fields wizard, clause library)
const { useState: useStTm } = React;
const TspTm = window.ArbiterTokens;

function StudioTemplates() {
  const st   = window.__st;
  const data = window.STUDIO_DATA;
  const [subTab,    setSubTab]    = useStTm('templates');
  const [cat,       setCat]       = useStTm('All');
  const [wizard,    setWizard]    = useStTm(null);
  const [clauseCat, setClauseCat] = useStTm('All');
  const [clauseQ,   setClauseQ]   = useStTm('');

  const cats     = ['All', 'Pleadings', 'Motions', 'Discovery', 'Contracts', 'Agreements', 'Orders', 'Correspondence', 'Court Forms'];
  const clauseCats = ['All', 'Contracts', 'Employment', 'Litigation'];
  const filtTpl  = cat === 'All' ? data.templates : data.templates.filter(t => t.category === cat);
  const filtClause = data.clauses.filter(c =>
    (clauseCat === 'All' || c.practice === clauseCat) &&
    (clauseQ === '' || c.title.toLowerCase().includes(clauseQ.toLowerCase()) || c.text.toLowerCase().includes(clauseQ.toLowerCase()))
  );

  const riskBadge = (r) => ({
    low:    { bg: 'rgba(5,150,105,0.08)',  color: '#059669', label: 'Low risk'  },
    medium: { bg: 'rgba(180,83,9,0.08)',   color: '#B45309', label: 'Review'   },
    high:   { bg: 'rgba(185,28,28,0.08)',  color: '#B91C1C', label: 'High risk' },
  }[r] || { bg: TspTm.color.bg.secondary, color: TspTm.color.text.secondary, label: r });

  return (
    <div>
      {/* Sub-tab */}
      <div style={{ display: 'flex', gap: '0', borderBottom: `1px solid ${TspTm.color.border.light}`, marginBottom: '16px' }}>
        {[['templates', '▤ Templates'], ['clauses', '◈ Clause Library']].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 : TspTm.color.text.secondary, borderBottom: subTab === id ? `2px solid ${st.gold}` : '2px solid transparent', fontFamily: TspTm.font.family, marginBottom: '-1px' }}>
            {label}
          </button>
        ))}
      </div>

      {/* ── Templates gallery ─────────────────────────────────────── */}
      {subTab === 'templates' && (
        <div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '14px', flexWrap: 'wrap', gap: '8px' }}>
            <div style={{ display: 'flex', gap: '5px', flexWrap: 'wrap' }}>
              {cats.map(c => (
                <button key={c} onClick={() => setCat(c)}
                  style={{ ...st.btnSecondary, background: cat === c ? st.goldBg : TspTm.color.bg.card, color: cat === c ? st.gold : TspTm.color.text.secondary, borderColor: cat === c ? st.gold : TspTm.color.border.light, fontSize: '11px', padding: '4px 10px' }}>
                  {c}
                </button>
              ))}
            </div>
            <button style={st.btnPrimary}>+ Create Template</button>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px' }}>
            {filtTpl.map(t => (
              <div key={t.id}
                style={{ background: TspTm.color.bg.card, border: `1px solid ${TspTm.color.border.light}`, borderRadius: TspTm.radius.lg, padding: '16px', cursor: 'pointer', transition: 'all 0.14s' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '10px' }}>
                  <div style={{ width: '36px', height: '36px', borderRadius: '8px', background: TspTm.color.bg.secondary, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '16px', color: TspTm.color.text.tertiary, border: `1px solid ${TspTm.color.border.light}` }}>{t.icon}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: '13px', fontWeight: 600, color: TspTm.color.text.primary, marginBottom: '2px' }}>{t.title}</div>
                    <div style={{ fontSize: '10px', color: TspTm.color.text.tertiary }}>{t.category}</div>
                  </div>
                </div>
                <div style={{ fontSize: '11px', color: TspTm.color.text.secondary, lineHeight: 1.5, marginBottom: '10px' }}>{t.desc}</div>
                <div style={{ fontSize: '10px', color: TspTm.color.text.tertiary, marginBottom: '10px' }}>
                  {t.fields.length} merge field{t.fields.length !== 1 ? 's' : ''} · Used {t.uses}× · Updated {t.updated}
                </div>
                <div style={{ display: 'flex', gap: '6px' }}>
                  <button style={{ ...st.btnSecondary, flex: 1, fontSize: '11px' }}>Preview</button>
                  <button onClick={() => setWizard(t)} style={{ ...st.btnPrimary, flex: 1, fontSize: '11px' }}>Use Template →</button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── Clause Library ────────────────────────────────────────── */}
      {subTab === 'clauses' && (
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '14px', flexWrap: 'wrap' }}>
            <div style={{ display: 'flex', gap: '5px' }}>
              {clauseCats.map(c => (
                <button key={c} onClick={() => setClauseCat(c)}
                  style={{ ...st.btnSecondary, background: clauseCat === c ? st.goldBg : TspTm.color.bg.card, color: clauseCat === c ? st.gold : TspTm.color.text.secondary, borderColor: clauseCat === c ? st.gold : TspTm.color.border.light, fontSize: '11px', padding: '4px 10px' }}>
                  {c}
                </button>
              ))}
            </div>
            <input value={clauseQ} onChange={e => setClauseQ(e.target.value)}
              placeholder="Search clauses..."
              style={{ padding: '6px 12px', borderRadius: '6px', border: `1px solid ${TspTm.color.border.light}`, background: TspTm.color.bg.secondary, fontSize: '12px', color: TspTm.color.text.primary, fontFamily: TspTm.font.family, outline: 'none', width: '200px' }} />
            <button style={{ marginLeft: 'auto', ...st.btnPrimary }}>+ Add Clause</button>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
            {filtClause.map(c => {
              const rb = riskBadge(c.risk);
              return (
                <div key={c.id} style={{ background: TspTm.color.bg.card, border: `1px solid ${TspTm.color.border.light}`, borderRadius: TspTm.radius.lg, padding: '14px 16px' }}>
                  <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px' }}>
                    <div style={{ flex: 1 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>
                        <span style={{ fontSize: '13px', fontWeight: 600, color: TspTm.color.text.primary }}>{c.title}</span>
                        <span style={{ ...st.tag, background: rb.bg, color: rb.color }}>{rb.label}</span>
                        <span style={{ ...st.tag, background: TspTm.color.bg.secondary, color: TspTm.color.text.tertiary }}>{c.practice}</span>
                        <span style={{ ...st.tag, background: TspTm.color.bg.secondary, color: TspTm.color.text.tertiary }}>{c.jurisdiction}</span>
                      </div>
                      <div style={{ fontSize: '11px', color: TspTm.color.text.secondary, lineHeight: 1.6, fontFamily: '"Georgia", serif', background: TspTm.color.bg.secondary, padding: '8px 10px', borderRadius: '4px', borderLeft: `3px solid ${TspTm.color.border.light}` }}>
                        {c.text.length > 200 ? c.text.slice(0, 200) + '...' : c.text}
                      </div>
                      <div style={{ fontSize: '10px', color: TspTm.color.text.tertiary, marginTop: '6px' }}>Used in {c.uses} documents</div>
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '5px', flexShrink: 0 }}>
                      <button style={{ ...st.btnPrimary, fontSize: '11px' }}>Insert →</button>
                      <button style={{ ...st.btnSecondary, fontSize: '11px' }}>Copy</button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* ── Merge fields wizard overlay ───────────────────────────── */}
      {wizard && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(10,22,40,0.5)', zIndex: 500, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ background: TspTm.color.bg.card, borderRadius: '12px', width: '520px', maxHeight: '80vh', overflow: 'auto', boxShadow: '0 24px 64px rgba(0,0,0,0.3)' }}>
            <div style={{ padding: '20px 24px', borderBottom: `1px solid ${TspTm.color.border.light}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: '16px', fontWeight: 700, color: TspTm.color.text.primary, marginBottom: '2px' }}>Use: {wizard.title}</div>
                <div style={{ fontSize: '12px', color: TspTm.color.text.tertiary }}>{wizard.fields.length} merge fields · Fill in to auto-populate the document</div>
              </div>
              <button onClick={() => setWizard(null)} style={{ ...st.btnGhost, color: TspTm.color.text.tertiary, fontSize: '18px', padding: '0 6px' }}><Icons.X size={11}/></button>
            </div>
            <div style={{ padding: '20px 24px' }}>
              {/* Matter quick-fill banner */}
              <div style={{ padding: '10px 14px', background: st.goldBg, borderRadius: '8px', border: `1px solid ${st.goldBorder}`, marginBottom: '16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div>
                  <div style={{ fontSize: '11px', fontWeight: 600, color: st.goldDeep }}>◆ Auto-fill from Matter</div>
                  <div style={{ fontSize: '11px', color: TspTm.color.text.secondary, marginTop: '1px' }}>Meridian Oil Corp v. Coastal Energy LLC (#4421)</div>
                </div>
                <button style={{ ...st.btnPrimary, fontSize: '11px' }}>Auto-fill →</button>
              </div>

              {wizard.fields.map((f, i) => (
                <div key={f.name} style={{ marginBottom: '14px' }}>
                  <label style={{ display: 'block', fontSize: '11px', fontWeight: 600, color: TspTm.color.text.secondary, marginBottom: '5px', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                    {`{{${f.name}}}`}
                  </label>
                  <input
                    defaultValue={f.example}
                    style={{ width: '100%', padding: '8px 12px', borderRadius: '6px', border: `1px solid ${TspTm.color.border.light}`, background: TspTm.color.bg.secondary, fontSize: '12px', color: TspTm.color.text.primary, fontFamily: TspTm.font.family, outline: 'none', boxSizing: 'border-box' }}
                    placeholder={`e.g. ${f.example}`}
                  />
                </div>
              ))}

              <div style={{ padding: '12px 14px', background: TspTm.color.bg.secondary, borderRadius: '6px', marginBottom: '16px' }}>
                <div style={{ fontSize: '11px', fontWeight: 600, color: TspTm.color.text.secondary, marginBottom: '5px' }}>Link to matter</div>
                <select style={{ width: '100%', padding: '7px 10px', borderRadius: '5px', border: `1px solid ${TspTm.color.border.light}`, background: TspTm.color.bg.card, fontSize: '12px', color: TspTm.color.text.primary, fontFamily: TspTm.font.family }}>
                  <option>Meridian Oil Corp v. Coastal Energy LLC (#4421)</option>
                  <option>TechNova vs. Quantum Systems</option>
                  <option>Hartwell Manufacturing</option>
                  <option>Blackwood Capital Partners</option>
                </select>
              </div>

              <div style={{ display: 'flex', gap: '8px' }}>
                <button onClick={() => setWizard(null)} style={{ ...st.btnSecondary, flex: 1 }}>Cancel</button>
                <button onClick={() => setWizard(null)} style={{ ...st.btnPrimary, flex: 2, fontSize: '13px' }}>Create Document →</button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.StudioTemplates = StudioTemplates;
