// Wines of Texas — Shared UI components (nav, footer, placeholder, tweaks)
// Globals: window.Nav, window.Footer, window.Ph, window.Tweaks, window.useTheme

const { useState, useEffect, useCallback, useMemo, useRef } = React;

/* ---------------------------------------------------------------------
   Theme hook — reads/writes [data-theme] on <html>
--------------------------------------------------------------------- */
function useTheme() {
  const [theme, setTheme] = useState(() => {
    return document.documentElement.getAttribute('data-theme') ||
      localStorage.getItem('wot-theme') || 'editorial';
  });
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem('wot-theme', theme);
  }, [theme]);
  return [theme, setTheme];
}

/* ---------------------------------------------------------------------
   Image / placeholder
   ---------------------------------------------------------------------
   Tiered image system:
     kind="photo"   (default) — seeded Picsum photo. Stable per seed.
                                Pass `src` to override with a real URL.
     kind="stripe"  — striped placeholder (schematic slots: maps, etc.)
     kind="initial" — colored card with a letter (unclaimed winery cards).
                      Background color is hashed from `seed`.
--------------------------------------------------------------------- */
const PH_TINTS = [
  '#7a1a1a', '#3e5c3a', '#8a5a2b', '#475a7a', '#6b4a6e',
  '#5a6b3a', '#8a6a4a', '#3a5a5a', '#7a4a3a', '#4a5a6b',
];
function hashSeed(s) {
  let h = 2166136261 >>> 0;
  for (let i = 0; i < s.length; i++) {
    h = Math.imul(h ^ s.charCodeAt(i), 16777619) >>> 0;
  }
  return h;
}
function picsumUrl(seed, w = 1200, h = 800) {
  const s = String(seed || 'wines-of-texas').replace(/\s+/g, '-').toLowerCase();
  return `https://picsum.photos/seed/${encodeURIComponent(s)}/${w}/${h}`;
}

function Ph({
  label = 'photo',
  aspect = '4/3',
  style,
  className = '',
  kind = 'photo',
  src,
  seed,
  initial,
  alt,
}) {
  const key = seed || label;

  if (kind === 'stripe') {
    return (
      <div className={`ph ${className}`} style={{ aspectRatio: aspect, ...style }}>
        <span>{label}</span>
      </div>
    );
  }

  if (kind === 'initial') {
    const tint = PH_TINTS[hashSeed(String(key)) % PH_TINTS.length];
    const letter = (initial || String(key).trim().charAt(0) || '?').toUpperCase();
    return (
      <div
        className={`ph-initial ${className}`}
        style={{ aspectRatio: aspect, background: tint, ...style }}
        aria-label={alt || label}>
        <span>{letter}</span>
      </div>
    );
  }

  // photo (default)
  const url = src || picsumUrl(key);
  return (
    <div
      className={`ph-photo ${className}`}
      style={{ aspectRatio: aspect, backgroundImage: `url("${url}")`, ...style }}
      role="img"
      aria-label={alt || label}
    />
  );
}

/* ---------------------------------------------------------------------
   Nav
--------------------------------------------------------------------- */
function Nav({ active, onNav, theme, setTheme }) {
  const links = [
    { id: 'home', label: 'Home' },
    { id: 'directory', label: 'Wineries' },
    { id: 'database', label: 'Database' },
    { id: 'regions', label: 'Regions' },
    { id: 'winery', label: 'Spotlight' },
    { id: 'advertise', label: 'Advertise' },
    { id: 'claim', label: 'Preview' },
    { id: 'portal', label: 'List Winery' },
  ];
  return (
    <header className="nav">
      <div className="nav-inner">
        <a className="nav-logo" onClick={() => onNav('home')} style={{ cursor: 'pointer' }}>
          <span>Wines of Texas</span>
          <small>EST. 2026</small>
        </a>
        <nav className="nav-links">
          {links.map(l => (
            <a key={l.id}
              className={active === l.id ? 'active' : ''}
              onClick={() => onNav(l.id)}>
              {l.label}
            </a>
          ))}
        </nav>
        <div className="nav-actions">
          <div className="theme-pill" title="Aesthetic direction">
            {['editorial','rustic','almanac'].map(t => (
              <button key={t}
                className={theme === t ? 'on' : ''}
                onClick={() => setTheme(t)}>
                {t[0]}
              </button>
            ))}
          </div>
          <input className="nav-search" placeholder="Search wineries, grapes…" />
        </div>
      </div>
    </header>
  );
}

