// Settings page with sub-sections.
//
// Sections:
//   - Space — fit-checker dimensions (car boot, storage cupboard)
//   - Bookmarklet — "Add to MagicRascals" browser button setup

const SETTINGS_SECTIONS = [
  { id: 'space',       label: 'Space',       sub: 'What fits where' },
  { id: 'bookmarklet', label: 'Bookmarklet', sub: 'Add from anywhere' },
];

function SettingsPage({ fitPrefs, onSetFitPrefs }) {
  const [section, setSection] = useState(() => {
    if (typeof window === 'undefined') return 'space';
    try {
      const p = new URLSearchParams(window.location.search);
      const s = p.get('section');
      return SETTINGS_SECTIONS.some(x => x.id === s) ? s : 'space';
    } catch { return 'space'; }
  });

  // Keep the active section in the URL so refresh + share + back-button work.
  useEffect(() => {
    if (typeof window === 'undefined') return;
    const params = new URLSearchParams(window.location.search);
    if (section === 'space') params.delete('section');
    else params.set('section', section);
    const search = params.toString();
    const next = window.location.pathname + (search ? '?' + search : '') + window.location.hash;
    if (next !== window.location.pathname + window.location.search + window.location.hash) {
      try { window.history.replaceState({}, '', next); } catch {}
    }
  }, [section]);

  return (
    <div className="page settings-page">
      <div className="page-head">
        <div>
          <div className="page-eyebrow">Settings</div>
          <h1 className="page-title">Tailor it to <em><Whimsy text="you" />.</em></h1>
        </div>
      </div>

      <nav className="settings-nav" role="tablist">
        {SETTINGS_SECTIONS.map(s => (
          <button
            key={s.id}
            type="button"
            role="tab"
            aria-selected={section === s.id}
            className={`settings-nav-item${section === s.id ? ' is-on' : ''}`}
            onClick={() => setSection(s.id)}
          >
            <span className="settings-nav-label">{s.label}</span>
            <span className="settings-nav-sub">{s.sub}</span>
          </button>
        ))}
      </nav>

      {section === 'space' && (
        <SpaceSettings fitPrefs={fitPrefs} onSetFitPrefs={onSetFitPrefs} />
      )}
      {section === 'bookmarklet' && (
        <BookmarkletSettings />
      )}
    </div>
  );
}

function SpaceSettings({ fitPrefs, onSetFitPrefs }) {
  return (
    <>
      <p className="page-sub" style={{ marginBottom: 22 }}>
        Tell us your storage measurements and we'll flag which prams, travel cots and big toys
        actually fit. Stays on this device.
      </p>
      <div className="settings-stack">
        <SpaceCard
          title="Car boot"
          subtitle="Used to check whether folded prams, car seats and travel cots will fit."
          icon={
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" width="22" height="22"><path d="M4 14 L4 18 L6 18 M20 18 L18 18 M20 14 L20 18"/><path d="M4 14 L6 8 H 18 L20 14 Z"/><circle cx="8" cy="18" r="1.5"/><circle cx="16" cy="18" r="1.5"/></svg>
          }
          value={fitPrefs.boot}
          onChange={(v) => onSetFitPrefs({ ...fitPrefs, boot: v })}
        />
        <SpaceCard
          title="Storage cupboard"
          subtitle="Used to check whether everything else — toys, gear, bath gear — fits in your space."
          icon={
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" width="22" height="22"><rect x="4" y="3" width="16" height="18" rx="1.5"/><path d="M12 3 L12 21 M9 11 L9 13 M15 11 L15 13"/></svg>
          }
          value={fitPrefs.cupboard}
          onChange={(v) => onSetFitPrefs({ ...fitPrefs, cupboard: v })}
        />
      </div>
    </>
  );
}

