// === Shared UI components for Tour Eiffel 2000 ===
const { useState, useEffect, useMemo, useRef } = React;

// SVG icons
const Icon = {
  Search: () => (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>),
  Cart: () => (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M3 4h2l2.5 12h12l2-9H6"/><circle cx="9" cy="20" r="1.2"/><circle cx="18" cy="20" r="1.2"/></svg>),
  Sun: () => (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>),
  Moon: () => (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></svg>),
  Arrow: () => (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M5 12h14M13 6l6 6-6 6"/></svg>),
  Close: () => (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M6 6l12 12M18 6 6 18"/></svg>),
  Plus: () => (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M12 5v14M5 12h14"/></svg>),
  Minus: () => (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M5 12h14"/></svg>),
};

// === Cart store (localStorage) ===
const CART_KEY = 'te2000_cart';
function readCart() {
  try { return JSON.parse(localStorage.getItem(CART_KEY) || '[]'); } catch { return []; }
}
function writeCart(items) {
  localStorage.setItem(CART_KEY, JSON.stringify(items));
  window.dispatchEvent(new CustomEvent('cart-updated'));
}
function useCart() {
  const [items, setItems] = useState(readCart());
  useEffect(() => {
    const sync = () => setItems(readCart());
    window.addEventListener('cart-updated', sync);
    window.addEventListener('storage', sync);
    return () => {
      window.removeEventListener('cart-updated', sync);
      window.removeEventListener('storage', sync);
    };
  }, []);
  return {
    items,
    add: (item) => {
      const existing = items.find(i => i.key === item.key);
      const next = existing
        ? items.map(i => i.key === item.key ? { ...i, qty: i.qty + 1 } : i)
        : [...items, { ...item, qty: 1 }];
      writeCart(next);
    },
    remove: (key) => writeCart(items.filter(i => i.key !== key)),
    setQty: (key, qty) => writeCart(items.map(i => i.key === key ? { ...i, qty } : i)),
    clear: () => writeCart([]),
    total: items.reduce((s, i) => s + i.price * i.qty, 0),
    count: items.reduce((s, i) => s + i.qty, 0),
  };
}

// === Theme ===
function useTheme() {
  const [theme, setTheme] = useState(() => localStorage.getItem('te2000_theme') || 'light');
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem('te2000_theme', theme);
  }, [theme]);
  return [theme, setTheme];
}

// === Header ===
function Header({ active }) {
  const cart = useCart();
  const [theme, setTheme] = useTheme();
  return (
    <header className="site-header">
      <div className="container site-header__inner">
        <a href="index.html" className="brand">
          <span className="brand__title">Tour Eiffel 2000</span>
          <span className="brand__sub">Jean-Paul Lubliner · 365 jours</span>
        </a>
        <nav className="nav" aria-label="Principale">
          <a href="index.html" className={active === 'home' ? 'active' : ''}>Collection</a>
          <a href="portfolio.html" className={active === 'portfolio' ? 'active' : ''}>Les 365 photos</a>
          <a href="photographe.html" className={active === 'photo' ? 'active' : ''}>Photographe</a>
          <a href="expositions.html" className={active === 'expo' ? 'active' : ''}>Expositions</a>
          <a href="contact.html" className={active === 'contact' ? 'active' : ''}>Contact</a>
        </nav>
        <div className="header-actions">
          <button className="icon-btn" aria-label="Recherche" onClick={() => document.dispatchEvent(new CustomEvent('open-search'))}>
            <Icon.Search />
          </button>
          <button className="icon-btn" aria-label="Mode" onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
            {theme === 'light' ? <Icon.Moon /> : <Icon.Sun />}
          </button>
          <a href="panier.html" className="icon-btn" aria-label="Panier">
            <Icon.Cart />
            {cart.count > 0 && <span className="cart-count">{cart.count}</span>}
          </a>
        </div>
      </div>
    </header>
  );
}

// === Footer ===
function Footer() {
  return (
    <footer className="site-footer" itemScope itemType="https://schema.org/Organization">
      <div className="container">
        <div className="footer-grid">
          <div>
            <h4>Tour Eiffel 2000</h4>
            <p style={{fontFamily:'var(--serif)', fontSize:'1.4rem', fontStyle:'italic', lineHeight:1.3, color:'var(--ink-soft)', maxWidth: 380}}>
              « Un an de la vie d'une dame de fer, 365 portraits depuis la même fenêtre. »
            </p>
            <p style={{marginTop:24, fontSize:13, color:'var(--ink-mute)', maxWidth: 380}}>
              Collection de photographies d'art signée Jean-Paul Lubliner. Tirages numérotés en édition limitée à 30 exemplaires.
            </p>
          </div>
          <div>
            <h4>Collection</h4>
            <ul>
              <li><a href="portfolio.html">Les 365 photos</a></li>
              <li><a href="portfolio.html?season=hiver">Hiver</a></li>
              <li><a href="portfolio.html?season=printemps">Printemps</a></li>
              <li><a href="portfolio.html?season=été">Été</a></li>
              <li><a href="portfolio.html?season=automne">Automne</a></li>
            </ul>
          </div>
          <div>
            <h4>Boutique</h4>
            <ul>
              <li><a href="portfolio.html">Acheter un tirage</a></li>
              <li><a href="#">Formats & papiers</a></li>
              <li><a href="#">Encadrement</a></li>
              <li><a href="#">Livraison & retour</a></li>
              <li><a href="#">Authentification</a></li>
            </ul>
          </div>
          <div>
            <h4>Maison</h4>
            <ul>
              <li><a href="photographe.html">Le photographe</a></li>
              <li><a href="expositions.html">Expositions</a></li>
              <li><a href="contact.html">Contact</a></li>
              <li><a href="#">Presse</a></li>
              <li><a href="#">Newsletter</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Jean-Paul Lubliner · Tous droits réservés</span>
          <span>Paris · 75007</span>
        </div>
      </div>
    </footer>
  );
}

// === Photo card (with lazy image) ===
function PhotoCard({ photo, ratio = '3/4', showMeta = true }) {
  return (
    <a href={`photo.html?j=${photo.j}`} className="photo-card" aria-label={`Voir ${photo.title}`}>
      <div className="img-frame img-frame--hover" style={{aspectRatio: ratio}}>
        <img src={photo.url} alt={`Tour Eiffel — ${photo.dateLabel}, ${photo.light}, ${photo.weather}`} loading="lazy" />
      </div>
      {showMeta && (
        <div className="photo-card__meta">
          <span className="mono">J-{photo.j}</span>
          <span className="photo-card__date">{photo.dateLabel}</span>
        </div>
      )}
    </a>
  );
}

// === Search overlay ===
function SearchOverlay() {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState('');
  const inputRef = useRef(null);
  useEffect(() => {
    const onOpen = () => { setOpen(true); setTimeout(() => inputRef.current?.focus(), 60); };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('open-search', onOpen);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('open-search', onOpen);
      document.removeEventListener('keydown', onKey);
    };
  }, []);
  if (!open) return null;
  const num = parseInt(q.replace(/\D/g, ''), 10);
  const results = q
    ? PHOTOS.filter(p =>
        (num && p.j === num) ||
        p.dateLabel.toLowerCase().includes(q.toLowerCase()) ||
        p.season.includes(q.toLowerCase()) ||
        p.light.includes(q.toLowerCase()) ||
        p.mood.includes(q.toLowerCase())
      ).slice(0, 8)
    : PHOTOS.slice(0, 8);
  return (
    <div className="search-overlay" onClick={(e) => e.target === e.currentTarget && setOpen(false)}>
      <div className="search-overlay__panel">
        <div className="search-overlay__bar">
          <Icon.Search />
          <input
            ref={inputRef}
            value={q}
            onChange={e => setQ(e.target.value)}
            placeholder="Chercher un jour, une saison, une lumière, un numéro J-…"
          />
          <button className="icon-btn" onClick={() => setOpen(false)}><Icon.Close /></button>
        </div>
        <div className="search-overlay__results">
          {results.map(p => (
            <a key={p.j} href={`photo.html?j=${p.j}`} className="search-result">
              <div className="img-frame" style={{width: 60, aspectRatio: '3/4'}}>
                <img src={p.url} alt="" loading="lazy" />
              </div>
              <div>
                <div className="mono" style={{fontSize:11, letterSpacing:'0.15em', color:'var(--ink-mute)'}}>J-{p.j} · {p.dateLabel}</div>
                <div style={{fontFamily:'var(--serif)', fontSize:'1.2rem'}}>{p.mood} · {p.light}</div>
              </div>
            </a>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Icon, Header, Footer, PhotoCard, SearchOverlay, useCart, useTheme });
