// Assets + Library pages for the outcome-based demo.
// Same page chrome as the Studies list: title, meta line, pill filters,
// search on the right, one white card holding the content.
const { useState: useStateAL } = React;

const alShell = { flex: 1, minHeight: 0, overflowY: 'auto', background: '#f6fafd' };
const alInner = { maxWidth: 1200, margin: '0 auto', padding: '32px 32px 48px', fontFamily: "'PP Telegraf', sans-serif" };
const alH1 = { fontFamily: "'PP Telegraf'", fontSize: 28, fontWeight: 700, margin: '6px 0 4px', letterSpacing: '-0.01em' };
const alMeta = { fontSize: 13, color: '#636c79' };
const alCard = { background: '#fff', border: '1px solid #e5ebf1', borderRadius: 12, fontFamily: "'PP Telegraf', sans-serif" };

function ALPills({ options, value, onChange, counts }) {
  return (
    <div style={{ display: 'flex', gap: 4, background: '#fff', border: '1px solid #e5ebf1', padding: 3, borderRadius: 900 }}>
      {options.map(f => {
        const active = value === f;
        return (
          <button key={f} onClick={() => onChange(f)} style={{
            padding: '6px 14px', borderRadius: 900, fontSize: 12, fontWeight: 600, cursor: 'pointer', border: 'none',
            background: active ? '#050301' : 'transparent', color: active ? '#fff' : '#050301', fontFamily: 'inherit',
            display: 'inline-flex', alignItems: 'center', gap: 6
          }}>
            {f}
            {counts && <span style={{ fontSize: 10, fontWeight: 600, color: active ? '#cdd4dc' : '#636c79' }}>{counts[f] ?? 0}</span>}
          </button>
        );
      })}
    </div>
  );
}

function ALSearch({ value, onChange, placeholder }) {
  return (
    <div style={{ position: 'relative', marginLeft: 'auto', width: 260 }}>
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#636c79" strokeWidth="2" strokeLinecap="round" style={{ position: 'absolute', left: 12, top: 12 }}><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
      <input value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder} style={{ width: '100%', height: 38, padding: '0 12px 0 32px', borderRadius: 900, border: '1px solid #e5ebf1', fontSize: 13, fontFamily: 'inherit', boxSizing: 'border-box', background: '#fff' }}/>
    </div>
  );
}

