/* screen-creator-apply-form.jsx — Enhanced apply form on Brief Detail
   ─────────────────────────────────────────────────────────────────────
   States covered (from Apply Flow States.html):
     1. Tab switching: 1 TikTok / 2 TikTok / TikTok+IG / Custom — shape changes
     2. Reference picker modal (Library / Paste URL / Upload tabs)
     3. Submit → validating (spinner + check list)
     4. Submit success (confetti + recap + next milestones)
   Exported as ApplyForm — used inline by ScreenCreatorBriefDetail.
*/
/* global React, Pill, Icon, useRouter, Modal */

const DELIV_TABS = [
  { id: '1tt',   label: '1 TikTok 30s video',  typical: '$1.8K typical', total: 1800 },
  { id: '2tt',   label: '2 TikTok videos',     typical: '$3.2K typical', total: 3000 },
  { id: 'ttig',  label: 'TikTok + IG reel',    typical: '$2.4K typical', total: 2400 },
  { id: 'custom',label: 'Custom',              typical: 'build your own', total: 3200 },
];

const PRESET_ROWS = {
  '1tt':  [ { platform: 'TikTok', format: 'Video · vertical 9:16', length: '30 seconds', concept: 'Hero · honest before/after', due: 'May 22, 2026', price: 1800 } ],
  '2tt':  [
    { platform: 'TikTok', format: 'Video · vertical 9:16', length: '30 seconds', concept: 'Hero · honest before/after', due: 'May 22, 2026', price: 1800 },
    { platform: 'TikTok', format: 'Video · vertical 9:16', length: '15 seconds', concept: 'Follow-up · 7-day result',     due: 'Jun 04, 2026', price: 1200 },
  ],
  'ttig': [
    { platform: 'TikTok',    format: 'Video · vertical 9:16', length: '30 seconds', concept: 'TikTok hero',           due: 'May 22, 2026', price: 1800 },
    { platform: 'Instagram', format: 'Reel · 9:16',           length: '15 seconds', concept: 'IG cross-post',         due: 'May 24, 2026', price: 600 },
  ],
  'custom': [
    { platform: 'TikTok',    format: 'Video · 45s',          length: '45 seconds', concept: 'Skin diary 0–30 montage',    due: 'May 22, 2026', price: 2200 },
    { platform: 'Instagram', format: 'Story · 4 frames',     length: '—',          concept: 'Daily routine sticker series', due: 'May 25, 2026', price: 600 },
    { platform: 'YouTube',   format: 'Short · 60s',          length: '60 seconds', concept: 'Cross-post repurpose',         due: 'May 28, 2026', price: 400 },
  ],
};

const LIB_ITEMS = [
  { id: 'l1', plat: 'tt',  g: 'linear-gradient(135deg, #79FEE7, #009CFF)', views: '1.2M', er: '8.4%' },
  { id: 'l2', plat: 'tt',  g: 'linear-gradient(135deg, #FFC3D6, #FF6FA3)', views: '820K', er: '7.1%' },
  { id: 'l3', plat: 'tt',  g: 'linear-gradient(135deg, #FEE960, #FF7A59)', views: '540K', er: '6.2%' },
  { id: 'l4', plat: 'ig',  g: 'linear-gradient(135deg, #79FEE7, #1FD6B4)', views: '410K', er: '9.8%' },
  { id: 'l5', plat: 'tt',  g: 'linear-gradient(135deg, #EAC2FB, #C9A3E8)', views: '320K', er: '5.4%' },
  { id: 'l6', plat: 'tt',  g: 'linear-gradient(135deg, #FF7A59, #FF6FA3)', views: '280K', er: '6.8%' },
  { id: 'l7', plat: 'ig',  g: 'linear-gradient(135deg, #FEE960, #F2C411)', views: '210K', er: '4.9%' },
  { id: 'l8', plat: 'tt',  g: 'linear-gradient(135deg, #6464E8, #1C1CC9)', views: '180K', er: '5.1%' },
];