/* ---------------------------------------------------------------------
   Footer
--------------------------------------------------------------------- */
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-grid">
        <div>
          <div className="footer-brand">
            Wines<br/>of Texas
            <small>EST. 2026</small>
          </div>
          <p style={{ fontSize: 14, opacity: 0.7, maxWidth: 320, lineHeight: 1.5 }}>
            An independent guide to Texas wine — its people, its places, and the
            bottles worth seeking out.
          </p>
        </div>
        <div>
          <h4>Explore</h4>
          <ul>
            <li>Wineries</li>
            <li>Regions &amp; AVAs</li>
            <li>Wine Trails</li>
            <li>Grape Varieties</li>
            <li>Events</li>
          </ul>
        </div>
        <div>
          <h4 style={{ display: 'none' }}>Shop</h4>
          <ul style={{ display: 'none' }}>
            <li>Featured Bottles</li>
            <li>Curated Cases</li>
            <li>Texan Club</li>
            <li>Gift Cards</li>
          </ul>
        </div>
        <div>
          <h4 style={{ display: 'none' }}>Read</h4>
          <ul style={{ display: 'none' }}>
            <li>Journal</li>
            <li>Tasting Notes</li>
            <li>Newsletter</li>
            <li>Podcast</li>
          </ul>
        </div>
        <div>
          <h4>Work With Us</h4>
          <ul>
            <li>Advertise</li>
            <li>List Your Winery</li>
            <li>Press</li>
            <li>Contact</li>
          </ul>
        </div>
      </div>
      <div className="footer-fine">
        <span>© 2026 Wines of Texas, LLC · winesoftexas.com</span>
        <span>Drink responsibly. 21+.</span>
      </div>
    </footer>
  );
}

/* ---------------------------------------------------------------------
   Tweaks panel — toggled by host via __activate_edit_mode
--------------------------------------------------------------------- */
function Tweaks({ state, setState }) {
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === '__activate_edit_mode') setOpen(true);
      if (d.type === '__deactivate_edit_mode') setOpen(false);
    };
    window.addEventListener('message', onMsg);
    // announce availability AFTER listener is live
    try { window.parent.postMessage({ type: '__edit_mode_available' }, '*'); } catch {}
    return () => window.removeEventListener('message', onMsg);
  }, []);

  if (!open) return null;

  const persist = (edits) => {
    try {
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits }, '*');
    } catch {}
  };

  const set = (key, val) => {
    setState(s => ({ ...s, [key]: val }));
    persist({ [key]: val });
  };

  return (
    <aside className="tweaks" role="region" aria-label="Tweaks">
      <h5>Tweaks <span style={{ opacity: 0.4 }}>·</span> <span style={{ opacity: 0.5 }}>winesoftexas.com</span></h5>

      <label>Aesthetic</label>
      <div className="opts">
        {['editorial','rustic','almanac'].map(t => (
          <button key={t} className={`opt ${state.theme===t?'on':''}`}
            onClick={() => set('theme', t)}>{t}</button>
        ))}
      </div>

      <label>Density</label>
      <div className="opts" style={{ gridTemplateColumns: '1fr 1fr' }}>
        {['airy','compact'].map(d => (
          <button key={d} className={`opt ${state.density===d?'on':''}`}
            onClick={() => set('density', d)}>{d}</button>
        ))}
      </div>

      <label>Hero Layout</label>
      <div className="opts">
        {['split','poster','data'].map(h => (
          <button key={h} className={`opt ${state.hero===h?'on':''}`}
            onClick={() => set('hero', h)}>{h}</button>
        ))}
      </div>

      <label style={{ marginTop: 18 }}>Toggles</label>
      <div className="check" onClick={() => set('showCommerce', !state.showCommerce)}>
        <span>Show commerce modules</span>
        <input type="checkbox" readOnly checked={state.showCommerce} />
      </div>
      <div className="check" onClick={() => set('showAds', !state.showAds)}>
        <span>Show ad slots</span>
        <input type="checkbox" readOnly checked={state.showAds} />
      </div>
      <div className="check" onClick={() => set('showNewsletter', !state.showNewsletter)}>
        <span>Newsletter block</span>
        <input type="checkbox" readOnly checked={state.showNewsletter} />
      </div>
    </aside>
  );
}

Object.assign(window, { Nav, Footer, Ph, Tweaks, useTheme });