function AssetsPage({ onNewStudy }) {
  const [uploads, setUploads] = useStateAL([]);
  const [drag, setDrag] = useStateAL(false);
  const inputRef = React.useRef(null);
  const all = [...uploads, ...(window.DEMO_ASSETS || [])];
  const [collection, setCollection] = useStateAL('All');
  const [query, setQuery] = useStateAL('');
  const [selected, setSelected] = useStateAL([]);
  const collections = ['All', ...Array.from(new Set(all.map(a => a.collection)))];
  const counts = { All: all.length };
  collections.slice(1).forEach(c => counts[c] = all.filter(a => a.collection === c).length);
  const filtered = all.filter(a => (collection === 'All' || a.collection === collection) && (!query || a.name.toLowerCase().includes(query.toLowerCase())));
  const toggle = (id) => setSelected(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  function addFiles(fileList) {
    const files = Array.from(fileList || []).filter(f => f.type.startsWith('image/'));
    if (!files.length) return;
    const items = files.map((f, i) => ({
      id: 'up-' + Date.now() + '-' + i,
      name: f.name.replace(/\.[a-z0-9]+$/i, '').replace(/[_-]+/g, ' '),
      img: URL.createObjectURL(f),
      collection: 'Uploaded'
    }));
    setUploads(prev => [...items, ...prev]);
    setCollection('Uploaded');
  }

  return (
    <div style={alShell} data-screen-label="Assets">
      <div style={alInner}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 24 }}>
          <div>
            <h1 style={alH1}>Assets</h1>
            <div style={alMeta}>{filtered.length} of {all.length} product assets · {collections.length - 1} collections · synced from PLM</div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <input ref={inputRef} type="file" accept="image/*" multiple style={{ display: 'none' }} onChange={e => { addFiles(e.target.files); e.target.value = ''; }}/>
            <window.Button variant="subtle" size="md" onClick={() => inputRef.current && inputRef.current.click()} icon={<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>}>Upload assets</window.Button>
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
          <ALPills options={collections} value={collection} onChange={setCollection} counts={counts}/>
          <ALSearch value={query} onChange={setQuery} placeholder="Search assets…"/>
        </div>

        {selected.length > 0 && (
          <div style={{ ...alCard, padding: '12px 16px', marginBottom: 12, display: 'flex', alignItems: 'center', gap: 12, borderColor: '#c8e2ba', background: '#f1f8ec' }}>
            <span style={{ fontSize: 13, fontWeight: 600 }}>{selected.length} asset{selected.length === 1 ? '' : 's'} selected</span>
            <span style={{ fontSize: 12, color: '#636c79' }}>Attach them to a new study and the intake reads them for category, price band and imagery.</span>
            <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
              <button onClick={() => setSelected([])} style={{ border: 'none', background: 'transparent', color: '#636c79', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>Clear</button>
              <window.Button variant="solid" size="sm" onClick={onNewStudy}>Start a study with these</window.Button>
            </div>
          </div>
        )}

        <div
          onDragOver={e => { e.preventDefault(); if (!drag) setDrag(true); }}
          onDragLeave={e => { if (e.currentTarget === e.target) setDrag(false); }}
          onDrop={e => { e.preventDefault(); setDrag(false); addFiles(e.dataTransfer.files); }}
          style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 12, borderRadius: 12, outline: drag ? '2px dashed #3a8518' : 'none', outlineOffset: 4, background: drag ? '#f3f9ef' : 'transparent' }}>
          {filtered.map(a => {
            const on = selected.includes(a.id);
            return (
              <button key={a.id} onClick={() => toggle(a.id)} style={{
                ...alCard, padding: 0, textAlign: 'left', cursor: 'pointer', overflow: 'hidden',
                borderColor: on ? '#3a8518' : '#e5ebf1', boxShadow: on ? '0 0 0 2px #daebd1' : 'none',
                display: 'flex', flexDirection: 'column'
              }}>
                <div style={{ position: 'relative', aspectRatio: '1 / 1', background: '#fafcfe', borderBottom: '1px solid #e5ebf1' }}>
                  <img src={a.img} alt={a.name} loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'contain', display: 'block' }}/>
                  <span style={{
                    position: 'absolute', top: 8, right: 8, width: 18, height: 18, borderRadius: 4,
                    border: on ? '1px solid #3a8518' : '1px solid #ced6de', background: on ? '#3a8518' : 'rgba(255,255,255,0.92)',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center'
                  }}>
                    {on && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3.4" strokeLinecap="round"><polyline points="20 6 9 17 4 12"/></svg>}
                  </span>
                </div>
                <div style={{ padding: '10px 12px 12px' }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: '#050301', marginBottom: 3 }}>{a.name}</div>
                  <div style={{ fontSize: 11, color: '#636c79' }}>{a.price ? a.price + ' · ' : ''}{a.collection}</div>
                </div>
              </button>
            );
          })}
        </div>
        {filtered.length === 0 && (
          <div style={{ ...alCard, padding: 36, textAlign: 'center', color: '#636c79' }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: '#050301', marginBottom: 4 }}>No assets match this search</div>
            <div style={{ fontSize: 12 }}>Try another collection or clear the search.</div>
          </div>
        )}
      </div>
    </div>
  );
}

