/* global React, Placeholder, SectionHead, StarRow, SkylineGlyph */

// ───────────── BOUTIQUE ─────────────
const PRODUCTS = [
  { id: 'p1', name: 'Red One Bright White Wax', cat: 'Estilizado', price: 13000, desc: 'Aqua Hair Wax Maximum Control. Acabado brillante, fijación firme. 150ml.', benefits: ['Full Force', 'Brillo alto'], img: 'uploads/redone-bright-white-wax.jpg' },
  { id: 'p2', name: 'Red One Silver Cologne', cat: 'Estilizado', price: 13000, desc: 'Cologne Body Splash Silver. Fragancia fresca y amaderada, sin alcohol. 400ml.', benefits: ['Sin alcohol', 'Silver 400ml'], img: 'uploads/redone-silver-cologne.jpg' },
  { id: 'p3', name: 'Red One After Shave Fresh', cat: 'Barba', price: 13000, desc: 'Crema colonia post-afeitado. Face Fresh, aroma mentolado fresco. 400ml.', benefits: ['Sin irritación', 'Fresh 400ml'], img: 'uploads/redone-aftershave-fresh.jpg' },
  { id: 'p4', name: 'Red One Black Wax', cat: 'Estilizado', price: 13000, desc: 'Aqua Hair Gel Wax Maximum Control. Full Force, 150ml.', benefits: ['Control 10/10', 'Full Force'], img: 'uploads/redone-black-wax.jpg' },
  { id: 'p5', name: 'Red One Violetta Wax', cat: 'Estilizado', price: 13000, desc: 'Aqua Hair Gel Wax Maximum Control. Fijación potente con aroma Violetta. 150ml.', benefits: ['Full Force', 'Violetta 150ml'], img: 'uploads/redone-violetta-wax.jpg' },
  { id: 'p6', name: 'Red One Spider Spray', cat: 'Cabello', price: 13000, desc: 'Spider Hair Styling Spray Full Force 06. Super Firm, solo profesionales. Efecto araña.', benefits: ['Super Firm', 'Spray 400ml'], img: 'uploads/redone-spider-spray.jpg' },
  { id: 'p7', name: 'Red One Gold Cologne', cat: 'Estilizado', price: 13000, desc: 'Cologne Body Splash Gold. Fragancia dorada, sin alcohol. Apta todo tipo de piel.', benefits: ['Sin alcohol', 'Gold · 400ml'], img: 'uploads/redone-gold-cologne.jpg' },
  { id: 'p8', name: 'Red One Orange Wax', cat: 'Estilizado', price: 13000, desc: 'Aqua Hair Gel Wax Maximum Control. Fijación extrema con aroma cítrico naranja. 150ml.', benefits: ['Full Force', 'Orange 150ml'], img: 'uploads/redone-orange-wax.jpg' },
];

