// Search modal, Saved drawer, Profile menu, Share modal, Create-list modal

function SearchModal({ open, onClose, onPickProduct, onPickList, lists }) {
  const [q, setQ] = useState('');
  const [focusIdx, setFocusIdx] = useState(0);
  const inputRef = useRef(null);

  useEffect(() => {
    if (open) {
      setTimeout(() => inputRef.current && inputRef.current.focus(), 80);
      setQ(''); setFocusIdx(0);
    }
  }, [open]);

  const ql = q.trim().toLowerCase();
  const productMatches = ql.length === 0 ? [] :
    (window.PRODUCTS || []).filter(p =>
      p.name.toLowerCase().includes(ql) ||
      p.brand.toLowerCase().includes(ql) ||
      (p.benefit || '').toLowerCase().includes(ql) ||
      p.category.includes(ql)
    ).slice(0, 8);
  const listMatches = ql.length === 0 ? [] :
    lists.filter(l => l.name.toLowerCase().includes(ql) || l.desc.toLowerCase().includes(ql)).slice(0, 3);

  const trending = ['Stokke pram', 'Magna-Tiles', 'Lovevery', 'Tonies', 'Carbon balance bike'];

  const onKey = (e) => {
    if (e.key === 'Escape') onClose();
  };

  return (
    <>
      <div className={`search-scrim${open ? ' is-open' : ''}`} onClick={onClose} />
      <div className={`search-modal${open ? ' is-open' : ''}`} onKeyDown={onKey}>
        <div className="search-input-wrap">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" style={{ color: 'var(--ink-3)' }}>
            <circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/>
          </svg>
          <input
            ref={inputRef}
            className="search-input"
            placeholder="Search 1,840 products, lists, and guides…"
            value={q}
            onChange={(e) => setQ(e.target.value)}
          />
          {q && <button className="iconbtn" style={{ width: 28, height: 28, border: 'none' }} onClick={() => setQ('')}>×</button>}
        </div>
        <div className="search-results">
          {ql.length === 0 ? (
            <div className="search-section">
              <div className="search-section-h">Trending searches</div>
              {trending.map(term => (
                <button key={term} className="search-result" onClick={() => setQ(term)} style={{ padding: '10px 0' }}>
                  <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--chip)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 17l6-6 4 4 8-8M14 7h7v7"/></svg>
                  </div>
                  <span style={{ fontSize: 14 }}>{term}</span>
                </button>
              ))}
            </div>
          ) : productMatches.length === 0 && listMatches.length === 0 ? (
            <div className="search-empty">No matches for &quot;{q}&quot;</div>
          ) : (
            <>
              {productMatches.length > 0 && (
                <div className="search-section">
                  <div className="search-section-h">Products · {productMatches.length}</div>
                  {productMatches.map((p, i) => (
                    <button
                      key={p.id}
                      className={`search-result${i === focusIdx ? ' is-focus' : ''}`}
                      onClick={() => { onPickProduct(p); onClose(); }}
                      style={{ padding: '10px 0' }}
                    >
                      <img className="search-result-img" src={p.img} alt="" />
                      <div className="search-result-body">
                        <div className="search-result-name">{p.name}</div>
                        <div className="search-result-meta">{p.brand} · {window.formatAge(p.ageMin, p.ageMax)} · ${p.price}</div>
                      </div>
                    </button>
                  ))}
                </div>
              )}
              {listMatches.length > 0 && (
                <div className="search-section">
                  <div className="search-section-h">Lists</div>
                  {listMatches.map(l => (
                    <button key={l.id} className="search-result" onClick={() => { onPickList(l); onClose(); }} style={{ padding: '10px 0' }}>
                      <div style={{ width: 44, height: 44, borderRadius: 8, background: 'var(--chip)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M19 21l-7-5-7 5V5a2 2 0 012-2h10a2 2 0 012 2z"/></svg>
                      </div>
                      <div className="search-result-body">
                        <div className="search-result-name">{l.name}</div>
                        <div className="search-result-meta">by {l.owner} · {l.productIds.length} items</div>
                      </div>
                    </button>
                  ))}
                </div>
              )}
            </>
          )}
        </div>
        <div className="search-foot">
          <span><kbd>↵</kbd>open</span>
          <span><kbd>↑</kbd><kbd>↓</kbd>navigate</span>
          <span><kbd>esc</kbd>close</span>
        </div>
      </div>
    </>
  );
}

function SavedDrawer({ open, savedIds, productMap, lists, onClose, onOpenProduct, onUnsave, onAddToList, onCreateListFromSaved }) {
  const items = savedIds.map(id => productMap[id]).filter(Boolean);
  return (
    <>
      <div className={`drawer-scrim${open ? ' is-open' : ''}`} onClick={onClose} />
      <aside className={`drawer${open ? ' is-open' : ''}`}>
        <div className="drawer-head">
          <h3 className="drawer-h">Saved · {items.length}</h3>
          <button className="iconbtn" onClick={onClose} aria-label="Close" style={{ width: 32, height: 32 }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6l12 12M6 18L18 6"/></svg>
          </button>
        </div>
        <div className="drawer-body">
          {items.length === 0 ? (
            <div className="drawer-empty">
              <h4 className="drawer-empty-h">Nothing saved yet</h4>
              <p style={{ fontSize: 13, margin: 0 }}>Tap the heart on any product to save it here for later.</p>
            </div>
          ) : (
            items.map(p => (
              <button key={p.id} className="drawer-item" onClick={() => { onOpenProduct(p); onClose(); }}>
                <img className="drawer-item-img" src={p.img} alt="" />
                <div className="drawer-item-body">
                  <div className="drawer-item-brand">{p.brand}</div>
                  <div className="drawer-item-name">{p.name}</div>
                  <div className="drawer-item-price">${p.price} · {window.formatAge(p.ageMin, p.ageMax)}</div>
                </div>
                <button onClick={(e) => { e.stopPropagation(); onUnsave(p.id); }}
                  style={{ background: 'transparent', border: 'none', color: 'var(--ink-3)', cursor: 'default', padding: 6 }}
                  aria-label="Remove">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6l12 12M6 18L18 6"/></svg>
                </button>
              </button>
            ))
          )}
        </div>
        {items.length > 0 && (
          <div className="drawer-foot">
            <button className="btn" onClick={onCreateListFromSaved}>
              <span>Make a list from these</span><span className="arrow">→</span>
            </button>
          </div>
        )}
      </aside>
    </>
  );
}

function ProfileMenu({ open, onClose, onNavigate, signedIn, onSignIn, onSignOut, onRevisit, onOpenKids, kids, audience }) {
  useEffect(() => {
    if (!open) return;
    const onClick = (e) => {
      if (!e.target.closest('.profile-menu') && !e.target.closest('[data-profile-trigger]')) onClose();
    };
    setTimeout(() => document.addEventListener('click', onClick), 50);
    return () => document.removeEventListener('click', onClick);
  }, [open, onClose]);

  return (
    <div className={`profile-menu${open ? ' is-open' : ''}`}>
      {signedIn ? (
        <>
          <div className="profile-menu-head">
            <div className="avatar">SA</div>
            <div>
              <p className="profile-menu-name">Sam Avery</p>
              <p className="profile-menu-email">sam@magicrascals.app</p>
            </div>
          </div>

          {audience === 'parent' && (
            <button onClick={() => { onOpenKids && onOpenKids(); onClose(); }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="9" cy="7" r="3"/><circle cx="17" cy="9" r="2.5"/><path d="M3 21a6 6 0 0112 0M14 21a4.5 4.5 0 017 0"/></svg>
              <span style={{ display: 'flex', alignItems: 'baseline', gap: 6, flex: 1, justifyContent: 'space-between' }}>
                <span>My kids</span>
                <span style={{ color: 'var(--ink-3)', fontSize: 11 }}>{(kids || []).length === 0 ? 'Add one' : `${kids.length} on profile`}</span>
              </span>
            </button>
          )}

          <button onClick={() => { onNavigate('collections', 'owned'); onClose(); }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M5 12l5 5L20 7"/></svg>
            Stuff I own
          </button>
          <button onClick={() => { onNavigate('collections', 'wishlist'); onClose(); }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 22 12 18.56 5.82 22 7 14.14l-5-4.87 6.91-1.01L12 2z"/></svg>
            My wishlist
          </button>
          <button onClick={() => { onNavigate('collections', 'loved'); onClose(); }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>
            Loved
          </button>
          <div className="menu-divider" />
          <button onClick={() => { onNavigate('lists'); onClose(); }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M19 21l-7-5-7 5V5a2 2 0 012-2h10a2 2 0 012 2z"/></svg>
            My lists
          </button>
          <button onClick={() => { onNavigate('settings'); onClose(); }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 01-2.83 2.83l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 11-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 11-2.83-2.83l.06-.06a1.65 1.65 0 00.33-1.82 1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9 1.65 1.65 0 004.27 7.18l-.06-.06a2 2 0 112.83-2.83l.06.06A1.65 1.65 0 009 4.6a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 112.83 2.83l-.06.06a1.65 1.65 0 00-.33 1.82V9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"/></svg>
            Settings
          </button>
          <button>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 015.83 1c0 2-3 3-3 3M12 17h.01"/></svg>
            Help & feedback
          </button>
          <div className="menu-divider" />
          <button onClick={() => { onRevisit && onRevisit(); onClose(); }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 12a9 9 0 0115-6.7L21 8M21 3v5h-5"/><path d="M21 12a9 9 0 01-15 6.7L3 16M3 21v-5h5"/></svg>
            Revisit as new visitor
          </button>
          <button onClick={() => { onSignOut(); onClose(); }} style={{ color: 'var(--ink-3)' }}>
            Sign out
          </button>
        </>
      ) : (
        <>
          <div style={{ padding: '20px 14px 14px' }}>
            <p style={{ fontFamily: 'var(--serif)', fontSize: 22, letterSpacing: '-0.02em', margin: '0 0 6px' }}>Welcome back</p>
            <p style={{ fontSize: 13, color: 'var(--ink-2)', margin: 0 }}>Save lists, follow editors, get notified when picks update.</p>
          </div>
          <div style={{ padding: '0 8px 12px', display: 'flex', flexDirection: 'column', gap: 6 }}>
            <button className="btn" onClick={() => { onSignIn(); onClose(); }} style={{ padding: '12px 16px' }}>
              <span>Sign in</span><span className="arrow">→</span>
            </button>
            <button className="btn btn-ghost" onClick={() => { onSignIn(); onClose(); }} style={{ padding: '12px 16px' }}>
              <span>Create account</span><span className="arrow">+</span>
            </button>
          </div>
        </>
      )}
    </div>
  );
}

function ShareModal({ open, list, onClose }) {
  const [copied, setCopied] = useState(false);
  const link = list ? `magicrascals.app/list/${list.id}` : '';
  const copy = () => {
    navigator.clipboard && navigator.clipboard.writeText('https://' + link);
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  };
  return (
    <>
      <div className={`share-scrim${open ? ' is-open' : ''}`} onClick={onClose} />
      <div className={`share-modal${open ? ' is-open' : ''}`}>
        <h3 className="share-h">Share &ldquo;{list && list.name}&rdquo;</h3>
        <p className="share-sub">Anyone with this link can see your list and tap straight through to retailers.</p>

        <div className="share-link">
          <span style={{ flex: 1 }}>{link}</span>
          <button className="iconbtn" onClick={copy} style={{ width: 32, height: 32, borderColor: 'transparent' }}>
            {copied ? '✓' : (
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>
            )}
          </button>
        </div>

        <div className="share-channels">
          {[
            { id: 'mail', label: 'Email', sym: '@' },
            { id: 'msg', label: 'Message', sym: '✉' },
            { id: 'tw', label: 'Threads', sym: '@' },
            { id: 'wa', label: 'WhatsApp', sym: '✓' },
          ].map(c => (
            <button key={c.id} className="share-channel">
              <span className="share-channel-icon">{c.sym}</span>
              <span>{c.label}</span>
            </button>
          ))}
        </div>

        <div style={{ marginTop: 24, display: 'flex', justifyContent: 'flex-end' }}>
          <button className="btn btn-ghost" onClick={onClose} style={{ width: 'auto', padding: '10px 18px' }}>
            <span>Done</span><span className="arrow">✓</span>
          </button>
        </div>
      </div>
    </>
  );
}

function CreateListModal({ open, onClose, onCreate, defaultKind = 'private' }) {
  const [name, setName] = useState('');
  const [desc, setDesc] = useState('');
  const [kind, setKind] = useState(defaultKind);
  useEffect(() => { if (open) { setName(''); setDesc(''); setKind(defaultKind); } }, [open, defaultKind]);
  if (!open) return null;
  const submit = (e) => {
    e.preventDefault();
    if (!name.trim()) return;
    onCreate({ name: name.trim(), desc: desc.trim(), kind });
  };
  const KINDS = [
    { id: 'private', label: 'Just for me', sub: 'A private wish list. Nobody else sees it.' },
    { id: 'partner', label: 'Share with my partner', sub: 'You and your partner edit it together.' },
    { id: 'registry', label: 'Public registry', sub: 'Friends and family can buy from it and leave a note.' },
  ];
  return (
    <>
      <div className="share-scrim is-open" onClick={onClose} />
      <form className="share-modal is-open" onSubmit={submit}>
        <h3 className="share-h">New list</h3>
        <p className="share-sub">Give it a name. You can fine-tune everything else later.</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="form-row">
            <span className="form-lbl">Name</span>
            <input className="gift-input" autoFocus placeholder="e.g. Mira's third birthday" value={name} onChange={(e) => setName(e.target.value)} />
          </div>
          <div className="form-row">
            <span className="form-lbl">Who is it for?</span>
            <div className="list-kind-stack">
              {KINDS.map(k => (
                <label key={k.id} className={`list-kind-opt${kind === k.id ? ' is-selected' : ''}`}>
                  <input type="radio" name="list-kind" checked={kind === k.id} onChange={() => setKind(k.id)} />
                  <span>
                    <strong>{k.label}</strong>
                    <em>{k.sub}</em>
                  </span>
                </label>
              ))}
            </div>
          </div>
          <div className="form-row">
            <span className="form-lbl">Description (optional)</span>
            <textarea className="gift-input gift-textarea" placeholder="A short note for whoever opens it" value={desc} onChange={(e) => setDesc(e.target.value)} />
          </div>
        </div>
        <div style={{ marginTop: 24, display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <button type="button" className="btn btn-ghost" onClick={onClose} style={{ width: 'auto', padding: '10px 18px' }}>
            <span>Cancel</span>
          </button>
          <button type="submit" className="btn" style={{ width: 'auto', padding: '10px 18px' }}>
            <span>Create</span><span className="arrow">→</span>
          </button>
        </div>
      </form>
    </>
  );
}

function WelcomeModal({ open, onComplete }) {
  const [step, setStep] = useState(0);
  const [audience, setAudience] = useState(null);
  const [stage, setStage] = useState(null);
  const [recipientStage, setRecipientStage] = useState(null);
  const [locale, setLocale] = useState(() => (window.detectLocale ? window.detectLocale() : null));
  const [localeOpen, setLocaleOpen] = useState(false);
  useEffect(() => {
    if (open) {
      setStep(0);
      setAudience(null);
      setStage(null);
      setRecipientStage(null);
      setLocaleOpen(false);
      if (window.detectLocale) setLocale(window.detectLocale());
    }
  }, [open]);
  if (!open) return null;

  const STAGES = [
    { key: 'pre',  label: 'Expecting',     stopIdx: 0 },
    { key: '0-6m', label: 'Newborn',       stopIdx: 1 },
    { key: '6-12m',label: '6–12 months',   stopIdx: 3 },
    { key: '1-2y', label: '1–2 years',     stopIdx: 4 },
    { key: '3-4y', label: '3–4 years',     stopIdx: 6 },
    { key: '5+',   label: '5 years and up',stopIdx: 8 },
    { key: 'mix',  label: 'A mix of ages', stopIdx: 4 },
  ];

  const finishParent = (stageKey) => {
    const s = STAGES.find(x => x.key === stageKey);
    onComplete({ audience: 'parent', stage: stageKey, stopIdx: s ? s.stopIdx : 7, location: locale });
  };
  const finishGift = () => {
    const s = STAGES.find(x => x.key === recipientStage);
    onComplete({
      audience: 'gift',
      stage: recipientStage,
      stopIdx: s ? s.stopIdx : 7,
      location: locale,
    });
  };
  const skip = () => onComplete({ audience: 'parent', stage: null, stopIdx: 7, location: locale });

  const localeRow = (
    <div className="welcome-locale-wrap">
      <span className="welcome-locale-lbl">Shopping from</span>
      <div className="welcome-locale-trigger-wrap" data-locator-trigger>
        <button
          type="button"
          className="welcome-locale-trigger"
          onClick={() => setLocaleOpen(o => !o)}
          aria-haspopup="listbox"
          aria-expanded={localeOpen}
        >
          <span className="welcome-locale-flag" aria-hidden="true">{locale ? locale.flag : '🌍'}</span>
          <span className="welcome-locale-country">{locale ? locale.country : 'Choose a country'}</span>
          <span className="welcome-locale-cur">{locale ? `${locale.currency} ${locale.symbol}` : ''}</span>
          <span className="welcome-locale-chev" aria-hidden="true">▾</span>
        </button>
        <LocationPopover open={localeOpen} onClose={() => setLocaleOpen(false)} current={locale} onSelect={(l) => setLocale(l)} />
      </div>
    </div>
  );

  return (
    <>
      <div className="welcome-scrim">
        {/* drifting decorative blocks */}
        <span className="welcome-orb welcome-orb--1" aria-hidden="true" />
        <span className="welcome-orb welcome-orb--2" aria-hidden="true" />
        <span className="welcome-orb welcome-orb--3" aria-hidden="true" />
        <span className="welcome-orb welcome-orb--4" aria-hidden="true" />
        <span className="welcome-orb welcome-orb--5" aria-hidden="true" />
      </div>
      <div className="welcome-modal welcome-modal--hero" role="dialog" aria-modal="true" aria-label="Welcome">
        <div className="welcome-mark welcome-mark--big brand-mark" aria-hidden="true">
          <svg className="brand-mark-svg" viewBox="0 0 32 32" fill="none">
            <path className="brand-star brand-star--big" d="M16 4 L18.5 12.4 L27 12.7 L20.1 17.7 L22.6 26 L16 21 L9.4 26 L11.9 17.7 L5 12.7 L13.5 12.4 Z" />
            <path className="brand-star brand-star--small1" d="M25 5.5 L25.6 8 L28 8.4 L25.8 9.4 L25 12 L24.2 9.4 L22 8.4 L24.4 8 Z" />
            <path className="brand-star brand-star--small2" d="M6 22.5 L6.5 24.5 L8.5 24.8 L6.7 25.6 L6 27.5 L5.3 25.6 L3.5 24.8 L5.5 24.5 Z" />
            <circle className="brand-star brand-star--dot" cx="27" cy="22.5" r="1.3" />
          </svg>
        </div>

        {step === 0 && (
          <>
            <p className="welcome-eyebrow">Welcome to MagicRascals</p>
            <h2 className="welcome-h welcome-h--xl">
              The little things,
              <br/><em>sorted.</em>
            </h2>
            <p className="welcome-sub welcome-sub--big">
              Curated picks, registries that work, and a checklist for every stage —
              all tuned to your family. To begin, tell us who you're shopping for.
            </p>
            <div className="welcome-choices">
              <button className="welcome-choice" onClick={() => { setAudience('parent'); setStep(1); }}>
                <span className="welcome-choice-icon" aria-hidden="true">
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="12" cy="7" r="3.2"/><path d="M5 21a7 7 0 0114 0"/><circle cx="18" cy="14" r="1.6"/></svg>
                </span>
                <span className="welcome-choice-body">
                  <strong>I'm a parent</strong>
                  <em>(or about to be)</em>
                  <span className="welcome-choice-foot">For my own baby or kids — including stuff for me, the parent.</span>
                </span>
                <span className="welcome-choice-arrow">→</span>
              </button>
              <button className="welcome-choice" onClick={() => { setAudience('gift'); setStep(2); }}>
                <span className="welcome-choice-icon" aria-hidden="true">
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="8" width="18" height="13" rx="1.5"/><path d="M3 12h18M12 8v13M7.5 8c-2 0-3-3.5 0-3.5 2 0 4.5 3.5 4.5 3.5s2.5-3.5 4.5-3.5c3 0 2 3.5 0 3.5"/></svg>
                </span>
                <span className="welcome-choice-body">
                  <strong>A gift for someone else</strong>
                  <em>(niece, friend's baby, godchild)</em>
                  <span className="welcome-choice-foot">Find something thoughtful — or claim from a registry.</span>
                </span>
                <span className="welcome-choice-arrow">→</span>
              </button>
            </div>
            <button className="welcome-skip" onClick={skip}>Just looking — let me browse</button>
          </>
        )}

        {step === 1 && (
          <>
            <p className="welcome-eyebrow">One quick thing</p>
            <h2 className="welcome-h welcome-h--xl">Where are you<br/><em>in the journey?</em></h2>
            <p className="welcome-sub welcome-sub--big">We'll start the picks at the right age. Change it any time.</p>
            <div className="welcome-pills">
              {STAGES.map(s => (
                <button key={s.key} className={`welcome-pill${stage === s.key ? ' is-selected' : ''}`} onClick={() => setStage(s.key)}>
                  {s.label}
                </button>
              ))}
            </div>
            {localeRow}
            <div className="welcome-cta-row">
              <button className="btn btn-ghost" onClick={() => setStep(0)} style={{ width: 'auto', padding: '12px 18px' }}>
                <span className="arrow" style={{ transform: 'rotate(180deg)' }}>→</span>
                <span>Back</span>
              </button>
              <button className="btn" disabled={!stage} onClick={() => finishParent(stage)} style={{ width: 'auto', padding: '12px 22px', opacity: stage ? 1 : 0.4 }}>
                <span>Show me my picks</span><span className="arrow">→</span>
              </button>
            </div>
          </>
        )}

        {step === 2 && (
          <>
            <p className="welcome-eyebrow">A gift for someone else</p>
            <h2 className="welcome-h welcome-h--xl">How old are<br/><em>they?</em></h2>
            <p className="welcome-sub welcome-sub--big">We'll tune everything to the right age. You can change it any time.</p>
            <div className="welcome-pills">
              {STAGES.map(s => (
                <button key={s.key} className={`welcome-pill${recipientStage === s.key ? ' is-selected' : ''}`} onClick={() => setRecipientStage(s.key)}>
                  {s.label}
                </button>
              ))}
            </div>
            {localeRow}
            <div className="welcome-cta-row">
              <button className="btn btn-ghost" onClick={() => setStep(0)} style={{ width: 'auto', padding: '12px 18px' }}>
                <span className="arrow" style={{ transform: 'rotate(180deg)' }}>→</span>
                <span>Back</span>
              </button>
              <button className="btn" disabled={!recipientStage} onClick={finishGift} style={{ width: 'auto', padding: '12px 22px', opacity: recipientStage ? 1 : 0.4 }}>
                <span>Find them something</span><span className="arrow">→</span>
              </button>
            </div>
          </>
        )}
      </div>
    </>
  );
}

function ClaimGiftModal({ open, product, onClose, onConfirm }) {
  const [name, setName] = useState('');
  const [note, setNote] = useState('');
  useEffect(() => { if (open) { setName(''); setNote(''); } }, [open]);
  if (!open || !product) return null;
  const submit = (e) => {
    e.preventDefault();
    if (!name.trim()) return;
    onConfirm({ buyerName: name.trim(), note: note.trim(), productId: product.id });
  };
  return (
    <>
      <div className="share-scrim is-open" onClick={onClose} />
      <form className="share-modal is-open" onSubmit={submit}>
        <h3 className="share-h">You're getting <em style={{ fontStyle: 'italic' }}>{product.name}</em></h3>
        <p className="share-sub">Lovely. We'll mark it as taken so nobody buys a duplicate. Add a note if you'd like.</p>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 0 18px', borderBottom: '1px solid var(--rule-2)', marginBottom: 18 }}>
          <img src={product.img} alt="" style={{ width: 54, height: 54, borderRadius: 8, objectFit: 'cover' }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>{product.brand}</div>
            <div style={{ fontSize: 14, fontWeight: 500 }}>{product.name}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>${product.price}</div>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div className="form-row">
            <span className="form-lbl">Your name</span>
            <input className="gift-input" autoFocus placeholder="e.g. Aunt Lou" value={name} onChange={(e) => setName(e.target.value)} />
          </div>
          <div className="form-row">
            <span className="form-lbl">A note for the parents (optional)</span>
            <textarea className="gift-input gift-textarea" placeholder="A line they'll see when they unwrap it." value={note} onChange={(e) => setNote(e.target.value)} />
          </div>
        </div>
        <div style={{ marginTop: 22, display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <button type="button" className="btn btn-ghost" onClick={onClose} style={{ width: 'auto', padding: '10px 18px' }}>
            <span>Cancel</span>
          </button>
          <button type="submit" className="btn" style={{ width: 'auto', padding: '10px 18px' }}>
            <span>Mark as taken</span><span className="arrow">✓</span>
          </button>
        </div>
      </form>
    </>
  );
}

function ShareEssentialsModal({ open, onClose, stageLabel, stats }) {
  const [copied, setCopied] = useState(false);
  const link = 'magicrascals.app/essentials/sam';
  const copy = () => {
    navigator.clipboard && navigator.clipboard.writeText('https://' + link);
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  };
  if (!open) return null;
  return (
    <>
      <div className="share-scrim is-open" onClick={onClose} />
      <div className="share-modal is-open">
        <h3 className="share-h">Share your {stageLabel ? stageLabel.toLowerCase() : ''} essentials</h3>
        <p className="share-sub">Send the whole list to your partner — they can edit picks alongside you, and the running total stays in sync.</p>

        {stats && (
          <div className="share-stats">
            <div className="share-stat"><span className="num">{stats.pickedCount + stats.ownedCount}<em>/{stats.totalItems}</em></span><span className="lbl">sorted</span></div>
            <div className="share-stat"><span className="num">${(stats.total || 0).toLocaleString()}</span><span className="lbl">running total</span></div>
            <div className="share-stat"><span className="num">{stats.registryCount || 0}</span><span className="lbl">on registry</span></div>
          </div>
        )}

        <div className="share-link">
          <span style={{ flex: 1 }}>{link}</span>
          <button className="iconbtn" onClick={copy} style={{ width: 32, height: 32, borderColor: 'transparent' }}>
            {copied ? '✓' : (
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>
            )}
          </button>
        </div>

        <div className="share-channels">
          {[
            { id: 'mail', label: 'Email', sym: '@' },
            { id: 'msg', label: 'Message', sym: '✉' },
            { id: 'wa', label: 'WhatsApp', sym: '✓' },
            { id: 'partner', label: 'Invite partner', sym: '+' },
          ].map(c => (
            <button key={c.id} className="share-channel">
              <span className="share-channel-icon">{c.sym}</span>
              <span>{c.label}</span>
            </button>
          ))}
        </div>

        <div style={{ marginTop: 24, display: 'flex', justifyContent: 'flex-end' }}>
          <button className="btn btn-ghost" onClick={onClose} style={{ width: 'auto', padding: '10px 18px' }}>
            <span>Done</span><span className="arrow">✓</span>
          </button>
        </div>
      </div>
    </>
  );
}

function AddEssentialModal({ open, sections, initialSectionId, onClose, onAdd }) {
  const [label, setLabel] = useState('');
  const [necessity, setNecessity] = useState('nice');
  const [sectionId, setSectionId] = useState((sections && sections[0] && sections[0].id) || '');

  useEffect(() => {
    if (open) {
      setLabel('');
      setNecessity('nice');
      setSectionId(initialSectionId || (sections && sections[0] && sections[0].id) || '');
    }
  }, [open, initialSectionId, sections]);

  if (!open) return null;
  const submit = (e) => {
    e.preventDefault();
    if (!label.trim()) return;
    onAdd({ label: label.trim(), necessity, sectionId, blurb: '' });
  };

  return (
    <>
      <div className="share-scrim is-open" onClick={onClose} />
      <form className="share-modal is-open" onSubmit={submit}>
        <h3 className="share-h">Add to your essentials</h3>
        <p className="share-sub">Something we missed? Add it here. You can pick a product for it later (or never — checklist items are fine on their own).</p>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="form-row">
            <span className="form-lbl">What is it?</span>
            <input
              className="gift-input"
              autoFocus
              placeholder="e.g. A play mat"
              value={label}
              onChange={(e) => setLabel(e.target.value)}
            />
          </div>
          <div className="form-row">
            <span className="form-lbl">Where does it fit?</span>
            <select
              className="gift-input"
              value={sectionId}
              onChange={(e) => setSectionId(e.target.value)}
              style={{ appearance: 'auto', cursor: 'pointer' }}
            >
              {sections.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
            </select>
          </div>
          <div className="form-row">
            <span className="form-lbl">How important?</span>
            <div className="add-essential-radios">
              <label className={`add-essential-radio${necessity === 'must' ? ' is-selected' : ''}`}>
                <input type="radio" name="necessity" checked={necessity === 'must'} onChange={() => setNecessity('must')} />
                <span><strong>Must-have</strong><em>You can't go without it.</em></span>
              </label>
              <label className={`add-essential-radio${necessity === 'nice' ? ' is-selected' : ''}`}>
                <input type="radio" name="necessity" checked={necessity === 'nice'} onChange={() => setNecessity('nice')} />
                <span><strong>Nice-to-have</strong><em>If budget allows.</em></span>
              </label>
            </div>
          </div>
        </div>

        <div style={{ marginTop: 22, display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <button type="button" className="btn btn-ghost" onClick={onClose} style={{ width: 'auto', padding: '10px 18px' }}>
            <span>Cancel</span>
          </button>
          <button type="submit" className="btn" disabled={!label.trim()} style={{ width: 'auto', padding: '10px 18px', opacity: label.trim() ? 1 : 0.4 }}>
            <span>Add</span><span className="arrow">+</span>
          </button>
        </div>
      </form>
    </>
  );
}

// Compute age string from a YYYY-MM-DD birthday.
function ageFromBirthday(birthday) {
  if (!birthday) return null;
  const dob = new Date(birthday);
  if (isNaN(dob.getTime())) return null;
  const now = new Date();
  let years = now.getFullYear() - dob.getFullYear();
  let months = now.getMonth() - dob.getMonth();
  if (now.getDate() < dob.getDate()) months -= 1;
  if (months < 0) { years -= 1; months += 12; }
  if (years < 0) return 'Due soon';
  if (years === 0 && months === 0) return 'Newborn';
  if (years === 0) return `${months} month${months === 1 ? '' : 's'}`;
  if (years < 2) return `${years}y ${months}m`;
  return `${years} year${years === 1 ? '' : 's'}`;
}
window.ageFromBirthday = ageFromBirthday;

function KidsModal({ open, kids, onClose, onAddKid, onUpdateKid, onRemoveKid }) {
  const [editingId, setEditingId] = useState(null);
  const [draftName, setDraftName] = useState('');
  const [draftDob, setDraftDob] = useState('');
  const [draftInterests, setDraftInterests] = useState([]);
  const [draftNotes, setDraftNotes] = useState('');
  const [adding, setAdding] = useState(false);
  const interestPool = (window.INTERESTS || []).slice(0, 12);

  useEffect(() => { if (!open) { setEditingId(null); setAdding(false); } }, [open]);

  if (!open) return null;

  const startEdit = (k) => {
    setEditingId(k.id);
    setAdding(false);
    setDraftName(k.name || '');
    setDraftDob(k.birthday || '');
    setDraftInterests(k.interests || []);
    setDraftNotes(k.notes || '');
  };
  const startAdd = () => {
    setEditingId(null);
    setAdding(true);
    setDraftName('');
    setDraftDob('');
    setDraftInterests([]);
    setDraftNotes('');
  };
  const cancelEdit = () => { setEditingId(null); setAdding(false); };

  const toggleInterest = (id) => {
    setDraftInterests(arr => arr.includes(id) ? arr.filter(x => x !== id) : [...arr, id]);
  };

  const submitDraft = (e) => {
    e && e.preventDefault();
    if (!draftName.trim()) return;
    if (adding) {
      onAddKid({ name: draftName.trim(), birthday: draftDob || null, interests: draftInterests, notes: draftNotes.trim() });
    } else if (editingId) {
      onUpdateKid(editingId, { name: draftName.trim(), birthday: draftDob || null, interests: draftInterests, notes: draftNotes.trim() });
    }
    cancelEdit();
  };

  const editing = adding || editingId;

  return (
    <>
      <div className="share-scrim is-open" onClick={onClose} />
      <div className="share-modal is-open kids-modal">
        <h3 className="share-h">Your kids</h3>
        <p className="share-sub">Tell us about the little ones you're shopping for. We use this to tailor the picks — and you can come back to update interests as they grow.</p>

        {!editing && (
          <>
            {(kids || []).length === 0 ? (
              <div className="kids-empty">
                <p>No kids on your profile yet.</p>
              </div>
            ) : (
              <ul className="kids-list">
                {kids.map(k => {
                  const age = ageFromBirthday(k.birthday);
                  const initials = (k.name || '?').split(' ').map(w => w[0]).slice(0, 2).join('').toUpperCase();
                  return (
                    <li key={k.id} className="kids-card">
                      <div className="kids-card-top">
                        <div className="kids-avatar">{initials}</div>
                        <div className="kids-card-h">
                          <div className="kids-name">{k.name}</div>
                          <div className="kids-meta">
                            {age || 'Birthday not set'}
                            {k.birthday && <span className="kids-meta-sep">·</span>}
                            {k.birthday && new Date(k.birthday).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })}
                          </div>
                        </div>
                        <div className="kids-card-actions">
                          <button className="kids-iconbtn" onClick={() => startEdit(k)} aria-label="Edit">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M12 20h9M16.5 3.5a2.121 2.121 0 113 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>
                          </button>
                          <button className="kids-iconbtn" onClick={() => onRemoveKid(k.id)} aria-label="Remove">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M3 6h18M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6M10 11v6M14 11v6M9 6V4a2 2 0 012-2h2a2 2 0 012 2v2"/></svg>
                          </button>
                        </div>
                      </div>
                      {(k.interests || []).length > 0 && (
                        <div className="kids-interests-row">
                          {(k.interests || []).map(iid => {
                            const intr = (window.INTERESTS || []).find(x => x.id === iid);
                            return intr ? <span key={iid} className="kids-interest-chip">{intr.name}</span> : null;
                          })}
                        </div>
                      )}
                      {k.notes && <p className="kids-notes">{k.notes}</p>}
                    </li>
                  );
                })}
              </ul>
            )}
            <button className="kids-add-btn" onClick={startAdd}>
              <span className="plus">+</span>
              <span>Add a kid</span>
            </button>
          </>
        )}

        {editing && (
          <form onSubmit={submitDraft} className="kids-edit">
            <div className="form-row">
              <span className="form-lbl">Name</span>
              <input className="gift-input" autoFocus placeholder="e.g. Mira" value={draftName} onChange={(e) => setDraftName(e.target.value)} />
            </div>
            <div className="form-row">
              <span className="form-lbl">Birthday</span>
              <input
                className="gift-input"
                type="date"
                value={draftDob || ''}
                max={new Date(Date.now() + 365 * 24 * 3600 * 1000).toISOString().slice(0, 10)}
                onChange={(e) => setDraftDob(e.target.value)}
              />
            </div>
            <div className="form-row">
              <span className="form-lbl">What they're into</span>
              <div className="kids-interests-pick">
                {interestPool.map(intr => (
                  <button
                    type="button"
                    key={intr.id}
                    className={`kids-interest-pick${draftInterests.includes(intr.id) ? ' is-on' : ''}`}
                    onClick={() => toggleInterest(intr.id)}
                  >
                    {intr.name}
                  </button>
                ))}
              </div>
            </div>
            <div className="form-row">
              <span className="form-lbl">Notes <em style={{ fontStyle: 'normal', color: 'var(--ink-3)', fontSize: 11 }}>(allergies, sizes, anything we should know)</em></span>
              <textarea className="gift-input gift-textarea" placeholder="e.g. Loves anything wooden. Allergic to nuts." value={draftNotes} onChange={(e) => setDraftNotes(e.target.value)} />
            </div>
            <div style={{ marginTop: 18, display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
              <button type="button" className="btn btn-ghost" onClick={cancelEdit} style={{ width: 'auto', padding: '10px 18px' }}>
                <span>Cancel</span>
              </button>
              <button type="submit" className="btn" disabled={!draftName.trim()} style={{ width: 'auto', padding: '10px 18px', opacity: draftName.trim() ? 1 : 0.4 }}>
                <span>{adding ? 'Add to my kids' : 'Save'}</span><span className="arrow">→</span>
              </button>
            </div>
          </form>
        )}

        {!editing && (
          <div style={{ marginTop: 18, display: 'flex', justifyContent: 'flex-end' }}>
            <button className="btn btn-ghost" onClick={onClose} style={{ width: 'auto', padding: '10px 18px' }}>
              <span>Done</span><span className="arrow">✓</span>
            </button>
          </div>
        )}
      </div>
    </>
  );
}

function LocationPopover({ open, onClose, current, onSelect }) {
  useEffect(() => {
    if (!open) return;
    const onClick = (e) => {
      if (!e.target.closest('.locator-pop') && !e.target.closest('[data-locator-trigger]')) onClose();
    };
    setTimeout(() => document.addEventListener('click', onClick), 50);
    return () => document.removeEventListener('click', onClick);
  }, [open, onClose]);
  if (!open) return null;
  const locales = window.LOCALES || [];
  return (
    <div className="locator-pop" role="dialog" aria-label="Choose location and currency">
      <div className="locator-pop-h">
        <span>Shopping from</span>
        <span className="locator-pop-sub">{current ? `${current.currency} ${current.symbol}` : ''}</span>
      </div>
      <ul className="locator-pop-list">
        {locales.map(l => {
          const isCurrent = current && current.code === l.code;
          return (
            <li key={l.code}>
              <button
                type="button"
                className={`locator-pop-item${isCurrent ? ' is-current' : ''}`}
                onClick={() => { onSelect(l); onClose(); }}
              >
                <span className="locator-pop-flag" aria-hidden="true">{l.flag}</span>
                <span className="locator-pop-country">{l.country}</span>
                <span className="locator-pop-cur">{l.currency} {l.symbol}</span>
                {isCurrent && (
                  <span className="locator-pop-check" aria-hidden="true">
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M5 12l5 5L20 7"/></svg>
                  </span>
                )}
              </button>
            </li>
          );
        })}
      </ul>
    </div>
  );
}

function AddCustomOwnedModal({ open, onClose, onAdd }) {
  const [name, setName] = useState('');
  const [brand, setBrand] = useState('');
  const [price, setPrice] = useState('');
  const [imgUrl, setImgUrl] = useState('');
  const [notes, setNotes] = useState('');

  useEffect(() => {
    if (open) { setName(''); setBrand(''); setPrice(''); setImgUrl(''); setNotes(''); }
  }, [open]);

  if (!open) return null;
  const submit = (e) => {
    e.preventDefault();
    if (!name.trim()) return;
    onAdd({
      name: name.trim(),
      brand: brand.trim(),
      price: price ? Number(price) : null,
      img: imgUrl.trim() || null,
      notes: notes.trim(),
    });
  };
  return (
    <>
      <div className="share-scrim is-open" onClick={onClose} />
      <form className="share-modal is-open" onSubmit={submit}>
        <h3 className="share-h">Add to "Stuff you own"</h3>
        <p className="share-sub">Got something we don't carry? Add it here so it's part of the picture when you share with family.</p>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div className="form-row">
            <span className="form-lbl">What is it?</span>
            <input className="gift-input" autoFocus placeholder="e.g. The crib from grandma" value={name} onChange={(e) => setName(e.target.value)} />
          </div>
          <div className="form-row form-row--split">
            <div style={{ flex: 1 }}>
              <span className="form-lbl">Brand <em style={{ fontStyle: 'normal', color: 'var(--ink-3)', fontSize: 11 }}>(optional)</em></span>
              <input className="gift-input" placeholder="e.g. IKEA" value={brand} onChange={(e) => setBrand(e.target.value)} />
            </div>
            <div style={{ width: 120 }}>
              <span className="form-lbl">Price</span>
              <input className="gift-input" type="number" min="0" step="1" placeholder="—" value={price} onChange={(e) => setPrice(e.target.value)} />
            </div>
          </div>
          <div className="form-row">
            <span className="form-lbl">Image URL <em style={{ fontStyle: 'normal', color: 'var(--ink-3)', fontSize: 11 }}>(optional)</em></span>
            <input className="gift-input" placeholder="https://…" value={imgUrl} onChange={(e) => setImgUrl(e.target.value)} />
          </div>
          <div className="form-row">
            <span className="form-lbl">Notes <em style={{ fontStyle: 'normal', color: 'var(--ink-3)', fontSize: 11 }}>(optional)</em></span>
            <textarea className="gift-input gift-textarea" placeholder="A line about it — where it's from, who passed it down…" value={notes} onChange={(e) => setNotes(e.target.value)} />
          </div>
        </div>

        <div style={{ marginTop: 22, display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <button type="button" className="btn btn-ghost" onClick={onClose} style={{ width: 'auto', padding: '10px 18px' }}>
            <span>Cancel</span>
          </button>
          <button type="submit" className="btn" disabled={!name.trim()} style={{ width: 'auto', padding: '10px 18px', opacity: name.trim() ? 1 : 0.4 }}>
            <span>Add it</span><span className="arrow">+</span>
          </button>
        </div>
      </form>
    </>
  );
}

window.SearchModal = SearchModal;
window.SavedDrawer = SavedDrawer;
window.ProfileMenu = ProfileMenu;
window.ShareModal = ShareModal;
window.CreateListModal = CreateListModal;
window.WelcomeModal = WelcomeModal;
window.ClaimGiftModal = ClaimGiftModal;
window.ShareEssentialsModal = ShareEssentialsModal;
window.AddEssentialModal = AddEssentialModal;
window.KidsModal = KidsModal;
window.LocationPopover = LocationPopover;
window.AddCustomOwnedModal = AddCustomOwnedModal;
