/* Home Page sections part 2 — Talleres, Insumos, Testimonios, Newsletter, Blog */

// Deterministic seeded rating: always same per id, varies 4.5-5.0
function seedRating(id) {
  const vals = ['4.5', '4.6', '4.7', '4.8', '4.9', '5.0'];
  return vals[(id * 7 + 3) % vals.length];
}

const WorkshopCard = ({ t, setPage }) => {
  const [showTemario, setShowTemario] = React.useState(false);
  const temarioItems = t.temario ? t.temario.split(', ').filter(Boolean) : [];
  return (
    <div className="card" style={{ cursor: 'default' }}>
      <div style={{ height: 180, position: 'relative', overflow: 'hidden', cursor: 'pointer' }} onClick={() => setPage && setPage('academia')}>
        <Img src={t.foto} alt={t.nombre} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
        <div style={{ position: 'absolute', top: 10, left: 10, display: 'flex', flexDirection: 'column', gap: 5 }}>
          <span style={{ fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 10, padding: '3px 9px', borderRadius: 'var(--r-p)', background: t.categoria === 'Panadería' ? 'var(--gr)' : 'var(--or)', color: '#fff' }}>{t.categoria}</span>
        </div>
        <span style={{ position: 'absolute', top: 10, right: 10, fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 10, padding: '3px 9px', borderRadius: 'var(--r-p)', background: 'rgba(255,255,255,0.95)', color: 'var(--or)' }}>Máx. {t.cupos} cupos</span>
      </div>
      <div style={{ padding: 16 }}>
        <div style={{ fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 11, color: 'var(--gr)', letterSpacing: '0.05em', textTransform: 'uppercase', display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 7 }}>
          {t.categoria} <span style={{ fontSize: 11, color: 'var(--t3)', display: 'flex', alignItems: 'center', gap: 3 }}><span style={{ color: 'var(--or)' }}>★</span>{seedRating(t.id)}</span>
        </div>
        <div style={{ fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 15, color: 'var(--t1)', marginBottom: 6, lineHeight: 1.3 }}>{t.nombre}</div>
        <div style={{ fontSize: 12, color: 'var(--t3)', lineHeight: 1.5, marginBottom: 10, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{t.descripcion}</div>
        <div style={{ display: 'flex', gap: 12, fontSize: 11, color: 'var(--t3)', marginBottom: 12 }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 3 }}><Icon name="clock" size={11} />{t.duracion}</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 3 }}><Icon name="users" size={11} />{t.cupos} personas</span>
        </div>
        {/* Temario dropdown */}
        {temarioItems.length > 0 && (
          <div style={{ marginBottom: 12 }}>
            <button onClick={() => setShowTemario(!showTemario)} style={{ background: showTemario ? 'var(--gr-lt)' : 'var(--bg)', border: '1px solid var(--bd)', borderRadius: 'var(--r)', padding: '7px 12px', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', fontFamily: 'var(--font-d)', fontWeight: 600, fontSize: 12, color: showTemario ? 'var(--gr-d)' : 'var(--t2)', transition: 'all 150ms' }}>
              <span>📋 Ver temario ({temarioItems.length} temas)</span>
              <span style={{ transform: showTemario ? 'rotate(90deg)' : 'rotate(0)', transition: 'transform 200ms', display: 'flex' }}><Icon name="chevRight" size={14} /></span>
            </button>
            {showTemario && (
              <div style={{ background: 'var(--bg)', border: '1px solid var(--bd)', borderTop: 'none', borderRadius: '0 0 var(--r) var(--r)', padding: '10px 12px', animation: 'slideUp 200ms ease-out' }}>
                {temarioItems.map((item, j) => (
                  <div key={j} style={{ display: 'flex', alignItems: 'flex-start', gap: 8, padding: '4px 0', fontSize: 12, color: 'var(--t2)' }}>
                    <span style={{ color: 'var(--gr)', fontWeight: 700, flexShrink: 0, marginTop: 1 }}>✓</span>
                    <span>{item}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 17, color: 'var(--t1)' }}>{formatPrice(t.precio)}<span style={{ fontSize: 10, color: 'var(--t3)', fontWeight: 400 }}> / persona</span></div>
          <a href={waLink(t.nombre)} target="_blank" rel="noopener noreferrer" className="btn btn-sm btn-green" onClick={e => e.stopPropagation()}>Inscribirme</a>
        </div>
      </div>
    </div>
  );
};

const TalleresPreview = ({ setPage }) => {
  const [filter, setFilter] = React.useState('Todos');
  const allTalleres = window.TALLERES_DATA || [];
  const destacados = React.useMemo(() => {
    const panNames = window.TALLERES_DESTACADOS_PANADERIA || [];
    const pasNames = window.TALLERES_DESTACADOS_PASTELERIA || [];
    return allTalleres.filter(t => [...panNames, ...pasNames].includes(t.nombre));
  }, [allTalleres]);

  const filtered = filter === 'Todos' ? destacados
    : filter === 'Panadería' ? destacados.filter(t => t.categoria === 'Panadería')
    : destacados.filter(t => t.categoria === 'Pastelería');

  return (
    <section style={{ background: '#fff' }}>
      <div className="container">
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 24 }}>
          <div>
            <span className="sec-label sec-label-green">Academia LK Mejia</span>
            <h2>Talleres que <span style={{ color: 'var(--gr)' }}>transforman</span></h2>
            <span className="heading-bar" style={{ background: 'var(--gr)' }}></span>
            <p style={{ maxWidth: 480 }}>Grupos pequeños, participación activa, técnicas reales. Aprende repostería de la manera correcta.</p>
          </div>
          <div style={{ background: '#FEF0DC', border: '1px solid #FAB968', borderRadius: 10, padding: '11px 16px', display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--or)', fontFamily: 'var(--font-d)', fontWeight: 600 }}>
            ⚡ ¡Alta demanda! Varios talleres con últimos cupos
          </div>
        </div>
        <div className="filters" style={{ marginBottom: 24 }}>
          {['Todos', 'Panadería', 'Pastelería'].map(f => (
            <button key={f} className={"filter-btn" + (filter === f ? " active" : "")} onClick={() => setFilter(f)}>{f}</button>
          ))}
        </div>
        <div className="grid-4">
          {filtered.map(t => <WorkshopCard key={t.id} t={t} setPage={setPage} />)}
        </div>
        <div style={{ textAlign: 'center', marginTop: 32 }}>
          <button className="btn btn-lg btn-outline-green" onClick={() => setPage('academia')}>
            Ver todos los talleres <Icon name="arrowRight" size={16} color="var(--gr)" />
          </button>
        </div>
      </div>
    </section>
  );
};

const ProductCard = ({ p }) => (
  <div className="card">
    <div style={{ height: 200, position: 'relative', overflow: 'hidden' }}>
      <Img src={p.foto} alt={p.nombre} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
      <span style={{ position: 'absolute', top: 10, left: 10, fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 10, padding: '4px 10px', borderRadius: 'var(--r-p)', background: 'var(--or)', color: '#fff' }}>{p.marca}</span>
    </div>
    <div style={{ padding: '16px 18px' }}>
      <div style={{ fontSize: 11, color: 'var(--t3)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
        <span>◉ {p.presentacion}</span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 3 }}><span style={{ color: 'var(--or)' }}>★</span>{seedRating(p.id)}</span>
      </div>
      <div style={{ fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 15, color: 'var(--t1)', marginBottom: 5 }}>{p.nombre}</div>
      <div style={{ fontSize: 12, color: 'var(--t3)', lineHeight: 1.5, marginBottom: 14, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{p.descripcion}</div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 20, color: 'var(--t1)' }}>{formatPrice(p.precio)}</div>
        <a href={waLink(p.nombre)} target="_blank" rel="noopener noreferrer" className="btn btn-sm btn-orange" onClick={e => e.stopPropagation()}>
          <WhatsAppIcon size={14} /> Pedir
        </a>
      </div>
    </div>
  </div>
);

const InsumosPreview = ({ setPage }) => {
  const [filter, setFilter] = React.useState('Todos');
  const allInsumos = window.INSUMOS_DATA || [];
  // Pick 2 products from each of the main categories for a balanced showcase
  const destacados = React.useMemo(() => {
    const picks = [];
    const mainCats = ['Chocolatería', 'Harinas y Mezclas', 'Herramientas'];
    mainCats.forEach(cat => {
      const items = allInsumos.filter(i => i.categoria === cat).slice(0, 2);
      picks.push(...items);
    });
    // Fill remaining slots with other categories
    if (picks.length < 6) {
      const rest = allInsumos.filter(i => !picks.includes(i)).slice(0, 6 - picks.length);
      picks.push(...rest);
    }
    return picks.slice(0, 6);
  }, [allInsumos]);

  const cats = ['Todos', 'Chocolatería', 'Harinas y Mezclas', 'Herramientas', 'Azúcares', 'Decoración'];
  const catIcons = { 'Chocolatería': 'coffee', 'Harinas y Mezclas': 'wheat', 'Decoración': 'palette', 'Herramientas': 'wrench', 'Azúcares': 'coffee' };

  const filtered = filter === 'Todos' ? destacados : (() => {
    const catItems = allInsumos.filter(i => i.categoria === filter).slice(0, 6);
    return catItems.length ? catItems : destacados;
  })();

  return (
    <section style={{ background: '#fff' }}>
      <div className="container">
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 24, flexWrap: 'wrap', gap: 12 }}>
          <div style={{ flex: '1 1 280px' }}>
            <span className="sec-label sec-label-orange">Tienda LK Mejia</span>
            <h2>Insumos con <span style={{ color: 'var(--or)' }}>asesoría técnica</span></h2>
            <span className="heading-bar" style={{ background: 'var(--or)' }}></span>
            <p style={{ maxWidth: 480 }}>Cada producto que vendemos está respaldado por expertise real. No vendemos por vender.</p>
          </div>
          <div style={{ background: '#EAF5D6', border: '1px solid var(--gr)', borderRadius: 'var(--r-p)', padding: '8px 16px', fontSize: 12, color: 'var(--gr-d)', fontFamily: 'var(--font-d)', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
            <Icon name="truck" size={14} color="var(--gr-d)" /> Envíos a toda Colombia
          </div>
        </div>
        <div className="filters" style={{ marginBottom: 24 }}>
          {cats.map(c => (
            <button key={c} className={"filter-btn filter-btn-or" + (filter === c ? " active" : "")} onClick={() => setFilter(c)}>
              {c !== 'Todos' && <Icon name={catIcons[c]} size={14} />}{c}
            </button>
          ))}
        </div>
        <div className="grid-3">
          {filtered.map(p => <ProductCard key={p.id} p={p} />)}
        </div>
        <div style={{ textAlign: 'center', marginTop: 32 }}>
          <button className="btn btn-lg btn-outline-orange" onClick={() => setPage('tienda')}>
            Ver todo el catálogo <Icon name="arrowRight" size={16} color="var(--or)" />
          </button>
          <p style={{ fontSize: 13, color: 'var(--t3)', marginTop: 8 }}>+300 productos en tienda física</p>
        </div>
        {/* Marcas */}
        <div style={{ marginTop: 40 }}>
          <MarcasLogos />
        </div>
      </div>
    </section>
  );
};

const TestimonialsSection = () => {
  const testimonials = [
    { text: "Excelente lugar, las clases son muy bien explicadas y Luis es un profesional increíble. Los insumos son de la mejor calidad.", name: "Carolina Ruiz", role: "Emprendedora repostera", bg: "var(--or)" },
    { text: "Los talleres son maravillosos, se aprende muchísimo en cada sesión. La atención personalizada marca toda la diferencia.", name: "Andrea Gómez", role: "Estudiante de pastelería", bg: "var(--gr)" },
    { text: "El mejor lugar para comprar insumos de repostería en Bogotá. La asesoría es inigualable, siempre te recomiendan lo mejor.", name: "Martha Sánchez", role: "Chef profesional", bg: "#89CFF0" },
    { text: "Tomé el diplomado de panadería y fue una experiencia transformadora. Los grupos pequeños hacen toda la diferencia.", name: "Diego Hernández", role: "Panadero artesanal", bg: "#FFB347" },
  ];
  return (
    <section style={{ background: 'var(--bg)' }}>
      <div className="container">
        <div style={{ textAlign: 'center', marginBottom: 40 }}>
          <span className="sec-label sec-label-green">Comunidad LK</span>
          <h2>Lo que dicen nuestros <span style={{ color: 'var(--gr)' }}>estudiantes</span></h2>
          <span className="heading-bar" style={{ background: 'var(--gr)', margin: '10px auto 20px' }}></span>
          <p>Más de <strong style={{ color: 'var(--t1)' }}>4.000 personas</strong> han transformado su pasión por la repostería con LK Mejia.</p>
        </div>
        <div className="grid-4">
          {testimonials.map((t, i) => (
            <div key={i} style={{ background: '#fff', borderRadius: 'var(--r-lg)', padding: 22, border: '1px solid var(--bd)' }}>
              <div style={{ color: 'var(--or)', fontSize: 14, letterSpacing: 2, marginBottom: 10 }}>★★★★★</div>
              <span style={{ fontFamily: 'Georgia,serif', fontSize: 32, color: 'var(--gr)', lineHeight: 1, display: 'block', marginBottom: 4 }}>"</span>
              <p style={{ fontSize: 13, color: 'var(--t2)', lineHeight: 1.6, marginBottom: 14 }}>{t.text}</p>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ width: 36, height: 36, borderRadius: '50%', background: t.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 12, color: '#fff', flexShrink: 0 }}>{t.name.split(' ').map(w => w[0]).join('').slice(0, 2)}</div>
                <div>
                  <div style={{ fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 13, color: 'var(--t1)' }}>{t.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--t3)' }}>{t.role}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

const NewsletterSection = () => {
  const [email, setEmail] = React.useState('');
  const [status, setStatus] = React.useState('idle');

  const submit = async () => {
    if (!email || !email.includes('@')) return;
    setStatus('loading');
    try {
      const SHEET_URL = "https://script.google.com/macros/s/AKfycbxPLACEHOLDER/exec";
      await fetch(SHEET_URL + "?email=" + encodeURIComponent(email) + "&ts=" + Date.now(), { method: 'GET', mode: 'no-cors' });
    } catch(e) {}
    setStatus('ok');
    setEmail('');
  };

  return (
    <div style={{ padding: '0 40px', marginTop: -20 }}>
      <div style={{ background: 'var(--gr)', padding: 'clamp(24px,4vw,44px) clamp(20px,4vw,48px)', borderRadius: 'var(--r-lg)', maxWidth: 1200, margin: '0 auto', display: 'flex', alignItems: 'center', gap: 32, flexWrap: 'wrap' }}>
        <div style={{ flex: '1 1 200px' }}>
          <div style={{ fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 'clamp(16px,2vw,22px)', color: '#fff', marginBottom: 6 }}>Únete a +4.000 reposteros</div>
          <div style={{ fontSize: 14, color: 'rgba(255,255,255,0.85)' }}>que reciben contenido educativo exclusivo cada semana.</div>
        </div>
        {status === 'ok' ? (
          <div style={{ flex: '1 1 200px', display: 'flex', alignItems: 'center', gap: 12, background: 'rgba(255,255,255,0.15)', borderRadius: 'var(--r-p)', padding: '12px 20px' }}>
            <Icon name="check" size={20} color="#fff" />
            <span style={{ fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 15, color: '#fff' }}>¡Suscrito exitosamente!</span>
          </div>
        ) : (
          <div style={{ flex: '1 1 260px', display: 'flex', background: '#fff', borderRadius: 'var(--r-p)', overflow: 'hidden', height: 46 }}>
            <input
              style={{ flex: 1, border: 'none', outline: 'none', padding: '0 16px', fontFamily: 'var(--font-b)', fontSize: 14, color: 'var(--t1)', minWidth: 0 }}
              placeholder="Tu correo electrónico"
              type="email"
              value={email}
              onChange={e => setEmail(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && submit()}
              disabled={status === 'loading'}
            />
            <button
              style={{ background: 'var(--or)', color: '#fff', fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 14, border: 'none', padding: '0 18px', cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0 }}
              onClick={submit}
              disabled={status === 'loading'}
            >
              {status === 'loading' ? '...' : 'Suscribirme'}
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

const BlogPreview = ({ setPage, setActiveArticle }) => {
  const allBlogs = window.BLOG_POSTS || [];
  const preview = allBlogs.slice(0, 3);
  const catColors = { Ingredientes: '#FEF0DC', Técnica: '#EAF5D6', Herramientas: '#E8F6FD', Recetas: '#FFE5B4' };

  const openArticle = (p) => {
    setActiveArticle(p);
    setPage('recetario');
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  return (
    <section style={{ background: 'var(--bg)' }}>
      <div className="container">
        <div style={{ textAlign: 'center', marginBottom: 36 }}>
          <span className="sec-label sec-label-orange">Recetas y Blog</span>
          <h2>Conocimiento que <span style={{ color: 'var(--or)' }}>transforma</span></h2>
          <span className="heading-bar" style={{ background: 'var(--or)', margin: '10px auto 20px' }}></span>
          <p style={{ maxWidth: 560, margin: '0 auto 10px' }}>Artículos técnicos, recetas adaptadas al contexto colombiano y la ciencia detrás de la repostería.</p>
        </div>
        <div className="grid-3">
          {preview.map((p, i) => (
            <div key={p.id} className="card" onClick={() => openArticle(p)} style={{ cursor: 'pointer' }}>
              <div style={{ height: 160, position: 'relative', overflow: 'hidden', background: `linear-gradient(135deg, ${catColors[p.cat] || '#FEF0DC'}, #fff)` }}>
                {p.imagen
                  ? <img src={p.imagen} alt={p.title} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                  : <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><div style={{ fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 42, color: 'var(--or)', opacity: 0.12 }}>LK</div></div>
                }
              </div>
              <div style={{ padding: 18 }}>
                <div style={{ fontSize: 11, color: 'var(--t3)', display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
                  <span>LKA Mejía</span><span>{p.cat}</span>
                </div>
                <div style={{ fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 15, color: 'var(--t1)', marginBottom: 7, lineHeight: 1.35 }}>{p.title}</div>
                <p style={{ fontSize: 13, color: 'var(--t3)', lineHeight: 1.5, marginBottom: 12, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{p.seo?.metaDesc || ''}</p>
                <span style={{ color: 'var(--or)', fontFamily: 'var(--font-d)', fontWeight: 700, fontSize: 13, display: 'flex', alignItems: 'center', gap: 5 }}>Leer artículo <Icon name="arrowRight" size={14} color="var(--or)" /></span>
              </div>
            </div>
          ))}
        </div>
        <div style={{ textAlign: 'center', marginTop: 28 }}>
          <button className="btn btn-lg btn-outline-orange" onClick={() => setPage('recetario')}>
            Ver todos los artículos ({allBlogs.length}) <Icon name="arrowRight" size={16} color="var(--or)" />
          </button>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { WorkshopCard, TalleresPreview, ProductCard, InsumosPreview, TestimonialsSection, NewsletterSection, BlogPreview });