const Boutique = () => {
  const [filter, setFilter] = React.useState('Todos');
  const [cart, setCart] = React.useState({}); // { [productId]: qty }
  const [nombre, setNombre] = React.useState('');
  const [telefono, setTelefono] = React.useState('');
  const [enviando, setEnviando] = React.useState(false);
  const [error, setError] = React.useState('');
  const [enviado, setEnviado] = React.useState(false);

  const cats = ['Todos', 'Cabello', 'Barba', 'Estilizado', 'Tratamientos'];
  const items = PRODUCTS.filter(p => filter === 'Todos' || p.cat === filter);

  const addToCart = (id) => {
    setEnviado(false);
    setCart(prev => ({ ...prev, [id]: (prev[id] || 0) + 1 }));
  };

  const removeFromCart = (id) => {
    setCart(prev => {
      const next = { ...prev };
      if (next[id] <= 1) { delete next[id]; } else { next[id] -= 1; }
      return next;
    });
  };

  const cartEntries = Object.entries(cart)
    .map(([id, qty]) => ({ product: PRODUCTS.find(p => p.id === id), qty }))
    .filter(e => e.product);
  const cartCount = cartEntries.reduce((sum, e) => sum + e.qty, 0);
  const cartTotal = cartEntries.reduce((sum, e) => sum + e.qty * e.product.price, 0);

  const confirmarPedido = async () => {
    setError('');
    if (cartEntries.length === 0) {
      setError('Agrega al menos un producto.');
      return;
    }
    if (!nombre.trim() || !telefono.trim()) {
      setError('Completa tu nombre y teléfono para el pedido.');
      return;
    }
    const itemsPayload = cartEntries.map(e => ({ name: e.product.name, qty: e.qty, price: e.product.price }));
    setEnviando(true);
    try {
      await fetch('/guardar-pedido.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          cliente_nombre: nombre.trim(),
          cliente_telefono: telefono.trim(),
          items: itemsPayload,
          total: cartTotal,
        }),
      });
    } catch (e) {
      // Si falla el guardado igual dejamos que el cliente confirme por WhatsApp.
    }
    setEnviando(false);
    setEnviado(true);
    const lineas = cartEntries.map(e => `• ${e.qty}x ${e.product.name} — $${(e.qty * e.product.price).toLocaleString('es-CL')}`).join('\n');
    const texto = `Hola! Quiero pedir:\n${lineas}\n\nTotal: $${cartTotal.toLocaleString('es-CL')}\nNombre: ${nombre.trim()}`;
    window.open(`https://wa.me/56984740024?text=${encodeURIComponent(texto)}`, '_blank', 'noreferrer');
    setCart({});
  };

  const pagarPedidoConTarjeta = async () => {
    setError('');
    if (cartEntries.length === 0) {
      setError('Agrega al menos un producto.');
      return;
    }
    if (!nombre.trim() || !telefono.trim()) {
      setError('Completa tu nombre y teléfono para el pedido.');
      return;
    }
    const itemsPayload = cartEntries.map(e => ({ name: e.product.name, qty: e.qty, price: e.product.price }));
    setEnviando(true);
    try {
      const res = await fetch('/guardar-pedido.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          cliente_nombre: nombre.trim(),
          cliente_telefono: telefono.trim(),
          items: itemsPayload,
          total: cartTotal,
        }),
      });
      const data = await res.json();
      if (!data || !data.id) throw new Error('sin id');
      const form = document.createElement('form');
      form.method = 'POST';
      form.action = '/pago/iniciar.php';
      form.style.display = 'none';
      form.innerHTML =
        '<input type="hidden" name="tipo" value="pedido">' +
        '<input type="hidden" name="id" value="' + data.id + '">';
      document.body.appendChild(form);
      form.submit();
    } catch (e) {
      setEnviando(false);
      setError('No se pudo iniciar el pago con tarjeta. Intenta de nuevo o confirma por WhatsApp.');
    }
  };

  return (
    <section id="boutique" className="bb-section bb-section--paper">
      <SectionHead
        num="03"
        title="Boutique"
        subtitle="Curaduría de productos que usamos en la silla. Llévate el ritual a casa."
      />

      {/* Category rail */}
      <div className="bb-rail" style={{ marginBottom: 22 }}>
        {cats.map(c => (
          <button
            key={c}
            onClick={() => setFilter(c)}
            className={'bb-chip' + (filter === c ? ' bb-chip--active' : '')}
            style={{ cursor: 'pointer' }}
          >
            {c}
          </button>
        ))}
      </div>

      {/* Product grid */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        {items.map(p => (
          <ProductCard key={p.id} product={p} qty={cart[p.id] || 0} onAdd={() => addToCart(p.id)} />
        ))}
      </div>

      <div style={{ textAlign: 'center', marginTop: 28 }}>
        <div className="bb-label" style={{ color: 'var(--muted)' }}>
          {items.length} de {PRODUCTS.length} piezas · más en camino
        </div>
      </div>

      {/* Carrito / pedido */}
      {cartEntries.length > 0 && (
        <div style={{
          marginTop: 28,
          padding: '18px 16px',
          background: 'var(--ink)',
          color: 'var(--bg)',
        }}>
          <div className="bb-label" style={{ color: 'var(--gold)', marginBottom: 12 }}>
            — TU PEDIDO ({cartCount}) —
          </div>

          {cartEntries.map(e => (
            <div key={e.product.id} style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              padding: '8px 0',
              borderBottom: '1px solid rgba(250,248,243,0.1)',
              gap: 10,
            }}>
              <span style={{ flex: 1, fontFamily: 'Inter', fontSize: 13 }}>{e.product.name}</span>
              <button onClick={() => removeFromCart(e.product.id)} style={{
                width: 22, height: 22, border: '1px solid rgba(250,248,243,0.3)', background: 'transparent',
                color: 'var(--bg)', cursor: 'pointer', fontSize: 13, lineHeight: 1,
              }}>−</button>
              <span className="bb-label" style={{ minWidth: 18, textAlign: 'center' }}>{e.qty}</span>
              <button onClick={() => addToCart(e.product.id)} style={{
                width: 22, height: 22, border: '1px solid rgba(250,248,243,0.3)', background: 'transparent',
                color: 'var(--bg)', cursor: 'pointer', fontSize: 13, lineHeight: 1,
              }}>+</button>
              <span style={{ fontFamily: "'Cormorant Garamond', serif", fontStyle: 'italic', fontSize: 15, minWidth: 64, textAlign: 'right' }}>
                ${(e.qty * e.product.price).toLocaleString('es-CL')}
              </span>
            </div>
          ))}

          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
            padding: '12px 0 6px',
          }}>
            <span className="bb-label" style={{ color: 'rgba(250,248,243,0.5)' }}>Total</span>
            <span style={{ fontFamily: "'Cormorant Garamond', serif", fontStyle: 'italic', fontSize: 22, color: 'var(--gold)' }}>
              ${cartTotal.toLocaleString('es-CL')}
            </span>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 12 }}>
            <input
              type="text"
              placeholder="Nombre completo"
              value={nombre}
              onChange={(e) => setNombre(e.target.value)}
              style={{ padding: '12px 14px', border: '1px solid rgba(250,248,243,0.2)', background: 'rgba(250,248,243,0.05)', color: 'var(--bg)', fontFamily: 'Inter, sans-serif', fontSize: 14 }}
            />
            <input
              type="tel"
              placeholder="Teléfono (WhatsApp)"
              value={telefono}
              onChange={(e) => setTelefono(e.target.value)}
              style={{ padding: '12px 14px', border: '1px solid rgba(250,248,243,0.2)', background: 'rgba(250,248,243,0.05)', color: 'var(--bg)', fontFamily: 'Inter, sans-serif', fontSize: 14 }}
            />
          </div>

          {error && <div style={{ color: '#ff9d9d', fontSize: 12, marginTop: 10 }}>{error}</div>}
          {enviado && !error && <div style={{ color: '#bdf5cd', fontSize: 12, marginTop: 10 }}>¡Pedido enviado! Te contactaremos por WhatsApp.</div>}

          <button
            onClick={confirmarPedido}
            disabled={enviando}
            className="bb-btn bb-btn--gold bb-btn--block"
            style={{ marginTop: 16, border: 0, cursor: enviando ? 'default' : 'pointer', opacity: enviando ? 0.7 : 1 }}
          >
            {enviando ? 'Enviando…' : 'Confirmar pedido por WhatsApp'}
          </button>
          <button
            onClick={pagarPedidoConTarjeta}
            disabled={enviando}
            className="bb-btn bb-btn--card bb-btn--block"
            style={{ marginTop: 8, cursor: enviando ? 'default' : 'pointer', opacity: enviando ? 0.7 : 1 }}
          >
            Pagar ahora con tarjeta
          </button>
        </div>
      )}
    </section>
  );
};