// ── Reference picker modal ─────────────────────────────────────────
function ReferencePickerModal({ open, onClose, picked, onConfirm }) {
  const [tab, setTab] = React.useState('library');
  const [filter, setFilter] = React.useState('all');
  const [selected, setSelected] = React.useState(picked.map(p => p.id));
  const [url, setUrl] = React.useState('');
  const [fetched, setFetched] = React.useState(false);

  React.useEffect(() => { if (open) { setSelected(picked.map(p => p.id)); setTab('library'); setUrl(''); setFetched(false); } }, [open]);

  const visible = LIB_ITEMS.filter(i => filter === 'all' || i.plat === filter);
  const toggle = (id) => setSelected(s => s.includes(id) ? s.filter(x => x !== id) : (s.length >= 5 ? s : [...s, id]));

  const confirmLibrary = () => {
    const items = LIB_ITEMS.filter(i => selected.includes(i.id));
    onConfirm(items);
  };

  return (
    <Modal open={open} onClose={onClose} width={680}
      title="Add a reference post"
      subtitle="Show DermaQ the kind of work you'll deliver · up to 5 references · they see views, ER and platform">

      <div className="row gap-4 mb-4" style={{ padding: 3, background: 'var(--bg-soft)', borderRadius: 999 }}>
        {[
          ['library', `From your library · 42`],
          ['url', 'Paste URL'],
          ['upload', 'Upload'],
        ].map(([k, l]) => (
          <button key={k} onClick={() => setTab(k)} style={{
            flex: 1, padding: '8px 12px', borderRadius: 999, border: 0, cursor: 'pointer', fontFamily: 'inherit',
            background: tab === k ? 'white' : 'transparent',
            color: tab === k ? 'var(--ink)' : 'var(--ink-soft)',
            fontWeight: 700, fontSize: 12,
            boxShadow: tab === k ? '0 1px 3px rgba(0,43,80,0.1)' : 'none'
          }}>{l}</button>
        ))}
      </div>

      {tab === 'library' && (
        <>
          <div className="row gap-6 mb-3" style={{ flexWrap: 'wrap', alignItems: 'center' }}>
            {[
              ['all', 'All 42'],
              ['tt', 'TikTok 28'],
              ['ig', 'Instagram 11'],
            ].map(([k, l]) => (
              <button key={k} onClick={() => setFilter(k)} style={{
                padding: '4px 11px', borderRadius: 999, border: 0, cursor: 'pointer', fontFamily: 'inherit',
                background: filter === k ? 'var(--ink)' : 'var(--bg-soft)',
                color: filter === k ? 'white' : 'var(--ink-soft)',
                fontWeight: 700, fontSize: 11
              }}>{l}</button>
            ))}
            <Pill variant="cyan">Skincare</Pill>
            <Pill variant="cyan">Before/after</Pill>
            <Pill variant="mint">★ Top performers</Pill>
            <span className="muted" style={{ marginLeft: 'auto', fontSize: 11 }}>Sort: <b style={{ color: 'var(--ink)' }}>Highest views ▾</b></span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, maxHeight: 360, overflowY: 'auto' }}>
            {visible.map((it) => {
              const isPicked = selected.includes(it.id);
              return (
                <button key={it.id} onClick={() => toggle(it.id)} style={{
                  position: 'relative', aspectRatio: '9/14', borderRadius: 12, overflow: 'hidden', border: 0, padding: 0, cursor: 'pointer',
                  background: it.g, outline: '3px solid ' + (isPicked ? 'var(--cyan)' : 'transparent'),
                  outlineOffset: isPicked ? -3 : 0, transition: 'outline-color .15s'
                }}>
                  <div style={{
                    position: 'absolute', top: 6, left: 6, background: 'rgba(255,255,255,0.92)',
                    color: 'var(--ink)', padding: '3px 6px', borderRadius: 5, fontSize: 10, fontWeight: 700
                  }}>{it.plat === 'tt' ? 'TT' : 'IG'}</div>
                  {isPicked && (
                    <div style={{
                      position: 'absolute', top: 6, right: 6, width: 22, height: 22, borderRadius: 999,
                      background: 'var(--cyan)', color: 'white', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 11
                    }}>✓</div>
                  )}
                  <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '8px 6px 6px',
                    background: 'linear-gradient(transparent, rgba(0,0,0,0.55))', color: 'white', fontSize: 10, fontWeight: 700 }}>
                    <div className="row items-center justify-between">
                      <span>{it.views}</span>
                      <span>{it.er} ER</span>
                    </div>
                  </div>
                </button>
              );
            })}
          </div>
          <div className="row items-center justify-between mt-4">
            <span className="muted" style={{ fontSize: 12 }}><b style={{ color: 'var(--ink)' }}>{selected.length} of 5</b> selected · DermaQ sees views & ER for each</span>
            <div className="row gap-8">
              <button onClick={onClose} className="btn btn-ghost btn-sm">Cancel</button>
              <button onClick={confirmLibrary} className="btn btn-primary btn-sm" disabled={selected.length === 0}
                style={{ opacity: selected.length === 0 ? 0.4 : 1 }}>
                Add {selected.length} reference{selected.length !== 1 ? 's' : ''}
              </button>
            </div>
          </div>
        </>
      )}

      {tab === 'url' && (
        <div>
          <div className="row gap-8 mb-4">
            <input className="input" placeholder="https://www.tiktok.com/@..." value={url} onChange={e => { setUrl(e.target.value); setFetched(false); }} style={{ flex: 1 }} />
            <button onClick={() => setFetched(!!url.trim())} disabled={!url.trim()} className="btn btn-primary btn-sm"
              style={{ opacity: url.trim() ? 1 : 0.4 }}>Fetch preview</button>
          </div>
          {fetched && (
            <div className="row items-center gap-12" style={{ padding: 14, background: 'var(--bg-soft)', borderRadius: 12, animation: 'cardIn .3s ease-out' }}>
              <div style={{
                width: 60, height: 84, borderRadius: 8, flexShrink: 0,
                background: 'linear-gradient(135deg, #79FEE7, #009CFF)',
                display: 'grid', placeItems: 'center', color: 'white', fontSize: 18
              }}>▶</div>
              <div className="flex-1">
                <div className="bold" style={{ fontSize: 13 }}>@linhmilk · "I tried 3 acne serums for 30 days"</div>
                <div className="muted" style={{ fontSize: 11 }}>TikTok · posted Apr 18, 2026</div>
                <div className="row gap-12 mt-2" style={{ fontSize: 11 }}>
                  <span><span className="cap-label" style={{ fontSize: 9 }}>Views</span> <b>1.4M</b></span>
                  <span><span className="cap-label" style={{ fontSize: 9 }}>Likes</span> <b>118K</b></span>
                  <span><span className="cap-label" style={{ fontSize: 9 }}>ER</span> <b>8.4%</b></span>
                </div>
              </div>
              <button className="btn btn-primary btn-sm" onClick={() => onConfirm([{ id: 'url-' + Date.now(), plat: 'tt', g: 'linear-gradient(135deg, #79FEE7, #009CFF)', views: '1.4M', er: '8.4%' }])}>Add</button>
            </div>
          )}
        </div>
      )}

      {tab === 'upload' && (
        <div style={{ padding: '40px 24px', textAlign: 'center', border: '2px dashed var(--line)', borderRadius: 12, background: 'var(--bg-soft)' }}>
          <div style={{ fontSize: 36 }}>📤</div>
          <div className="bold mt-2" style={{ fontSize: 14 }}>Drop a video file</div>
          <div className="muted" style={{ fontSize: 11.5 }}>MP4/MOV · max 200MB · or click to browse</div>
        </div>
      )}
    </Modal>
  );
}