function BookmarkletSettings() {
  // The bookmarklet's href — clicking-in-place is a no-op (preventDefault);
  // its real life starts when dragged to the bookmarks bar.
  const bookmarkletHref = "javascript:void(open('https://magicrascals.com/?url='+encodeURIComponent(location.href)+'#add'))";

  // Detect browser for tailored "show bookmarks bar" tip
  const browserHint = (() => {
    if (typeof navigator === 'undefined') return null;
    const ua = navigator.userAgent;
    if (/Safari/.test(ua) && !/Chrome|Chromium|Edg/.test(ua)) return 'safari';
    if (/Edg/.test(ua)) return 'edge';
    if (/Firefox/.test(ua)) return 'firefox';
    if (/Chrome|Chromium/.test(ua)) return 'chrome';
    return null;
  })();

  const showBookmarksShortcut = (() => {
    const isMac = typeof navigator !== 'undefined' && /Mac/.test(navigator.platform);
    return isMac ? '⌘ + ⇧ + B' : 'Ctrl + Shift + B';
  })();

  // Pick a sample URL to test against
  const testUrl = 'https://www.lovevery.com/products/the-block-set';

  return (
    <div className="bookmarklet-settings">
      <div className="bookmarklet-intro">
        <div className="bookmarklet-eyebrow">Browser button</div>
        <h2 className="bookmarklet-h">
          Add from <em><Whimsy text="any tab" /></em>, one click
        </h2>
        <p className="bookmarklet-sub">
          Drag the button below to your bookmarks bar. From then on, when you're shopping anywhere
          on the web and find something you want to add, just click your bookmark — we'll grab the
          product details and drop them into a new MagicRascals tab, ready to save.
        </p>
      </div>

      {/* The thing they actually drag */}
      <div className="bookmarklet-drag-section">
        <a
          className="bookmarklet-drag"
          href={bookmarkletHref}
          draggable={true}
          onClick={(e) => e.preventDefault()}
          title="Drag me to your bookmarks bar"
        >
          <span className="bookmarklet-drag-icon" aria-hidden="true">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2 L14.4 9.5 L21.2 9.7 L15.7 13.7 L17.7 20.3 L12 16.4 L6.3 20.3 L8.3 13.7 L2.8 9.7 L9.6 9.5 Z"/></svg>
          </span>
          <span className="bookmarklet-drag-label">+ Add to MagicRascals</span>
        </a>
        <p className="bookmarklet-drag-hint">↑ drag this button to your bookmarks bar</p>
      </div>

      {/* Step-by-step instructions */}
      <div className="bookmarklet-steps">
        <h3 className="bookmarklet-steps-h">How to set it up</h3>
        <ol className="bookmarklet-steplist">
          <li className="bookmarklet-step">
            <span className="bookmarklet-step-num">1</span>
            <div className="bookmarklet-step-body">
              <strong>Show your bookmarks bar.</strong>
              <p>Press <kbd>{showBookmarksShortcut}</kbd> to toggle it on if it's hidden. You'll see a thin row of bookmarks appear under the address bar.</p>
              {browserHint === 'safari' && (
                <p className="bookmarklet-step-note">In Safari: <strong>View → Show Favorites Bar</strong> if the shortcut doesn't fire.</p>
              )}
              {browserHint === 'firefox' && (
                <p className="bookmarklet-step-note">In Firefox: right-click anywhere in the toolbar area and tick <strong>Bookmarks Toolbar → Always show</strong>.</p>
              )}
            </div>
          </li>
          <li className="bookmarklet-step">
            <span className="bookmarklet-step-num">2</span>
            <div className="bookmarklet-step-body">
              <strong>Drag the button above to your bookmarks bar.</strong>
              <p>Click and hold the "+ Add to MagicRascals" button, then drag up to the bookmarks bar and release. A new bookmark appears.</p>
              <p className="bookmarklet-step-note">It looks like a bookmark, but it's actually a tiny piece of JavaScript. Don't worry — it's exactly 0 lines of tracking and runs entirely on your machine.</p>
            </div>
          </li>
          <li className="bookmarklet-step">
            <span className="bookmarklet-step-num">3</span>
            <div className="bookmarklet-step-body">
              <strong>Use it on any product page.</strong>
              <p>Browsing Lovevery, Pottery Barn, Maisonette, Etsy, anywhere — when you find something good, click your new bookmark. A new MagicRascals tab opens, already fetching the page, ready for you to pick a list and save.</p>
            </div>
          </li>
        </ol>
      </div>

      {/* Test it section */}
      <div className="bookmarklet-test">
        <h3 className="bookmarklet-test-h">Test it</h3>
        <p>Open a sample product page in a new tab, then click your new bookmark on that tab:</p>
        <a className="btn btn-ghost" href={testUrl} target="_blank" rel="noopener noreferrer" style={{ width: 'auto', padding: '10px 16px' }}>
          <span>Open the Lovevery Block Set</span><span className="arrow">↗</span>
        </a>
        <p className="bookmarklet-test-hint">
          On that page → click the "+ Add to MagicRascals" bookmark → a new MagicRascals tab opens
          with the Add modal already filled in with the block set's details.
        </p>
      </div>

      {/* Troubleshooting / FAQ */}
      <details className="bookmarklet-faq">
        <summary>Troubleshooting</summary>
        <div className="bookmarklet-faq-body">
          <h4>The button doesn't drag</h4>
          <p>Some browsers (especially in private/incognito mode) disable dragging from web pages. Try in a normal window.</p>

          <h4>I dragged it but nothing happens when I click it</h4>
          <p>Make sure the bookmark you created points to a URL that starts with <code>javascript:</code>. Right-click the bookmark → <strong>Edit</strong> and check the URL.</p>

          <h4>It works on most sites but not on (e.g.) Amazon</h4>
          <p>A few large retailers disable third-party JavaScript via Content Security Policy. Amazon, eBay, and most banks block bookmarklets entirely. For those, just copy the URL from your address bar and paste it into the <strong>+ Add by link</strong> modal directly.</p>

          <h4>Can I use it on my phone?</h4>
          <p>Technically yes, but mobile bookmark UX is awkward — bookmarklets don't show up in the typical "share" sheet. We're planning to add a proper "Share to MagicRascals" target for Android soon. For iOS, Apple still gatekeeps share extensions to native apps.</p>
        </div>
      </details>
    </div>
  );
}