const ProductCard = ({ product, qty, onAdd }) => (
  <div className="bb-lift" style={{
    background: 'var(--bg)',
    border: '1px solid var(--line-soft)',
    display: 'flex', flexDirection: 'column',
  }}>
    <div style={{ position: 'relative' }}>
      {product.img
        ? <img
            src={product.img}
            alt={product.name}
            style={{ width: '100%', height: 150, objectFit: 'cover', display: 'block', background: '#fff' }}
          />
        : <Placeholder label={product.name.toUpperCase()} height={150} />
      }
      <div style={{
        position: 'absolute', top: 8, left: 8,
        background: 'var(--paper)',
        padding: '3px 8px',
        borderLeft: '2px solid var(--gold)',
      }}>
        <span className="bb-label" style={{ color: 'var(--ink)' }}>{product.cat}</span>
      </div>
    </div>
    <div style={{ padding: '12px 12px 14px', flex: 1, display: 'flex', flexDirection: 'column' }}>
      <div style={{
        fontFamily: "'Cormorant Garamond', serif",
        fontSize: 17, fontWeight: 500,
        lineHeight: 1.1,
      }}>
        {product.name}
      </div>
      <div className="bb-small" style={{ marginTop: 6, fontSize: 11, lineHeight: 1.45 }}>
        {product.desc}
      </div>
      <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginTop: 8 }}>
        {product.benefits.map(b => (
          <span key={b} className="bb-label" style={{
            background: 'var(--bg-soft)',
            padding: '2px 6px', fontSize: 7,
            color: 'var(--ink-soft)',
          }}>{b}</span>
        ))}
      </div>
      <div style={{
        marginTop: 12,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div style={{
          fontFamily: "'Cormorant Garamond', serif",
          fontStyle: 'italic',
          fontSize: 18,
        }}>
          ${product.price.toLocaleString('es-CL')}
        </div>
        <button
          onClick={onAdd}
          style={{
            minWidth: 28, height: 28, padding: '0 8px',
            border: '1px solid var(--ink)',
            background: 'var(--ink)',
            color: 'var(--bg)',
            cursor: 'pointer',
            fontSize: 14, lineHeight: 1,
            fontFamily: "'JetBrains Mono', monospace",
          }}
        >
          {qty > 0 ? `+ (${qty})` : '+'}
        </button>
      </div>
    </div>
  </div>
);

// ───────────── GALERÍA ─────────────
const GaleriaTile = ({ img, label, tall, dark }) => (
  img
    ? <img
        className="bb-lift"
        src={img}
        alt={label}
        style={{
          width: '100%',
          height: tall ? 300 : 160,
          objectFit: 'cover',
          display: 'block',
          gridRow: tall ? 'span 2' : 'span 1',
        }}
      />
    : <Placeholder
        label={label}
        height={tall ? 300 : 160}
        dark={dark}
        style={{ gridRow: tall ? 'span 2' : 'span 1' }}
        className="bb-lift"
      />
);

const Galeria = () => {
  const tiles = [
    { label: 'Local · Fachada', tall: true },
    { label: 'Estación 01' },
    { img: 'uploads/galeria-fade-barba.jpg', label: 'Fade + barba' },
    { label: 'Antes / Después', dark: true },
    { img: 'uploads/galeria-fade-taper.jpg', label: 'Fade taper', tall: true },
    { label: 'Detalle navaja' },
    { label: 'Boutique · Estante' },
  ];
  return (
    <section id="galeria" className="bb-section">
      <SectionHead num="04" title="Galería" subtitle="Trabajos, local y detalles capturados en la silla." />
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr',
        gap: 6, gridAutoFlow: 'dense',
      }}>
        {tiles.map((t, i) => (
          <GaleriaTile key={i} {...t} />
        ))}
      </div>
    </section>
  );
};

