// Command palette + Quick add modal

function CommandPalette({ open, onClose, onAction }) {
  const [q, setQ] = React.useState('');
  const [active, setActive] = React.useState(0);

  React.useEffect(() => {
    if (!open) { setQ(''); setActive(0); }
  }, [open]);

  if (!open) return null;

  const isUrl = q.startsWith('http://') || q.startsWith('https://');

  const actions = [
    { id: 'add', icon: I.Plus, label: 'Add bookmark', meta: '⌘N', onSelect: () => onAction('add') },
    { id: 'newcol', icon: I.Folder, label: 'New collection', meta: '', onSelect: () => onAction('newcol') },
    { id: 'bulk', icon: I.Upload, label: 'Bulk import', meta: '', onSelect: () => onAction('bulk') },
    { id: 'map', icon: I.Map, label: 'Open knowledge map', meta: 'G then M', onSelect: () => onAction('map') },
    { id: 'theme', icon: I.Moon, label: 'Toggle theme', meta: '⌘⇧L', onSelect: () => onAction('theme') },
  ];

  const filteredBookmarks = SAMPLE.bookmarks.filter(b =>
    !q || b.title.toLowerCase().includes(q.toLowerCase()) || b.tags.some(t => t.includes(q.toLowerCase()))
  ).slice(0, 5);

  const filteredCols = SAMPLE.collections.filter(c => !q || c.name.toLowerCase().includes(q.toLowerCase())).slice(0, 4);

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="cmdk" onClick={(e) => e.stopPropagation()}>
        <div className="cmdk-input-row">
          {isUrl ? <I.Link className="icon" /> : <I.Search className="icon" />}
          <input
            autoFocus
            placeholder="Type a URL to add, or search bookmarks, collections, commands…"
            value={q}
            onChange={(e) => setQ(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Escape') onClose(); }}
          />
          <span className="kbd">esc</span>
        </div>
        <div className="cmdk-list">
          {isUrl && (
            <>
              <div className="cmdk-section-label">Add bookmark</div>
              <div className="cmdk-item active">
                <I.Plus className="icon icon-sm" />
                <span className="cmdk-item-label">Add <span className="mono" style={{color:'var(--blue)', fontWeight:600}}>{q.length > 50 ? q.slice(0, 50) + '…' : q}</span></span>
                <span className="cmdk-item-meta"><I.Sparkle className="icon icon-xs" style={{display:'inline'}} /> AI extract</span>
              </div>
            </>
          )}

          {!isUrl && filteredBookmarks.length > 0 && (
            <>
              <div className="cmdk-section-label">Bookmarks</div>
              {filteredBookmarks.map((b, i) => (
                <div key={b.id} className={`cmdk-item ${active === i ? 'active' : ''}`} onMouseEnter={() => setActive(i)}>
                  <div className="b-thumb" style={{background: b.thumbColor + '22', color: b.thumbColor, width:20, height:20, fontSize:9, borderRadius:5}}>{b.thumb}</div>
                  <span className="cmdk-item-label" style={{whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{b.title}</span>
                  <span className="cmdk-item-meta">{b.domain}</span>
                </div>
              ))}
            </>
          )}

          {!isUrl && filteredCols.length > 0 && (
            <>
              <div className="cmdk-section-label">Collections</div>
              {filteredCols.map(c => (
                <div key={c.id} className="cmdk-item">
                  <span className="dot" style={{background: c.color, width:10, height:10, borderRadius:3}}></span>
                  <span className="cmdk-item-label">{c.name}</span>
                  <span className="cmdk-item-meta">{c.count}</span>
                </div>
              ))}
            </>
          )}

          {!isUrl && (
            <>
              <div className="cmdk-section-label">Actions</div>
              {actions.map(a => {
                const Icon = a.icon;
                return (
                  <div key={a.id} className="cmdk-item" onClick={() => { a.onSelect(); onClose(); }}>
                    <Icon className="icon icon-sm" />
                    <span className="cmdk-item-label">{a.label}</span>
                    {a.meta && <span className="cmdk-item-meta">{a.meta}</span>}
                  </div>
                );
              })}
            </>
          )}
        </div>
        <div className="cmdk-footer">
          <div className="hints">
            <span className="hint"><span className="kbd">↵</span> Open</span>
            <span className="hint"><span className="kbd">↑↓</span> Navigate</span>
            <span className="hint"><I.Sparkle className="icon icon-xs" style={{color:'var(--blue)'}} /> AI suggestions</span>
          </div>
          <span style={{display:'inline-flex', alignItems:'center', gap:4}}>Powered by <I.AI className="icon icon-xs" style={{color:'var(--blue)'}} /> Claude</span>
        </div>
      </div>
    </div>
  );
}

function QuickAddModal({ open, onClose }) {
  const [url, setUrl] = React.useState('');
  const [extracting, setExtracting] = React.useState(false);
  const [done, setDone] = React.useState(false);

  React.useEffect(() => {
    if (!open) { setUrl(''); setExtracting(false); setDone(false); }
  }, [open]);

  if (!open) return null;

  const submit = () => {
    setExtracting(true);
    setTimeout(() => { setExtracting(false); setDone(true); }, 1400);
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div style={{padding:'14px 18px', borderBottom:'0.5px solid var(--border-sub)', display:'flex', alignItems:'center', justifyContent:'space-between'}}>
          <div style={{fontSize:13, fontWeight:600, display:'flex', alignItems:'center', gap:8}}>
            <I.Plus className="icon icon-sm" /> Add bookmark
          </div>
          <button className="btn-icon" onClick={onClose}><I.Close className="icon icon-sm" /></button>
        </div>

        <div style={{padding:18}}>
          <input
            autoFocus
            className="input"
            placeholder="Paste a URL — Trove will fetch the rest"
            style={{height:44, fontSize:14}}
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter' && url) submit(); }}
          />

          {extracting && (
            <div style={{marginTop:18, padding:14, background:'var(--surface-2)', borderRadius:10, display:'flex', alignItems:'center', gap:10, fontSize:12, color:'var(--text-2)'}}>
              <div style={{width:18, height:18, border:'2px solid var(--surface-4)', borderTopColor:'var(--blue)', borderRadius:'50%', animation:'spin 0.8s linear infinite'}}></div>
              <div style={{flex:1}}>
                <div style={{fontWeight:600, color:'var(--text-1)'}}>Fetching & extracting…</div>
                <div style={{color:'var(--text-4)', fontSize:11, marginTop:2}}>Reading the page · summarizing with AI · suggesting collection</div>
              </div>
            </div>
          )}

          {done && (
            <div className="fade-up" style={{marginTop:18}}>
              <div style={{padding:14, background:'var(--surface-2)', borderRadius:10}}>
                <div style={{display:'flex', gap:12, marginBottom:10}}>
                  <div className="b-thumb" style={{background:'#FCD34D22', color:'#FCD34D', width:48, height:48}}>LS</div>
                  <div style={{flex:1, minWidth:0}}>
                    <div style={{fontSize:14, fontWeight:600, color:'var(--text-1)', letterSpacing:'-0.01em'}}>On the diminishing returns of larger LLMs</div>
                    <div style={{fontSize:11, color:'var(--text-4)', marginTop:2}}>latent.space</div>
                  </div>
                </div>
                <div style={{fontSize:12, color:'var(--text-3)', lineHeight:1.5}}>
                  After GPT-5 and Claude 4.5, raw scaling yields less than data quality and reasoning training. A field-wide reckoning.
                </div>
              </div>

              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginTop:14}}>
                <div>
                  <div style={{fontSize:10, fontWeight:700, color:'var(--text-4)', letterSpacing:'0.08em', textTransform:'uppercase', marginBottom:6}}>Suggested collection</div>
                  <button className="btn btn-ghost" style={{width:'100%', justifyContent:'flex-start'}}>
                    <span className="dot" style={{background:'#2563EB', width:8, height:8, borderRadius:2}}></span>
                    AI &amp; ML
                    <span style={{marginLeft:'auto', color:'var(--text-4)', fontSize:11, fontWeight:500}}>change</span>
                  </button>
                </div>
                <div>
                  <div style={{fontSize:10, fontWeight:700, color:'var(--text-4)', letterSpacing:'0.08em', textTransform:'uppercase', marginBottom:6}}>Suggested tags</div>
                  <div style={{display:'flex', flexWrap:'wrap', gap:4}}>
                    <span className="tag">#scaling-laws</span>
                    <span className="tag">#llm</span>
                    <span className="tag">#research</span>
                  </div>
                </div>
              </div>
            </div>
          )}

          {!extracting && !done && (
            <div style={{marginTop:14, fontSize:11, color:'var(--text-4)', display:'flex', alignItems:'center', gap:6}}>
              <I.Sparkle className="icon icon-xs" style={{color:'var(--blue)'}} />
              Trove will extract title, description, tags, and suggest a collection automatically.
            </div>
          )}
        </div>

        <div style={{padding:14, borderTop:'0.5px solid var(--border-sub)', display:'flex', justifyContent:'space-between', alignItems:'center'}}>
          <span style={{fontSize:11, color:'var(--text-4)'}}>
            <span className="kbd">⌘</span> <span className="kbd">↵</span> to save
          </span>
          {done
            ? <button className="btn btn-primary btn-sm" onClick={onClose}>Save to library <I.ArrowRight className="icon icon-xs" /></button>
            : <button className="btn btn-primary btn-sm" disabled={!url} onClick={submit} style={{opacity: url ? 1 : 0.5}}>{extracting ? 'Working…' : 'Continue'}</button>
          }
        </div>
      </div>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}

window.CommandPalette = CommandPalette;
window.QuickAddModal = QuickAddModal;

const GATE_FORM_HTML = `<form action="https://app.kit.com/forms/9409216/subscriptions" class="seva-form formkit-form" method="post" data-sv-form="9409216" data-uid="b920902896" data-format="inline" data-version="5" data-options="{&quot;settings&quot;:{&quot;after_subscribe&quot;:{&quot;action&quot;:&quot;message&quot;,&quot;success_message&quot;:&quot;Excited to show you what we&#x27;re building. Head over to your email inbox to confirm your email and you&#x27;ll be added to the list!&quot;,&quot;redirect_url&quot;:&quot;&quot;},&quot;analytics&quot;:{&quot;google&quot;:null,&quot;fathom&quot;:null,&quot;facebook&quot;:null,&quot;segment&quot;:null,&quot;pinterest&quot;:null,&quot;sparkloop&quot;:null,&quot;googletagmanager&quot;:null},&quot;modal&quot;:{&quot;trigger&quot;:&quot;timer&quot;,&quot;scroll_percentage&quot;:null,&quot;timer&quot;:5,&quot;devices&quot;:&quot;all&quot;,&quot;show_once_every&quot;:15},&quot;powered_by&quot;:{&quot;show&quot;:false,&quot;url&quot;:&quot;https://kit.com/features/forms?utm_campaign=poweredby&amp;utm_content=form&amp;utm_medium=referral&amp;utm_source=dynamic&quot;},&quot;recaptcha&quot;:{&quot;enabled&quot;:true},&quot;return_visitor&quot;:{&quot;action&quot;:&quot;show&quot;,&quot;custom_content&quot;:&quot;&quot;},&quot;slide_in&quot;:{&quot;display_in&quot;:&quot;bottom_right&quot;,&quot;trigger&quot;:&quot;timer&quot;,&quot;scroll_percentage&quot;:null,&quot;timer&quot;:5,&quot;devices&quot;:&quot;all&quot;,&quot;show_once_every&quot;:15},&quot;sticky_bar&quot;:{&quot;display_in&quot;:&quot;top&quot;,&quot;trigger&quot;:&quot;timer&quot;,&quot;scroll_percentage&quot;:null,&quot;timer&quot;:5,&quot;devices&quot;:&quot;all&quot;,&quot;show_once_every&quot;:15}},&quot;version&quot;:&quot;5&quot;}" min-width="400 500 600 700 800" style="background-color: #ffffff; border-radius: 0;"><div class="formkit-background" style="opacity: 0.2;"></div><div data-style="minimal"><div class="formkit-header" data-element="header" style="color: #111827; font-size: 22px; font-weight: 700; letter-spacing: -0.02em;"><h2>Sign Up to Preview the Complete Site</h2></div><div class="formkit-subheader" data-element="subheader" style="color: rgb(104, 104, 104); font-size: 13px;"><div style="width:100%;text-align:center"><figure style="display:none"><div style="display:block;max-width:65px"><img src="https://embed.filekitcdn.com/e/nXksRXDds8iLbcKN2okUrC/vHKXG9fJiccDWTL3DqrxEx" alt="trove_logo" width="65" height="64" style="max-width:100%;height:auto;border-radius:4px;width:65px"></div><figcaption style="text-align:center;display:none">&#8203;</figcaption></figure></div><p>Add your details and we'll share Trove's preview link over email</p></div><ul class="formkit-alert formkit-alert-error" data-element="errors" data-group="alert"></ul><div data-element="fields" data-stacked="true" class="seva-fields formkit-fields"><div class="formkit-field"><input class="formkit-input" aria-label="First Name" name="fields[first_name]" required="" placeholder="First Name" type="text" style="color: rgb(0, 0, 0); border-color: rgb(227, 227, 227); border-radius: 4px; font-weight: 400;"></div><div class="formkit-field"><input class="formkit-input" name="email_address" aria-label="Email Address" placeholder="Email Address" required="" type="email" style="color: rgb(0, 0, 0); border-color: rgb(227, 227, 227); border-radius: 4px; font-weight: 400;"></div><div class="formkit-field"><div data-group="dropdown" class="formkit-3609" type="Custom" order="2" save_as="Tag" group="field"><select class="formkit-select" data-element="tags-select" name="tags[]" required="" style="color: rgb(0, 0, 0); border-color: rgb(227, 227, 227); border-radius: 4px; font-weight: 400;"><option value="">Currently I...</option><option value="18245841">Save a Lot of Bookmarks</option><option value="18245842">Rarely save Bookmarks</option><option value="18245846">Save bookmarks sometimes but not often</option></select></div></div><div class="formkit-field"><div data-group="dropdown" class="formkit-4352" type="Custom" order="3" save_as="Tag" group="field"><select class="formkit-select" data-element="tags-select" name="tags[]" style="color: rgb(0, 0, 0); border-color: rgb(227, 227, 227); border-radius: 4px; font-weight: 400;"><option value="">I primarily use</option><option value="18248074">ChatGPT</option><option value="18248075">Claude</option><option value="18248076">Gemini</option><option value="18248770">OpenSource Models</option><option value="18248771">No AI Model</option><option value="18248783">Perplexity</option></select></div></div><button data-element="submit" class="formkit-submit formkit-submit" style="color: rgb(255, 255, 255); background-color: rgb(41, 124, 255); border-radius: 4px; font-weight: 400;"><div class="formkit-spinner"><div></div><div></div><div></div></div><span class="">Request Preview Access</span></button></div><div class="formkit-guarantee" data-element="guarantee" style="color: rgb(77, 77, 77); font-size: 13px; font-weight: 400;"><p>We won't send you spam. Unsubscribe at any time.</p></div></div><style>.formkit-form[data-uid="b920902896"] *{box-sizing:border-box;}.formkit-form[data-uid="b920902896"]{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;}.formkit-form[data-uid="b920902896"] .formkit-input,.formkit-form[data-uid="b920902896"] .formkit-select,.formkit-form[data-uid="b920902896"] .formkit-checkboxes{width:100%;}.formkit-form[data-uid="b920902896"] .formkit-button,.formkit-form[data-uid="b920902896"] .formkit-submit{border:0;border-radius:5px;color:#ffffff;cursor:pointer;display:inline-block;text-align:center;font-size:15px;font-weight:500;cursor:pointer;margin-bottom:15px;overflow:hidden;padding:0;position:relative;vertical-align:middle;}.formkit-form[data-uid="b920902896"] .formkit-button > span,.formkit-form[data-uid="b920902896"] .formkit-submit > span{display:block;-webkit-transition:all 300ms ease-in-out;transition:all 300ms ease-in-out;padding:10px 20px;}.formkit-form[data-uid="b920902896"] .formkit-input{background:#ffffff;font-size:13px;padding:9px 12px;border:1px solid #e3e3e3;-webkit-flex:1 0 auto;-ms-flex:1 0 auto;flex:1 0 auto;line-height:1.4;margin:0;-webkit-transition:border-color ease-out 300ms;transition:border-color ease-out 300ms;}.formkit-form[data-uid="b920902896"] .formkit-input:focus{outline:none;border-color:#1677be;}.formkit-form[data-uid="b920902896"] [data-group="dropdown"]{position:relative;display:inline-block;width:100%;}.formkit-form[data-uid="b920902896"] [data-group="dropdown"]::before{content:"";top:calc(50% - 2.5px);right:10px;position:absolute;pointer-events:none;border-color:#4f4f4f transparent transparent transparent;border-style:solid;border-width:6px 6px 0 6px;height:0;width:0;z-index:999;}.formkit-form[data-uid="b920902896"] [data-group="dropdown"] select{height:auto;width:100%;cursor:pointer;color:#333333;line-height:1.4;margin-bottom:0;padding:0 6px;-webkit-appearance:none;-moz-appearance:none;appearance:none;font-size:13px;padding:9px 12px;padding-right:25px;border:1px solid #e3e3e3;background:#ffffff;}.formkit-form[data-uid="b920902896"] .formkit-alert{background:#f9fafb;border:1px solid #e3e3e3;border-radius:5px;-webkit-flex:1 0 auto;-ms-flex:1 0 auto;flex:1 0 auto;list-style:none;margin:25px auto;padding:12px;text-align:center;width:100%;}.formkit-form[data-uid="b920902896"] .formkit-alert:empty{display:none;}.formkit-form[data-uid="b920902896"] .formkit-alert-success{background:#d3fbeb;border-color:#10bf7a;color:#0c905c;}.formkit-form[data-uid="b920902896"] .formkit-alert-error{background:#fde8e2;border-color:#f2643b;color:#ea4110;}.formkit-form[data-uid="b920902896"] .formkit-spinner{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;height:0px;width:0px;margin:0 auto;position:absolute;top:0;left:0;right:0;width:0px;overflow:hidden;text-align:center;-webkit-transition:all 300ms ease-in-out;transition:all 300ms ease-in-out;}.formkit-form[data-uid="b920902896"] .formkit-spinner > div{margin:auto;width:12px;height:12px;background-color:#fff;opacity:0.3;border-radius:100%;display:inline-block;-webkit-animation:formkit-bouncedelay-formkit-form-data-uid-b920902896- 1.4s infinite ease-in-out both;animation:formkit-bouncedelay-formkit-form-data-uid-b920902896- 1.4s infinite ease-in-out both;}.formkit-form[data-uid="b920902896"] .formkit-spinner > div:nth-child(1){-webkit-animation-delay:-0.32s;animation-delay:-0.32s;}.formkit-form[data-uid="b920902896"] .formkit-spinner > div:nth-child(2){-webkit-animation-delay:-0.16s;animation-delay:-0.16s;}.formkit-form[data-uid="b920902896"] .formkit-submit[data-active] .formkit-spinner{opacity:1;height:100%;width:50px;}.formkit-form[data-uid="b920902896"] .formkit-submit[data-active] .formkit-spinner ~ span{opacity:0;}.formkit-form[data-uid="b920902896"]{border:none;max-width:700px;position:relative;overflow:hidden;}.formkit-form[data-uid="b920902896"] .formkit-background{width:100%;height:100%;position:absolute;top:0;left:0;background-size:cover;background-position:center;opacity:0.3;}.formkit-form[data-uid="b920902896"] [data-style="minimal"]{padding:8px 28px 24px;width:100%;position:relative;}.formkit-form[data-uid="b920902896"] .formkit-header{margin:0 0 8px 0;text-align:center;}.formkit-form[data-uid="b920902896"] .formkit-subheader{margin:6px 0;text-align:center;}.formkit-form[data-uid="b920902896"] .formkit-guarantee{font-size:12px;margin:6px 0 8px 0;text-align:center;}.formkit-form[data-uid="b920902896"] .formkit-guarantee > p{margin:0;}.formkit-form[data-uid="b920902896"] .formkit-fields{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-wrap:wrap;-ms-flex-wrap:wrap;flex-wrap:wrap;margin:10px auto 0 auto;}.formkit-form[data-uid="b920902896"] .formkit-field{min-width:220px;}.formkit-form[data-uid="b920902896"] .formkit-field,.formkit-form[data-uid="b920902896"] .formkit-submit{margin:0 0 10px 0;-webkit-flex:1 0 100%;-ms-flex:1 0 100%;flex:1 0 100%;}@-webkit-keyframes formkit-bouncedelay-formkit-form-data-uid-b920902896-{0%,80%,100%{-webkit-transform:scale(0);-ms-transform:scale(0);transform:scale(0);}40%{-webkit-transform:scale(1);-ms-transform:scale(1);transform:scale(1);}}@keyframes formkit-bouncedelay-formkit-form-data-uid-b920902896-{0%,80%,100%{-webkit-transform:scale(0);-ms-transform:scale(0);transform:scale(0);}40%{-webkit-transform:scale(1);-ms-transform:scale(1);transform:scale(1);}}</style></form>`;

function PreviewGateModal({ onClose, onSuccess }) {
  React.useEffect(() => {
    if (!window.__ckjsLoaded) {
      const s = document.createElement('script');
      s.src = 'https://f.convertkit.com/ckjs/ck.5.js';
      s.async = true;
      s.onload = () => { window.__ckjsLoaded = true; };
      document.head.appendChild(s);
    }
  }, []);

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div
        style={{position:'relative', maxWidth:440, width:'92%', margin:'auto', borderRadius:14, overflow:'hidden', boxShadow:'0 20px 60px rgba(0,0,0,0.35)', background:'#fff'}}
        onClick={e => e.stopPropagation()}
      >
        <button
          onClick={onClose}
          aria-label="Close"
          style={{position:'absolute', top:12, right:12, zIndex:10, background:'transparent', border:'none', borderRadius:'50%', width:28, height:28, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', color:'#9ca3af'}}
        >
          <I.Close className="icon icon-sm" />
        </button>
        <div style={{display:'flex', alignItems:'center', justifyContent:'center', gap:8, padding:'24px 20px 4px', background:'#fff'}}>
          <I.Logo style={{width:26, height:26}} />
          <span style={{fontSize:18, fontWeight:700, color:'#111827', letterSpacing:'-0.02em'}}>Trove</span>
        </div>
        <div dangerouslySetInnerHTML={{__html: GATE_FORM_HTML}} />
      </div>
    </div>
  );
}

window.PreviewGateModal = PreviewGateModal;

function AddBookmarkPopup({ onClose }) {
  const [url, setUrl] = React.useState('');
  const [addToCatchup, setAddToCatchup] = React.useState(true);
  const [expanded, setExpanded] = React.useState(false);
  const [title, setTitle] = React.useState('');
  const [collection, setCollection] = React.useState('');
  const [notes, setNotes] = React.useState('');
  const [tags, setTags] = React.useState([]);
  const [tagInput, setTagInput] = React.useState('');
  const cardRef = React.useRef(null);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    const onDocClick = (e) => {
      if (cardRef.current && !cardRef.current.contains(e.target)) onClose();
    };
    document.addEventListener('keydown', onKey);
    // Defer to next tick so the click that opened the popup doesn't immediately close it.
    const t = setTimeout(() => document.addEventListener('click', onDocClick), 0);
    return () => {
      clearTimeout(t);
      document.removeEventListener('keydown', onKey);
      document.removeEventListener('click', onDocClick);
    };
  }, [onClose]);

  const handleTagKey = (e) => {
    if ((e.key === 'Enter' || e.key === ',') && tagInput.trim()) {
      e.preventDefault();
      const raw = tagInput.trim().replace(/^#/, '');
      if (raw && !tags.includes(raw)) setTags(t => [...t, raw]);
      setTagInput('');
    }
    if (e.key === 'Backspace' && !tagInput && tags.length) {
      setTags(t => t.slice(0, -1));
    }
  };

  const topCollections = (typeof SAMPLE !== 'undefined' ? SAMPLE.collections : []).filter(c => !c.parentId);

  const S = {
    card: {
      position:'fixed', top:90, right:24, width:348, zIndex:999,
      background:'var(--surface)', border:'0.5px solid var(--border)',
      borderRadius:14, boxShadow:'0 8px 32px rgba(0,0,0,0.18), 0 2px 8px rgba(0,0,0,0.10)',
      overflow:'hidden', animation:'fadeUp 0.18s ease both',
    },
    header: {
      padding:'12px 14px 10px', borderBottom:'0.5px solid var(--border-sub)',
      display:'flex', alignItems:'center', justifyContent:'space-between',
    },
    headerTitle: { fontSize:13, fontWeight:700, color:'var(--text-1)', letterSpacing:'-0.01em' },
    body: { padding:'12px 14px' },
    label: { fontSize:11, fontWeight:600, color:'var(--text-3)', letterSpacing:'0.04em', textTransform:'uppercase', marginBottom:5, display:'block' },
    input: {
      width:'100%', boxSizing:'border-box', height:36, padding:'0 10px',
      fontSize:13, background:'var(--surface-2)', border:'0.5px solid var(--border)',
      borderRadius:8, color:'var(--text-1)', outline:'none',
      transition:'border-color 0.15s',
    },
    textarea: {
      width:'100%', boxSizing:'border-box', padding:'8px 10px', minHeight:64,
      fontSize:13, lineHeight:1.5, background:'var(--surface-2)', border:'0.5px solid var(--border)',
      borderRadius:8, color:'var(--text-1)', outline:'none', resize:'none',
      fontFamily:'inherit',
    },
    select: {
      width:'100%', boxSizing:'border-box', height:36, padding:'0 28px 0 10px',
      fontSize:13, background:'var(--surface-2)', border:'0.5px solid var(--border)',
      borderRadius:8, color:'var(--text-1)', outline:'none', appearance:'none',
      backgroundImage:'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%239ca3af\' stroke-width=\'2\'%3E%3Cpath d=\'m6 9 6 6 6-6\'/%3E%3C/svg%3E")',
      backgroundRepeat:'no-repeat', backgroundPosition:'right 8px center', backgroundSize:16,
    },
    row: { marginBottom:10 },
    checkRow: { display:'flex', alignItems:'center', gap:8, marginBottom:10 },
    expandBtn: {
      width:'100%', display:'flex', alignItems:'center', gap:6, padding:'7px 0',
      background:'none', border:'none', borderTop:'0.5px solid var(--border-sub)',
      color:'var(--text-3)', fontSize:12, fontWeight:600, cursor:'pointer',
      letterSpacing:'0.01em',
    },
    tagArea: {
      display:'flex', flexWrap:'wrap', gap:5, padding:'6px 8px', minHeight:36,
      background:'var(--surface-2)', border:'0.5px solid var(--border)', borderRadius:8,
      cursor:'text',
    },
    tag: {
      display:'inline-flex', alignItems:'center', gap:4, padding:'2px 8px',
      background:'var(--blue-bg)', color:'var(--blue-text)', borderRadius:8,
      fontSize:12, fontWeight:500,
    },
    tagInput: {
      flex:1, minWidth:60, background:'none', border:'none', outline:'none',
      fontSize:12, color:'var(--text-1)', fontFamily:'inherit',
    },
    footer: {
      padding:'10px 14px', borderTop:'0.5px solid var(--border-sub)',
      display:'flex', justifyContent:'flex-end',
    },
  };

  return (
    <div ref={cardRef} style={S.card}>
        <div style={S.header}>
          <span style={S.headerTitle}><I.Plus className="icon icon-xs" style={{display:'inline',verticalAlign:'middle',marginRight:5}} />Add Bookmark</span>
          <button className="btn-icon" onClick={onClose} style={{width:24,height:24}}><I.Close className="icon icon-xs" /></button>
        </div>

        <div style={S.body}>
          {/* URL */}
          <div style={S.row}>
            <input
              autoFocus
              style={S.input}
              placeholder="Paste a URL…"
              value={url}
              onChange={e => setUrl(e.target.value)}
            />
          </div>

          {/* Add to Catch Up toggle */}
          <div style={S.checkRow}>
            <div
              onClick={() => setAddToCatchup(v => !v)}
              style={{
                width:16, height:16, borderRadius:4, border:'1.5px solid var(--border)',
                background: addToCatchup ? 'var(--blue)' : 'var(--surface-2)',
                borderColor: addToCatchup ? 'var(--blue)' : 'var(--border)',
                display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', flexShrink:0,
                transition:'background 0.15s, border-color 0.15s',
              }}
            >
              {addToCatchup && <I.Check className="icon" style={{width:10,height:10,stroke:'#fff',strokeWidth:3}} />}
            </div>
            <span style={{fontSize:13, color:'var(--text-2)', cursor:'pointer', userSelect:'none'}} onClick={() => setAddToCatchup(v => !v)}>
              Add to Catch Up
            </span>
          </div>

          {/* More Details toggle */}
          <button style={S.expandBtn} onClick={() => setExpanded(v => !v)}>
            {expanded ? <I.ChevronUp className="icon icon-xs" /> : <I.ChevronDown className="icon icon-xs" />}
            More Details
          </button>

          {expanded && (
            <div style={{marginTop:10}} className="fade-up">
              {/* Title */}
              <div style={S.row}>
                <label style={S.label}>Title</label>
                <input style={S.input} placeholder="Auto-extracted from URL" value={title} onChange={e => setTitle(e.target.value)} />
              </div>

              {/* Collection */}
              <div style={S.row}>
                <label style={S.label}>Collection</label>
                <div style={{position:'relative'}}>
                  <select style={S.select} value={collection} onChange={e => setCollection(e.target.value)}>
                    <option value="">No collection</option>
                    {topCollections.map(c => (
                      <option key={c.id} value={c.id}>{c.name}</option>
                    ))}
                  </select>
                </div>
              </div>

              {/* Notes */}
              <div style={S.row}>
                <label style={S.label}>Notes</label>
                <textarea style={S.textarea} placeholder="Add a note…" value={notes} onChange={e => setNotes(e.target.value)} />
              </div>

              {/* Tags */}
              <div style={{...S.row, marginBottom:0}}>
                <label style={S.label}>Tags</label>
                <div style={S.tagArea} onClick={e => e.currentTarget.querySelector('input').focus()}>
                  {tags.map((t, i) => (
                    <span key={i} style={S.tag}>
                      #{t}
                      <span
                        onClick={() => setTags(prev => prev.filter((_, j) => j !== i))}
                        style={{cursor:'pointer', opacity:0.6, fontSize:11, lineHeight:1}}
                      >×</span>
                    </span>
                  ))}
                  <input
                    style={S.tagInput}
                    placeholder={tags.length === 0 ? 'Type a tag and press Enter…' : ''}
                    value={tagInput}
                    onChange={e => setTagInput(e.target.value)}
                    onKeyDown={handleTagKey}
                  />
                </div>
              </div>
            </div>
          )}
        </div>

        <div style={S.footer}>
          <button
            className="btn btn-primary btn-sm"
            disabled={!url}
            style={{opacity: url ? 1 : 0.45, minWidth:90}}
            onClick={onClose}
          >
            Add URL
          </button>
        </div>
    </div>
  );
}

window.AddBookmarkPopup = AddBookmarkPopup;