function LibraryPage() {
  const cas = window.CONSUMER_ATTRIBUTES || [];
  const [type, setType] = useStateAL('All');
  const [query, setQuery] = useStateAL('');
  const types = ['All', 'Numeric', 'Categorical', 'Boolean'];
  const counts = { All: cas.length };
  types.slice(1).forEach(t => counts[t] = cas.filter(c => c.type === t.toLowerCase()).length);
  const filtered = cas.filter(c => (type === 'All' || c.type === type.toLowerCase()) && (!query || c.name.toLowerCase().includes(query.toLowerCase())));
  const tagged = cas.reduce((s, c) => s + (c.respondentsTagged || 0), 0);
  const cols = '1fr 120px 110px 130px';

  return (
    <div style={alShell} data-screen-label="Library">
      <div style={alInner}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 24 }}>
          <div>
            <h1 style={alH1}>Library</h1>
            <div style={alMeta}>{filtered.length} of {cas.length} consumer attributes · {tagged.toLocaleString()} respondent tags across the account</div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <window.Button variant="subtle" size="md" icon={<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>}>New attribute</window.Button>
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
          <ALPills options={types} value={type} onChange={setType} counts={counts}/>
          <ALSearch value={query} onChange={setQuery} placeholder="Search attributes…"/>
        </div>

        <div style={alCard}>
          <div style={{ display: 'grid', gridTemplateColumns: cols, padding: '12px 20px', background: '#fafcfe', borderBottom: '1px solid #e5ebf1', fontSize: 11, fontWeight: 700, color: '#636c79', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
            <span>Attribute</span>
            <span>Type</span>
            <span style={{ textAlign: 'right' }}>Studies</span>
            <span style={{ textAlign: 'right' }}>Respondents</span>
          </div>
          {filtered.map((c, i) => (
            <div key={c.id} style={{ display: 'grid', gridTemplateColumns: cols, padding: '14px 20px', borderBottom: i === filtered.length - 1 ? 'none' : '1px solid #e5ebf1', alignItems: 'center' }}>
              <div style={{ minWidth: 0, paddingRight: 16 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: '#050301', marginBottom: 2 }}>{c.name}</div>
                <div style={{ fontSize: 12, color: '#636c79', marginBottom: 6 }}>{c.description}</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                  {(c.values || []).slice(0, 5).map(v => (
                    <span key={v.id} style={{ padding: '2px 8px', borderRadius: 900, fontSize: 11, fontWeight: 600, border: '1px solid #e5ebf1', background: '#fff', color: '#636c79' }}>{v.label}</span>
                  ))}
                  {(c.values || []).length > 5 && (
                    <span style={{ padding: '2px 8px', borderRadius: 900, fontSize: 11, fontWeight: 600, border: '1px solid #e5ebf1', background: '#fafcfe', color: '#636c79' }}>+{c.values.length - 5} more</span>
                  )}
                </div>
              </div>
              <div><window.Badge tone="neutral">{c.type}</window.Badge></div>
              <div style={{ fontSize: 13, color: '#050301', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{c.usedInStudies ?? '—'}</div>
              <div style={{ fontSize: 13, color: '#050301', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{(c.respondentsTagged || 0).toLocaleString()}</div>
            </div>
          ))}
          {filtered.length === 0 && (
            <div style={{ padding: 36, textAlign: 'center', color: '#636c79' }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: '#050301', marginBottom: 4 }}>No attributes match this search</div>
              <div style={{ fontSize: 12 }}>Try another type or clear the search.</div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function FavoritesPage({ onPick }) {
  const favs = window.INTAKE_FAVORITES || [];
  return (
    <div style={alShell} data-screen-label="Favorites">
      <div style={alInner}>
        <div style={{ marginBottom: 24 }}>
          <h1 style={alH1}>Favorites</h1>
          <div style={alMeta}>{favs.length} saved study setups · start a new study from any of them</div>
        </div>
        <div style={{ display: 'grid', gap: 10 }}>
          {favs.map((f, i) => (
            <button key={f.id || i} onClick={() => onPick && onPick(f)} style={{ ...alCard, padding: '16px 18px', textAlign: 'left', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 14 }}>
              <span style={{ color: '#e0a422', fontSize: 15 }}>★</span>
              <span style={{ minWidth: 0 }}>
                <span style={{ display: 'block', fontSize: 14, fontWeight: 600, marginBottom: 3 }}>{f.title || f.name}</span>
                <span style={{ display: 'block', fontSize: 12, color: '#636c79' }}>{f.meta || f.summary || ''}</span>
              </span>
            </button>
          ))}
          {favs.length === 0 && (
            <div style={{ ...alCard, padding: 36, textAlign: 'center', color: '#636c79', fontSize: 13 }}>No saved setups yet.</div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AssetsPage, LibraryPage, FavoritesPage });