// ── Deliverable rows table ─────────────────────────────────────────
function DeliverableRows({ rows, setRows, tabId }) {
  const updateRow = (i, k, v) => setRows(rs => rs.map((r, j) => j === i ? { ...r, [k]: v } : r));
  const removeRow = (i) => setRows(rs => rs.filter((_, j) => j !== i));
  const addRow = () => setRows(rs => [...rs, { platform: 'TikTok', format: 'Video · 30s', length: '30 seconds', concept: 'New angle', due: 'May 30, 2026', price: 800 }]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 10 }}>
      {rows.map((r, i) => (
        <div key={i} className="row items-end gap-10" style={{ padding: 12, background: 'var(--bg-soft)', borderRadius: 12 }}>
          <div style={{
            width: 26, height: 26, borderRadius: 999, background: 'var(--ink)', color: 'white',
            display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 11, flexShrink: 0, marginBottom: 2
          }}>{i + 1}</div>
          {tabId === 'custom' && (
            <div style={{ flex: '0 0 110px' }}>
              <div className="cap-label" style={{ fontSize: 9, marginBottom: 4 }}>Platform</div>
              <select className="input" value={r.platform} onChange={e => updateRow(i, 'platform', e.target.value)} style={{ padding: '7px 10px', fontSize: 12 }}>
                <option>TikTok</option><option>Instagram</option><option>YouTube</option>
              </select>
            </div>
          )}
          <div style={{ flex: '0 0 140px' }}>
            <div className="cap-label" style={{ fontSize: 9, marginBottom: 4 }}>Format · length</div>
            <input className="input" value={r.format} onChange={e => updateRow(i, 'format', e.target.value)} style={{ padding: '7px 10px', fontSize: 12 }} />
          </div>
          <div className="flex-1">
            <div className="cap-label" style={{ fontSize: 9, marginBottom: 4 }}>Concept</div>
            <input className="input" value={r.concept} onChange={e => updateRow(i, 'concept', e.target.value)} style={{ padding: '7px 10px', fontSize: 12 }} />
          </div>
          <div style={{ flex: '0 0 120px' }}>
            <div className="cap-label" style={{ fontSize: 9, marginBottom: 4 }}>{tabId === 'custom' ? 'Your price' : 'Delivers by'}</div>
            <input className="input"
              value={tabId === 'custom' ? '$' + r.price.toLocaleString() : r.due}
              onChange={e => updateRow(i, tabId === 'custom' ? 'price' : 'due', tabId === 'custom' ? parseInt(e.target.value.replace(/\D/g, '')) || 0 : e.target.value)}
              style={{ padding: '7px 10px', fontSize: 12 }} />
          </div>
          {rows.length > 1 && (
            <button onClick={() => removeRow(i)} style={{
              width: 30, height: 30, borderRadius: 8, background: 'white', border: '1px solid var(--line)',
              color: 'var(--pink-hot)', cursor: 'pointer', display: 'grid', placeItems: 'center', flexShrink: 0
            }}>🗑</button>
          )}
        </div>
      ))}
      {tabId === 'custom' && (
        <button onClick={addRow} style={{
          padding: '10px 0', borderRadius: 10, border: '2px dashed var(--line)', background: 'transparent',
          cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 12, color: 'var(--cyan-dark)'
        }}>{Icon.plus} Add another deliverable</button>
      )}
    </div>
  );
}

