// extras.jsx — Funcionalidades extra: progress bar, search, cart, post detail, recipe detail, now playing, 404

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

// ============================================
// READING PROGRESS BAR
// ============================================
function ReadingProgress() {
  const [progress, setProgress] = useState(0);
  useEffect(() => {
    const onScroll = () => {
      const h = document.documentElement;
      const total = h.scrollHeight - h.clientHeight;
      setProgress(total > 0 ? (h.scrollTop / total) * 100 : 0);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return <div className="reading-progress" style={{ transform: `scaleX(${progress / 100})` }}></div>;
}

// ============================================
// COMMAND PALETTE (Cmd+K)
// ============================================
function CommandPalette() {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState('');
  const inputRef = useRef(null);

  useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        setOpen(o => !o);
      } else if (e.key === 'Escape') setOpen(false);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  useEffect(() => {
    if (open && inputRef.current) setTimeout(() => inputRef.current.focus(), 50);
    if (!open) setQuery('');
  }, [open]);

  const data = window.SITE_DATA;
  const items = [
    ...data.blog.map(p => ({ kind: 'Blog', title: p.title, sub: p.cat, href: '#blog' })),
    ...data.recipes.map(r => ({ kind: 'Receta', title: r.title, sub: r.cat, href: '#cocina' })),
    ...data.merch.map(m => ({ kind: 'Tienda', title: m.name, sub: m.price, href: '#merch' })),
    { kind: 'Ir a', title: 'Inicio', sub: 'Volver al hero', href: '#inicio' },
    { kind: 'Ir a', title: 'Sobre mí', sub: 'Conoce a Cristhy', href: '#sobre-mi' },
    { kind: 'Ir a', title: 'Newsletter', sub: 'Carta del domingo', href: '#newsletter' },
  ];
  const filtered = query
    ? items.filter(i => (i.title + ' ' + i.sub + ' ' + i.kind).toLowerCase().includes(query.toLowerCase()))
    : items.slice(0, 8);

  if (!open) return null;
  return (
    <div className="cmdk-backdrop" onClick={() => setOpen(false)}>
      <div className="cmdk" onClick={(e) => e.stopPropagation()}>
        <div className="cmdk-input">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="7"/><path d="M21 21l-5-5" strokeLinecap="round"/></svg>
          <input ref={inputRef} type="text" placeholder="Buscar posts, recetas, productos…" value={query} onChange={(e) => setQuery(e.target.value)} />
          <kbd>esc</kbd>
        </div>
        <div className="cmdk-list">
          {filtered.length === 0 && <div className="cmdk-empty">Sin resultados para "{query}"</div>}
          {filtered.map((i, idx) => (
            <a key={idx} href={i.href} className="cmdk-item" onClick={() => setOpen(false)}>
              <span className="cmdk-kind">{i.kind}</span>
              <div>
                <div className="cmdk-title">{i.title}</div>
                <div className="cmdk-sub">{i.sub}</div>
              </div>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </a>
          ))}
        </div>
        <div className="cmdk-footer">
          <span><kbd>↑</kbd><kbd>↓</kbd> navegar</span>
          <span><kbd>↵</kbd> abrir</span>
          <span><kbd>esc</kbd> cerrar</span>
        </div>
      </div>
    </div>
  );
}

// ============================================
// CART (localStorage)
// ============================================
function useCart() {
  const [items, setItems] = useState(() => {
    try { return JSON.parse(localStorage.getItem('cristhy-cart') || '[]'); } catch { return []; }
  });
  useEffect(() => {
    localStorage.setItem('cristhy-cart', JSON.stringify(items));
  }, [items]);

  const add = (product) => setItems(prev => {
    const idx = prev.findIndex(i => i.id === product.id);
    if (idx >= 0) {
      const copy = [...prev];
      copy[idx] = { ...copy[idx], qty: copy[idx].qty + 1 };
      return copy;
    }
    return [...prev, { ...product, qty: 1 }];
  });
  const remove = (id) => setItems(prev => prev.filter(i => i.id !== id));
  const clear = () => setItems([]);
  const total = items.reduce((s, i) => s + parseFloat(i.price) * i.qty, 0);

  return { items, add, remove, clear, total };
}

function CartDrawer({ cart, open, onClose }) {
  return (
    <React.Fragment>
      <div className={`cart-backdrop ${open ? 'open' : ''}`} onClick={onClose}></div>
      <aside className={`cart ${open ? 'open' : ''}`}>
        <header className="cart-head">
          <h3>Tu cesta</h3>
          <button className="cart-close" onClick={onClose} aria-label="Cerrar">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6l12 12M6 18L18 6"/></svg>
          </button>
        </header>
        <div className="cart-body">
          {cart.items.length === 0 ? (
            <div className="cart-empty">
              <span style={{ fontSize: 40 }}>✦</span>
              <p>Aún no has añadido nada.</p>
              <a href="#merch" onClick={onClose} className="btn-arrow">Ver tienda →</a>
            </div>
          ) : cart.items.map(i => (
            <div key={i.id} className="cart-item">
              <div className={`cart-thumb ${i.bg}`}>
                <ProductArt kind={i.art} />
              </div>
              <div className="cart-info">
                <h4>{i.name}</h4>
                <span className="cart-tag">{i.tag}</span>
                <div className="cart-row">
                  <span className="cart-qty">×{i.qty}</span>
                  <span className="cart-price">{i.price}</span>
                  <button onClick={() => cart.remove(i.id)} aria-label="Eliminar">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2M6 6l1 14a2 2 0 002 2h6a2 2 0 002-2l1-14"/></svg>
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
        {cart.items.length > 0 && (
          <footer className="cart-foot">
            <div className="cart-total">
              <span>Total</span>
              <span className="big">{cart.total.toFixed(2)}€</span>
            </div>
            <button className="btn btn-primary btn-pill" style={{ width: '100%', justifyContent: 'center' }}>
              Pagar — Stripe
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </button>
            <button className="cart-clear" onClick={cart.clear}>Vaciar cesta</button>
          </footer>
        )}
      </aside>
    </React.Fragment>
  );
}

function CartButton({ count, onClick }) {
  return (
    <button className="cart-btn" onClick={onClick} aria-label="Carrito">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
        <path d="M3 6h2l2.5 12a2 2 0 002 2h7a2 2 0 002-2L20 9H6" strokeLinecap="round" strokeLinejoin="round"/>
        <circle cx="9" cy="22" r="1"/><circle cx="17" cy="22" r="1"/>
      </svg>
      {count > 0 && <span className="cart-badge">{count}</span>}
    </button>
  );
}

// ============================================
// POST DETAIL MODAL
// ============================================
function PostDetail({ post, onClose }) {
  const [progress, setProgress] = useState(0);
  const bodyRef = useRef(null);
  useEffect(() => {
    const el = bodyRef.current;
    if (!el) return;
    const onScroll = () => {
      const total = el.scrollHeight - el.clientHeight;
      setProgress(total > 0 ? (el.scrollTop / total) * 100 : 0);
    };
    el.addEventListener('scroll', onScroll);
    return () => el.removeEventListener('scroll', onScroll);
  }, [post]);

  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = post ? 'hidden' : '';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [post, onClose]);

  if (!post) return null;

  const body = `Hace seis meses convertimos una furgoneta vieja en hogar. Pintamos las paredes interiores con cal, pusimos una cocina pequeña, una cama que mira al horizonte y un panel solar que ya nos ha dado más de un disgusto.

La libertad existe, sí. Pero también el panel solar que se rompe un martes a las 7 de la mañana cuando estás en mitad de la nada. La gente pregunta mucho por la parte instagramable: la luz dorada, los desayunos al sol, los lugares con nombre raro.

Yo voy a contar lo otro: el día que se nos coló agua por la claraboya, el día que mi pareja me miró con ojos de "vámonos a casa", el día que descubrimos que en una furgo no caben todas las cosas que crees que necesitas.

Vivir despacio en cuatro ruedas no es huir. Es elegir mejor qué te llevas.`;

  return (
    <div className="modal-overlay" onClick={onClose}>
      <article className="post-detail" onClick={(e) => e.stopPropagation()}>
        <div className="post-progress" style={{ transform: `scaleX(${progress / 100})` }}></div>
        <button className="modal-close" onClick={onClose}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6l12 12M6 18L18 6"/></svg>
        </button>
        <div ref={bodyRef} className="post-scroll">
          <div className="post-hero">
            <img src={post.img} alt={post.title} />
          </div>
          <div className="post-content">
            <div className="post-meta">
              <span className="cat">{post.cat}</span>
              <span>·</span>
              <span>{post.date}</span>
              <span>·</span>
              <span>{post.readTime} de lectura</span>
            </div>
            <h1>{post.title}</h1>
            <p className="post-lede">{post.excerpt}</p>
            {body.split('\n\n').map((para, i) => <p key={i}>{para}</p>)}
            <div className="post-share">
              <span>Compartir:</span>
              <a href="#">Twitter</a>
              <a href="#">Facebook</a>
              <a href="#">Copiar enlace</a>
            </div>
          </div>
        </div>
      </article>
    </div>
  );
}

// ============================================
// RECIPE DETAIL MODAL
// ============================================
function RecipeDetail({ recipe, onClose }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = recipe ? 'hidden' : '';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [recipe, onClose]);

  if (!recipe) return null;

  const ingredients = [
    '300g de harina',
    '200g de azúcar',
    '4 huevos camperos',
    '120ml de aceite de oliva virgen extra',
    'Ralladura de 2 limones',
    '1 yogur natural',
    'Levadura química',
    'Una pizca de sal',
  ];
  const steps = [
    'Precalienta el horno a 180°C con calor arriba y abajo.',
    'Mezcla los huevos con el azúcar hasta que blanqueen.',
    'Añade el aceite y el yogur. Bate suave.',
    'Incorpora la harina con la levadura tamizadas. La ralladura al final.',
    'Vuelca en molde engrasado. Hornea 45 minutos.',
    'Deja enfriar en el molde 10 minutos antes de desmoldar.',
  ];

  return (
    <div className="modal-overlay" onClick={onClose}>
      <article className="recipe-detail" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6l12 12M6 18L18 6"/></svg>
        </button>
        <div className="recipe-hero">
          <img src={recipe.img} alt={recipe.title} />
        </div>
        <div className="recipe-content">
          <span className="badge">{recipe.cat}</span>
          <h1>{recipe.title}</h1>
          <div className="recipe-stats">
            <div><span className="num">{recipe.time}</span><span className="lbl">Tiempo</span></div>
            <div><span className="num">6</span><span className="lbl">Raciones</span></div>
            <div><span className="num">Fácil</span><span className="lbl">Dificultad</span></div>
          </div>
          <div className="recipe-grid-2">
            <div>
              <h3>Ingredientes</h3>
              <ul className="recipe-ing">
                {ingredients.map((i, idx) => <li key={idx}><span className="dot"></span>{i}</li>)}
              </ul>
            </div>
            <div>
              <h3>Pasos</h3>
              <ol className="recipe-steps">
                {steps.map((s, idx) => <li key={idx}><span className="step-num">{String(idx + 1).padStart(2, '0')}</span><span>{s}</span></li>)}
              </ol>
            </div>
          </div>
          <div className="recipe-actions">
            <button className="btn btn-ghost btn-pill">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9V2h12v7M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2M6 14h12v8H6z"/></svg>
              Imprimir
            </button>
            <button className="btn btn-ghost btn-pill">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M19 14V6a2 2 0 00-2-2H7a2 2 0 00-2 2v8M19 14h2v6H3v-6h2M19 14H5"/></svg>
              Guardar
            </button>
          </div>
        </div>
      </article>
    </div>
  );
}

// ============================================
// NOW PLAYING WIDGET
// ============================================
function NowWidget() {
  const items = [
    { icon: '🍳', label: 'Cocinando', text: 'Bizcocho de limón' },
    { icon: '📖', label: 'Leyendo', text: 'El cuento de la criada' },
    { icon: '🎧', label: 'Escuchando', text: 'Lana del Rey · Honeymoon' },
    { icon: '🌿', label: 'Plantando', text: 'Tomates cherry' },
  ];
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setIdx(i => (i + 1) % items.length), 4000);
    return () => clearInterval(t);
  }, []);
  return (
    <div className="now-widget">
      <div className="now-pulse"></div>
      <div className="now-text">
        <span className="now-label">{items[idx].label} ahora</span>
        <span className="now-title">{items[idx].icon} {items[idx].text}</span>
      </div>
    </div>
  );
}

// ============================================
// EASTER EGG — gallinitas que cruzan
// ============================================
function ChickenEasterEgg() {
  const [chicken, setChicken] = useState(null);
  useEffect(() => {
    let last = 0;
    const onScroll = () => {
      if (Math.random() > 0.985 && Date.now() - last > 8000 && !chicken) {
        last = Date.now();
        setChicken({ id: Date.now(), top: 60 + Math.random() * 30 });
        setTimeout(() => setChicken(null), 6000);
      }
    };
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, [chicken]);

  if (!chicken) return null;
  return (
    <div className="chicken" style={{ top: chicken.top + 'vh' }}>
      <span style={{ fontSize: 32 }}>🐔</span>
      <span className="chicken-cluck">cloc cloc</span>
    </div>
  );
}

// Export
Object.assign(window, {
  ReadingProgress, CommandPalette, useCart, CartDrawer, CartButton,
  PostDetail, RecipeDetail, NowWidget, ChickenEasterEgg
});