// ───────────── TESTIMONIOS ─────────────
const TESTIMONIES = [
  { name: 'Tomás V.', role: 'Cliente · 2 años', text: 'La atención al detalle es otra liga. Salí no solo con un corte impecable, sino con un ritual.', stars: 5 },
  { name: 'Diego A.', role: 'Cliente nuevo', text: 'Me atendió Matías. Conversación, café y el mejor fade de Coquimbo. Volveré sin duda.', stars: 5 },
  { name: 'Javier M.', role: 'Cliente · 1 año', text: 'Compré la pomada mate después del corte y se nota la diferencia. Boutique con criterio.', stars: 5 },
];

const Testimonios = () => (
  <section id="testimonios" className="bb-section bb-section--ink" style={{ position: 'relative', overflow: 'hidden' }}>
    <div style={{ position: 'absolute', top: 0, left: 0, right: 0, opacity: 0.7 }}>
      <SkylineGlyph height={54} color="rgba(184,146,74,0.16)" />
    </div>
    <SectionHead title="Voces" subtitle="Lo que cuentan quienes pasan por la silla." light />
    <div className="bb-rail" style={{ paddingBottom: 8 }}>
      {TESTIMONIES.map((t, i) => (
        <div key={i} className="bb-lift" style={{
          width: 280,
          background: 'rgba(250,248,243,0.04)',
          border: '1px solid rgba(184,146,74,0.3)',
          padding: '20px',
          display: 'flex', flexDirection: 'column', gap: 14,
        }}>
          <div style={{
            fontFamily: "'Cormorant Garamond', serif",
            fontStyle: 'italic',
            fontSize: 28, lineHeight: 1,
            color: 'var(--gold)',
          }}>"</div>
          <p style={{
            fontFamily: "'Cormorant Garamond', serif",
            fontStyle: 'italic',
            fontSize: 18, lineHeight: 1.35,
            color: 'var(--bg)',
            margin: 0,
          }}>
            {t.text}
          </p>
          <StarRow value={t.stars} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 6 }}>
            <Placeholder label="" height={36} style={{ width: 36, borderRadius: '50%' }} dark />
            <div>
              <div style={{ fontFamily: 'Inter', fontSize: 13, color: 'var(--bg)' }}>{t.name}</div>
              <div className="bb-label" style={{ color: 'rgba(250,248,243,0.5)', marginTop: 2 }}>
                {t.role}
              </div>
            </div>
          </div>
        </div>
      ))}
    </div>

    {/* Video testimonial placeholder */}
    <div style={{ marginTop: 22, padding: '0 4px' }}>
      <div className="bb-label" style={{ color: 'rgba(250,248,243,0.5)', marginBottom: 8, textAlign: 'center' }}>
        — Video destacado —
      </div>
      <div style={{ position: 'relative' }}>
        <Placeholder label="Video · 1:24" height={180} dark style={{ border: '1px solid rgba(184,146,74,0.4)' }} />
        <div style={{
          position: 'absolute', inset: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <div style={{
            width: 56, height: 56,
            borderRadius: '50%',
            border: '1px solid var(--gold)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            background: 'rgba(20,17,12,0.5)',
          }}>
            <div style={{
              width: 0, height: 0,
              borderLeft: '12px solid var(--gold)',
              borderTop: '8px solid transparent',
              borderBottom: '8px solid transparent',
              marginLeft: 4,
            }} />
          </div>
        </div>
      </div>
    </div>
  </section>
);

Object.assign(window, { Boutique, Galeria, Testimonios, PRODUCTS, TESTIMONIES });