// ── Main ApplyForm component ───────────────────────────────────────
function ApplyForm({ onCancel }) {
  const { go } = useRouter();
  const [tab, setTab] = React.useState('1tt');
  const [rows, setRows] = React.useState(PRESET_ROWS['1tt']);
  const [pitch, setPitch] = React.useState("My audience is HCM 18–24F, 78% female, with strong before/after engagement on skincare. I've worked with 2 acne brands last quarter (DermaPlus, ClearSkin VN) and over-performed CPM by 24%. I can deliver a 30s TikTok by May 22.");
  const [refs, setRefs] = React.useState([
    { id: 'r1', plat: 'tt', g: 'linear-gradient(135deg, #79FEE7, #009CFF)', views: '1.2M', er: '8.4%' },
    { id: 'r2', plat: 'tt', g: 'linear-gradient(135deg, #FFC3D6, #FF6FA3)', views: '820K', er: '7.1%' },
  ]);
  const [pickerOpen, setPicker] = React.useState(false);
  const [submitState, setSubmit] = React.useState('idle'); // idle | validating | success
  const [validStep, setValidStep] = React.useState(0);

  // When tab changes, reset rows to preset
  const pickTab = (id) => { setTab(id); setRows(PRESET_ROWS[id]); };

  const total = rows.reduce((s, r) => s + (r.price || 0), 0);
  const BAND_MAX = 2400, BAND_MIN = 1200;
  const inBand = total >= BAND_MIN && total <= BAND_MAX;
  const overBand = total > BAND_MAX;

  // Submit flow: idle → validating (animate steps) → success
  const submit = () => {
    setSubmit('validating');
    setValidStep(0);
    let n = 0;
    const id = setInterval(() => {
      n++;
      setValidStep(n);
      if (n >= 3) { clearInterval(id); setTimeout(() => setSubmit('success'), 350); }
    }, 600);
  };

  if (submitState === 'success') {
    return (
      <div className="card-elevated mb-6" style={{ padding: 36, textAlign: 'center', position: 'relative', overflow: 'hidden' }}>
        {/* Confetti */}
        {[0, 1, 2, 3, 4, 5].map(i => (
          <div key={i} style={{
            position: 'absolute', top: 0, left: `${15 + i * 14}%`,
            width: 8, height: 8, borderRadius: 2,
            background: ['var(--cyan)', 'var(--mint-deep)', 'var(--pink-hot)', 'var(--yellow-deep)', 'var(--lavender-deep)', 'var(--coral)'][i],
            animation: `confettiDrop 1.8s ${i * 0.08}s cubic-bezier(.4,.2,.6,1) forwards`,
            opacity: 0
          }} />
        ))}
        <div style={{
          width: 80, height: 80, borderRadius: 999, background: 'var(--mint-deep)',
          display: 'grid', placeItems: 'center', margin: '0 auto 16px',
          color: 'white', fontSize: 40, animation: 'pop .5s cubic-bezier(.2,1.4,.5,1)'
        }}>✓</div>
        <h2 className="font-display" style={{ fontSize: 28, fontWeight: 700, margin: 0, letterSpacing: '-0.02em' }}>You're in DermaQ's queue</h2>
        <p style={{ margin: '8px 0 24px', fontSize: 13.5, color: 'var(--ink-soft)', lineHeight: 1.5, maxWidth: 480, marginLeft: 'auto', marginRight: 'auto' }}>
          Your application went out at <b style={{ color: 'var(--ink)' }}>3:42pm</b>. DermaQ usually responds within <b style={{ color: 'var(--ink)' }}>48 hours</b>. We'll ping you the moment they decide.
        </p>

        <div style={{
          maxWidth: 520, margin: '0 auto', padding: 18, background: 'var(--bg-soft)', borderRadius: 14, textAlign: 'left'
        }}>
          <div className="cap-label mb-3">Application snapshot</div>
          {[
            ['Brief', 'Acne care · awareness video'],
            ['Bundle', DELIV_TABS.find(d => d.id === tab).label],
            ['Your rate', '$' + total.toLocaleString() + ' USD'],
            ['References', refs.length + ' attached'],
            ['Match score', '92% · strong fit'],
          ].map(([k, v], i) => (
            <div key={i} className="row items-center" style={{ padding: '6px 0', borderTop: i ? '1px solid var(--line)' : 'none' }}>
              <span className="muted" style={{ fontSize: 12, width: 110 }}>{k}</span>
              <span className="bold" style={{ fontSize: 13, color: k === 'Match score' ? 'var(--mint-deep)' : 'var(--ink)' }}>{v}</span>
            </div>
          ))}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, maxWidth: 520, margin: '20px auto 0' }}>
          {[
            { l: 'Brand reviews', sub: 'Today → 48h', state: 'now' },
            { l: 'Shortlist call', sub: 'If picked, 15-min sync', state: 'todo' },
            { l: 'Contract', sub: 'Auto-drafted, e-sign', state: 'todo' },
          ].map((s, i) => (
            <div key={i} style={{
              padding: 12, borderRadius: 10, textAlign: 'left',
              background: s.state === 'now' ? 'rgba(0,156,255,0.06)' : 'var(--bg-soft)',
              border: '1px solid ' + (s.state === 'now' ? 'rgba(0,156,255,0.25)' : 'transparent')
            }}>
              <div className="row items-center gap-6 mb-1">
                <div style={{
                  width: 18, height: 18, borderRadius: 999,
                  background: s.state === 'now' ? 'var(--ink)' : 'var(--line)',
                  color: 'white', display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 800
                }}>{i + 1}</div>
                <span className="bold" style={{ fontSize: 12 }}>{s.l}</span>
              </div>
              <div className="muted" style={{ fontSize: 10.5 }}>{s.sub}</div>
            </div>
          ))}
        </div>

        <div className="row justify-center gap-8 mt-6">
          <button className="btn btn-ghost btn-sm" onClick={() => go('creator-discover')}>Browse more briefs</button>
          <button className="btn btn-primary btn-sm" onClick={() => { window.__appStatus = 'pending'; go('creator-application-detail'); }}>
            View my applications {Icon.arrow}
          </button>
        </div>
        <style>{`
          @keyframes confettiDrop { 0% { transform: translateY(-20px) rotate(0); opacity: 1; } 100% { transform: translateY(280px) rotate(720deg); opacity: 0; } }
          @keyframes pop { 0% { transform: scale(0); } 60% { transform: scale(1.1); } 100% { transform: scale(1); } }
        `}</style>
      </div>
    );
  }

  return (
    <div className="card-elevated mb-6" style={{ padding: 28, position: 'relative', animation: 'slideDown .35s ease-out' }}>
      {submitState === 'validating' && (
        <div style={{
          position: 'absolute', inset: 0, background: 'rgba(255,255,255,0.85)', backdropFilter: 'blur(4px)',
          borderRadius: 18, zIndex: 5, display: 'grid', placeItems: 'center', animation: 'cardIn .25s ease-out'
        }}>
          <div className="card-elevated" style={{ padding: 28, maxWidth: 420, width: '100%', textAlign: 'center', boxShadow: '0 24px 60px rgba(0,43,80,0.18)' }}>
            <div style={{
              width: 64, height: 64, borderRadius: 999, margin: '0 auto 14px',
              background: 'linear-gradient(135deg, #79FEE7, #009CFF)',
              display: 'grid', placeItems: 'center', color: 'white',
              fontFamily: 'Space Grotesk', fontWeight: 800, fontSize: 18,
              animation: 'spin 1.4s linear infinite, pulseGlow 1.4s ease-in-out infinite'
            }}>AI</div>
            <div className="font-display bold" style={{ fontSize: 18, letterSpacing: '-0.015em' }}>Submitting your application…</div>
            <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>Running final checks · usually 1–2 seconds.</div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 20, textAlign: 'left' }}>
              {[
                'Pitch validated · ' + pitch.trim().split(/\s+/).length + ' words',
                refs.length + ' references attached · ' + (refs.length ? '2.0M combined views' : 'none'),
                'Re-computing match score with your bundle…',
                'Notify DermaQ',
              ].map((l, i) => (
                <div key={i} className="row items-center gap-10" style={{ fontSize: 12.5 }}>
                  <span style={{
                    width: 22, height: 22, borderRadius: 999,
                    background: i < validStep ? 'var(--mint-deep)' : i === validStep ? 'var(--cyan)' : 'var(--bg-soft)',
                    color: 'white', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 11,
                    animation: i === validStep ? 'pulse 1s infinite' : 'none'
                  }}>{i < validStep ? '✓' : ''}</span>
                  <span style={{ color: i <= validStep ? 'var(--ink)' : 'var(--ink-soft)', fontWeight: i === validStep ? 700 : 600 }}>{l}</span>
                </div>
              ))}
            </div>
          </div>
          <style>{`@keyframes spin { to { transform: rotate(360deg); } } @keyframes pulseGlow { 0%, 100% { box-shadow: 0 0 0 0 rgba(0,156,255,0.4); } 50% { box-shadow: 0 0 0 16px rgba(0,156,255,0); } }`}</style>
        </div>
      )}

      <div className="title-md mb-2">Tell DermaQ why you're a fit</div>
      <div className="muted mb-4" style={{ fontSize: 13 }}>Your media kit + 100-word pitch · brand sees AI match score, ER, audience demographics automatically.</div>

      <label className="label">Proposed deliverable</label>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginTop: 6 }}>
        {DELIV_TABS.map(d => {
          const active = tab === d.id;
          return (
            <button key={d.id} onClick={() => pickTab(d.id)} style={{
              padding: 12, borderRadius: 12,
              border: '2px solid ' + (active ? 'var(--cyan)' : 'var(--line)'),
              background: active ? 'rgba(0,156,255,0.06)' : 'white',
              color: active ? 'var(--cyan-dark)' : 'var(--ink)',
              fontFamily: 'inherit', cursor: 'pointer', textAlign: 'center'
            }}>
              <div className="bold" style={{ fontSize: 12 }}>{d.label}</div>
              <div style={{ fontSize: 10, marginTop: 3, opacity: 0.8, fontWeight: 600 }}>{d.typical}</div>
            </button>
          );
        })}
      </div>

      {tab !== '1tt' && (
        <div className="muted mt-3" style={{ fontSize: 12, padding: '8px 12px', background: 'var(--bg-soft)', borderRadius: 8 }}>
          {tab === '2tt'    && <>Brand asked for a hero post + a follow-up. Split below into two assets.</>}
          {tab === 'ttig'   && <>Cross-platform bundle · TikTok hero with IG cross-post in 9:16.</>}
          {tab === 'custom' && <><b>Brand expects:</b> 1 TikTok + 1 follow-up. Going outside that lowers your fit score — explain in pitch.</>}
        </div>
      )}

      <DeliverableRows rows={rows} setRows={setRows} tabId={tab} />

      {/* Subtotal */}
      <div className="row items-center justify-between mt-4" style={{
        padding: 14, borderRadius: 12,
        background: overBand ? 'rgba(254,233,96,0.25)' : 'rgba(31,214,180,0.10)',
        border: '1px solid ' + (overBand ? 'rgba(242,196,17,0.4)' : 'rgba(31,214,180,0.3)')
      }}>
        <div>
          <div className="font-display bold" style={{ fontSize: 13 }}>{rows.length} deliverable{rows.length > 1 ? 's' : ''}</div>
          <div className="muted" style={{ fontSize: 11.5, marginTop: 2 }}>
            {rows.map(r => '$' + r.price.toLocaleString()).join(' + ')} = <b style={{ color: 'var(--ink)' }}>${total.toLocaleString()}</b>
            {overBand && <span style={{ color: '#856200', fontWeight: 700, marginLeft: 6 }}>· ${(total - BAND_MAX).toLocaleString()} above brand cap. Add rationale in pitch.</span>}
            {inBand && <span style={{ color: 'var(--mint-deep)', fontWeight: 700, marginLeft: 6 }}>· within brand band ✓</span>}
          </div>
        </div>
        <div className="text-right">
          <div className="font-display tabular bold" style={{ fontSize: 26 }}>${total.toLocaleString()}</div>
          <Pill variant={overBand ? 'yellow' : 'mint'}>{overBand ? '⚠ Above band' : '✓ In band'}</Pill>
        </div>
      </div>

      <label className="label mt-6" style={{ marginTop: 22 }}>Your pitch (max 100 words)</label>
      <textarea className="input" rows="4" value={pitch} onChange={e => setPitch(e.target.value)} style={{ resize: 'vertical', fontFamily: 'inherit' }} />
      <div className="muted mt-1" style={{ fontSize: 11 }}>{pitch.trim().split(/\s+/).length} / 100 words</div>

      <label className="label mt-4" style={{ marginTop: 18 }}>Reference posts (optional · max 5)</label>
      <div className="row gap-8" style={{ flexWrap: 'wrap' }}>
        {refs.map((r, i) => (
          <div key={r.id} style={{
            position: 'relative', width: 76, height: 100, borderRadius: 10, overflow: 'hidden', background: r.g
          }}>
            <div style={{ position: 'absolute', bottom: 4, left: 4, right: 4, color: 'white', fontSize: 9, fontWeight: 800, textShadow: '0 1px 3px rgba(0,0,0,0.3)' }}>
              {r.views} · {r.er}
            </div>
            <button onClick={() => setRefs(rs => rs.filter(x => x.id !== r.id))} style={{
              position: 'absolute', top: 4, right: 4, width: 18, height: 18, borderRadius: 999, border: 0,
              background: 'rgba(0,0,0,0.5)', color: 'white', cursor: 'pointer', fontSize: 10, fontWeight: 800
            }}>×</button>
          </div>
        ))}
        {refs.length < 5 && (
          <button onClick={() => setPicker(true)} style={{
            width: 76, height: 100, borderRadius: 10, background: 'var(--bg-soft)',
            border: '2px dashed var(--line)', cursor: 'pointer', color: 'var(--ink-soft)', fontSize: 24, fontWeight: 800
          }}>+</button>
        )}
      </div>

      <div className="row gap-8 mt-6 justify-end">
        <button className="btn btn-ghost btn-sm" onClick={onCancel}>Cancel</button>
        <button className="btn btn-primary" onClick={submit}>{Icon.spark} Submit application</button>
      </div>

      <ReferencePickerModal open={pickerOpen} onClose={() => setPicker(false)} picked={refs}
        onConfirm={(items) => { setRefs(prev => {
          // merge by id, dedupe
          const ids = new Set(prev.map(p => p.id));
          return [...prev, ...items.filter(i => !ids.has(i.id))].slice(0, 5);
        }); setPicker(false); }} />

      <style>{`@keyframes slideDown { from { opacity: 0; transform: translateY(-8px); } to { opacity: 1; transform: translateY(0); } }`}</style>
    </div>
  );
}

Object.assign(window, { ApplyForm });
