/* ============================================
   Public Site Part 2 — Calculadora, Galería, Testimonios, Contacto, Footer, WhatsApp FAB
   ============================================ */

/* ============================================
   Calculadora
   ============================================ */
function Calculadora() {
  const [animalId, setAnimalId] = useState("lecheras");
  const [cantidad, setCantidad] = useState(80);
  const [meses, setMeses] = useState(6);

  const animal = window.DATA.ANIMALES.find(a => a.id === animalId);
  // proporción de alfalfa en la dieta (40-60%)
  const propAlfalfa = 0.5;
  const diasTotal = meses * 30;
  const kgTotal = animal.kg * propAlfalfa * cantidad * diasTotal;

  // distribución sugerida: 50% prismático chico, 30% redondo, 20% mega
  const fardosChico = Math.ceil((kgTotal * 0.5) / 25);
  const fardosRedondo = Math.ceil((kgTotal * 0.3) / 350);
  const fardosMega = Math.ceil((kgTotal * 0.2) / 500);

  const animalIcon = (id) => ({ lecheras: "Milk", cria: "Beef", caballos: "Rabbit", vaquillonas: "Beef" }[id] || "Beef");

  return (
    <section id="calculadora" className="section" data-screen-label="Calculadora">
      <div className="container">
        <div className="section-head">
          <div className="section-head__title">
            <div className="eyebrow">Calculadora</div>
            <h2 className="h-section" style={{ marginTop: 14 }}>¿Cuántos fardos necesitás?</h2>
          </div>
          <div className="section-head__aside">
            Estimación basada en consumo promedio de materia seca (50% de la dieta cubierta con alfalfa).
            Para un cálculo exacto, consultanos.
          </div>
        </div>

        <div className="calc">
          <div>
            <div className="calc__field">
              <label>Tipo de animal</label>
              <div className="animal-grid">
                {window.DATA.ANIMALES.map(a => (
                  <button key={a.id}
                    className={`animal-tile ${animalId === a.id ? "is-active" : ""}`}
                    onClick={() => setAnimalId(a.id)}>
                    <I name={animalIcon(a.id)} size={20} className="animal-tile__icon" />
                    <div className="animal-tile__main">
                      <span>{a.label}</span>
                      <span className="animal-tile__rate">{a.kg} kg MS / día</span>
                    </div>
                  </button>
                ))}
              </div>
            </div>

            <div className="calc__field">
              <label>Cantidad de animales — <strong style={{ color: "var(--green-800)" }}>{cantidad}</strong></label>
              <input type="range" min="5" max="500" value={cantidad}
                onChange={e => setCantidad(+e.target.value)}
                className="calc__input" style={{ padding: 0, accentColor: "#2d5016" }} />
            </div>

            <div className="calc__field">
              <label>Meses a cubrir — <strong style={{ color: "var(--green-800)" }}>{meses} {meses === 1 ? "mes" : "meses"}</strong></label>
              <input type="range" min="1" max="12" value={meses}
                onChange={e => setMeses(+e.target.value)}
                className="calc__input" style={{ padding: 0, accentColor: "#2d5016" }} />
            </div>
          </div>

          <div className="calc__result">
            <div className="calc__result-headline">Necesitarías aproximadamente</div>
            <div className="calc__total">
              {window.DATA.fmtNum(Math.round(kgTotal / 1000))} t
              <small>de alfalfa para {cantidad} {animal.label.toLowerCase()} durante {meses} {meses === 1 ? "mes" : "meses"}</small>
            </div>
            <div className="calc__breakdown">
              <div className="calc__break-row">
                <strong>{window.DATA.fmtNum(fardosChico)}</strong>
                <span>Prismáticos chicos (25kg)</span>
              </div>
              <div className="calc__break-row">
                <strong>{window.DATA.fmtNum(fardosRedondo)}</strong>
                <span>Redondos (350kg)</span>
              </div>
              <div className="calc__break-row">
                <strong>{window.DATA.fmtNum(fardosMega)}</strong>
                <span>Megafardos (500kg)</span>
              </div>
            </div>
            <a className="btn btn-wa" href="https://wa.me/5493564000000" target="_blank" style={{ alignSelf: "flex-start", marginTop: 8 }}>
              <I name="MessageCircle" size={15} /> Solicitar esta cantidad
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================
   Galería
   ============================================ */
function Galeria() {
  const tiles = [
    { cls: "gal-1 gal-tile--w2 gal-tile--h2", cap: "campo en floración" },
    { cls: "gal-2", cap: "atardecer en Los Talas" },
    { cls: "gal-3", cap: "megafardos apilados" },
    { cls: "gal-5", cap: "rotoenfardadora trabajando" },
    { cls: "gal-6 gal-tile--w2", cap: "stock galpón A" },
    { cls: "gal-4", cap: "tractor John Deere" },
    { cls: "gal-7 gal-tile--h2", cap: "equipo de campo 2025" },
    { cls: "gal-2", cap: "rastrillado matinal" },
    { cls: "gal-3 gal-tile--w2", cap: "carga para Pergamino" },
    { cls: "gal-1", cap: "fardo prismático" },
  ];

  return (
    <section id="galeria" className="section section--soft" data-screen-label="Galeria">
      <div className="container">
        <div className="section-head">
          <div className="section-head__title">
            <div className="eyebrow">Galería</div>
            <h2 className="h-section" style={{ marginTop: 14 }}>Una temporada en el campo.</h2>
          </div>
          <div className="section-head__aside">
            Imágenes de nuestra última campaña: siembra, corte, enfardado y entrega.
          </div>
        </div>
        <div className="gallery">
          {tiles.map((t, i) => (
            <div key={i} className={`gal-tile ${t.cls}`}>
              <div className="gal-tile__caption">{t.cap}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============================================
   Testimonios
   ============================================ */
function Testimonios() {
  const [idx, setIdx] = useState(0);
  const items = window.DATA.TESTIMONIOS;
  const cur = items[idx];

  useEffect(() => {
    const id = setInterval(() => setIdx(i => (i + 1) % items.length), 6500);
    return () => clearInterval(id);
  }, [items.length]);

  return (
    <section id="testimonios" className="testi" data-screen-label="Testimonios">
      <div className="testi__inner">
        <div className="eyebrow" style={{ color: "var(--gold-300)" }}>Lo que dicen los clientes</div>
        <div className="testi__quote" style={{ marginTop: 32 }} key={idx}>
          {cur.texto}
        </div>
        <div className="testi__author">
          <div className="testi__avatar">{cur.autor.split(" ").map(s=>s[0]).slice(0,2).join("")}</div>
          <div>
            <div className="testi__author-name">{cur.autor}</div>
            <div className="testi__author-meta">{cur.cargo}</div>
          </div>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 16 }}>
          <div className="testi__dots">
            {items.map((_, i) => (
              <div key={i} className={`testi__dot ${i === idx ? "is-active" : ""}`} onClick={() => setIdx(i)}></div>
            ))}
          </div>
          <div className="testi__nav">
            <button className="testi__nav-btn" onClick={() => setIdx((idx - 1 + items.length) % items.length)}><I name="ArrowLeft" size={18} /></button>
            <button className="testi__nav-btn" onClick={() => setIdx((idx + 1) % items.length)}><I name="ArrowRight" size={18} /></button>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================
   Contacto
   ============================================ */
function Contacto() {
  const [sent, setSent] = useState(false);
  const [form, setForm] = useState({ nombre: "", email: "", telefono: "", tipo: "tambo", mensaje: "" });

  const submit = (e) => {
    e.preventDefault();
    setSent(true);
    setTimeout(() => setSent(false), 5000);
    setForm({ nombre: "", email: "", telefono: "", tipo: "tambo", mensaje: "" });
  };

  const update = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

  return (
    <section id="contacto" className="section" data-screen-label="Contacto">
      <div className="container">
        <div className="section-head">
          <div className="section-head__title">
            <div className="eyebrow">Contacto</div>
            <h2 className="h-section" style={{ marginTop: 14 }}>Pedinos una cotización<br/>o contanos tu necesidad.</h2>
          </div>
          <div className="section-head__aside">
            Te respondemos en menos de 24 horas hábiles. También podés escribirnos directamente por WhatsApp.
          </div>
        </div>

        <div className="contact-grid">
          <form className="form" onSubmit={submit}>
            <div className="form__row">
              <div className="form__field">
                <label>Nombre</label>
                <input className="form__input" required value={form.nombre} onChange={update("nombre")} placeholder="Tu nombre" />
              </div>
              <div className="form__field">
                <label>Establecimiento</label>
                <select className="form__select" value={form.tipo} onChange={update("tipo")}>
                  <option value="tambo">Tambo</option>
                  <option value="cria">Cría / Recría</option>
                  <option value="haras">Haras / Equino</option>
                  <option value="otro">Otro</option>
                </select>
              </div>
            </div>
            <div className="form__row">
              <div className="form__field">
                <label>Email</label>
                <input className="form__input" type="email" required value={form.email} onChange={update("email")} placeholder="tu@email.com" />
              </div>
              <div className="form__field">
                <label>Teléfono</label>
                <input className="form__input" required value={form.telefono} onChange={update("telefono")} placeholder="+54 9 ..." />
              </div>
            </div>
            <div className="form__field">
              <label>Mensaje</label>
              <textarea className="form__textarea" value={form.mensaje} onChange={update("mensaje")} placeholder="Contanos qué cantidad y tipo de fardos necesitás, plazo de entrega, etc." />
            </div>
            <div style={{ display: "flex", gap: 12, alignItems: "center", marginTop: 8 }}>
              <button className="btn btn-primary" type="submit">
                Enviar consulta <I name="ArrowRight" size={16} />
              </button>
            </div>
            {sent && (
              <div className="form-toast" style={{ marginTop: 8 }}>
                <I name="CheckCircle2" size={18} />
                ¡Gracias! Recibimos tu mensaje. Te contactamos en las próximas 24 horas.
              </div>
            )}
          </form>

          <div className="contact-info">
            <div className="contact-info__item">
              <div className="contact-info__icon"><I name="Phone" size={18} /></div>
              <div>
                <div className="contact-info__label">Teléfono</div>
                <div className="contact-info__value">(03562) 49-1180<small>Lun a Sáb · 7 a 19 hs</small></div>
              </div>
            </div>
            <div className="contact-info__item">
              <div className="contact-info__icon"><I name="Mail" size={18} /></div>
              <div>
                <div className="contact-info__label">Email</div>
                <div className="contact-info__value">ventas@msamoro.com.ar<small>Pedidos y cotizaciones</small></div>
              </div>
            </div>
            <div className="contact-info__item">
              <div className="contact-info__icon"><I name="MapPin" size={18} /></div>
              <div>
                <div className="contact-info__label">Ubicación</div>
                <div className="contact-info__value">RP 13 km 47, Sacanta<small>Córdoba, Argentina · CP 2415</small></div>
              </div>
            </div>
            <div className="map">
              <div className="map__pin"></div>
              <div className="map__label">RP 13 km 47, Sacanta</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================
   Footer
   ============================================ */
function Footer({ onNav, onAdminClick }) {
  return (
    <footer className="footer">
      <div className="footer__inner">
        <div className="footer__top">
          <div className="footer__brand">
            <div className="brand">
              <BrandMark />
              <div>
                <div className="brand__name" style={{ color: "#fff" }}>MSA <span style={{ color: "var(--gold-300)" }}>Moro</span></div>
              </div>
            </div>
            <p>Forraje premium para tambos, cabañas y haras. Producimos en 1.200 ha en Sacanta, Córdoba.</p>
            <div className="footer__socials">
              <a href="#" aria-label="Instagram"><I name="Instagram" size={16} /></a>
              <a href="#" aria-label="Facebook"><I name="Facebook" size={16} /></a>
            </div>
          </div>
          <div>
            <h5>Navegar</h5>
            <ul>
              <li><a onClick={() => onNav("inicio")}>Inicio</a></li>
              <li><a onClick={() => onNav("nosotros")}>Nosotros</a></li>
              <li><a onClick={() => onNav("servicios")}>Servicios</a></li>
            </ul>
          </div>
          <div>
            <h5>Recursos</h5>
            <ul>
              <li><a onClick={() => onNav("galeria")}>Galería</a></li>
              <li><a onClick={() => onNav("contacto")}>Contacto</a></li>
              <li><a onClick={onAdminClick}>Acceso panel</a></li>
            </ul>
          </div>
          <div>
            <h5>Contacto</h5>
            <ul>
              <li>RP 13 km 47, Sacanta</li>
              <li>Córdoba, Argentina</li>
              <li>(03562) 49-1180</li>
              <li>ventas@msamoro.com.ar</li>
            </ul>
          </div>
        </div>
        <div className="footer__bottom">
          <div>© 2026 MSA Moro Servicios Agropecuarios · Todos los derechos reservados</div>
          <div>CUIT 30-71234567-8 · RENSPA 12.345.6.78901/00</div>
        </div>
      </div>
    </footer>
  );
}

/* ============================================
   WhatsApp FAB
   ============================================ */
function WhatsAppFab() {
  return (
    <a className="wa-fab" href="https://wa.me/5493564000000" target="_blank" aria-label="WhatsApp">
      <I name="MessageCircle" size={26} />
    </a>
  );
}

Object.assign(window, { Calculadora, Galeria, Testimonios, Contacto, Footer, WhatsAppFab });