function SpaceCard({ title, subtitle, icon, value, onChange }) {
  const v = value || { l: '', w: '', h: '' };
  const update = (key, val) => {
    const cleaned = val.replace(/[^0-9.]/g, '');
    onChange({ ...v, [key]: cleaned });
  };
  const clear = () => onChange({ l: '', w: '', h: '' });
  const isSet = (v.l && v.w && v.h);

  return (
    <section className="settings-card">
      <div className="settings-card-head">
        <div className="settings-card-icon" aria-hidden="true">{icon}</div>
        <div>
          <h2 className="settings-card-title">{title}</h2>
          <p className="settings-card-sub">{subtitle}</p>
        </div>
        {isSet && (
          <button type="button" className="settings-card-clear" onClick={clear} aria-label={`Clear ${title}`}>Clear</button>
        )}
      </div>
      <div className="settings-card-fields">
        <label className="settings-field">
          <span>Length (cm)</span>
          <input type="text" inputMode="decimal" placeholder="—" value={v.l} onChange={(e) => update('l', e.target.value)} />
        </label>
        <label className="settings-field">
          <span>Width (cm)</span>
          <input type="text" inputMode="decimal" placeholder="—" value={v.w} onChange={(e) => update('w', e.target.value)} />
        </label>
        <label className="settings-field">
          <span>Height (cm)</span>
          <input type="text" inputMode="decimal" placeholder="—" value={v.h} onChange={(e) => update('h', e.target.value)} />
        </label>
      </div>
    </section>
  );
}

window.SettingsPage = SettingsPage;
