/* parts/sections-bottom.jsx — About, FAQ, Contact, Footer, CartDrawer */
const { useState } = React;

function About() {
  return (
    <section className="section about" id="about">
      <div className="wrap">
        <div className="about-card reveal">
          <div className="glow"></div>
          <div className="about-grid">
            <div>
              <span className="eyebrow" style={{ color: 'var(--accent-2)' }}>Über Ice Cup</span>
              <h2 style={{ marginTop: '14px' }}>Eis als Geschäft,<br />einfach gemacht.</h2>
              <p>Ice Cup macht verkaufsfertiges Würfeleis für Schweizer Betriebe zugänglich. Unsere Mission: Gastronomie, Detailhandel und Events zuverlässig mit Swiss-Made-Eis beliefern – frisch, hygienisch und ohne Aufwand.</p>
            </div>
            <div className="about-stats">
              <div className="about-stat"><b>1 MIO.+</b><span>Becher geliefert</span></div>
              <div className="about-stat"><b>150+</b><span>Partner schweizweit</span></div>
              <div className="about-stat"><b>100%</b><span>Swiss Made</span></div>
              <div className="about-stat"><b>3 CM</b><span>VOLLEISWÜRFEL</span></div>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

function FaqItem({ item, open, onToggle }) {
  const ref = React.useRef(null);
  return (
    <div className={"faq-item" + (open ? " open" : "")}>
      <button className="faq-q" onClick={onToggle} aria-expanded={open}>
        <span>{item.q}</span>
        <span className="faq-ic"><IcPlus s={16} /></span>
      </button>
      <div className="faq-a" style={{ maxHeight: open ? (ref.current ? ref.current.scrollHeight + 0 : 400) + 'px' : '0px' }}>
        <div className="faq-a-inner" ref={ref}>{item.a}</div>
      </div>
    </div>);

}

function FAQ() {
  const [open, setOpen] = useState(0);
  return (
    <section className="section" id="faq">
      <div className="wrap">
        <div className="sec-head center reveal">
          <span className="eyebrow">GUT ZU WISSEN</span>
          <h2 className="section-title">Questions, chilled.</h2>
        </div>
        <div className="faq reveal">
          {FAQS.map((f, i) =>
          <FaqItem key={i} item={f} open={open === i} onToggle={() => setOpen(open === i ? -1 : i)} />
          )}
        </div>
      </div>
    </section>);

}

const RECAPTCHA_SITE_KEY = '6LccXx4tAAAAALssGBSbQh66jLHs2BxLSCRCBGQa';

function Contact() {
  const [form, setForm] = useState({ firma: '', vorname: '', nachname: '', email: '', telefon: '', strasse: '', plz: '', ort: '', uid: '', bemerkungen: '' });
  const [errors, setErrors] = useState({});
  const [sent, setSent] = useState(false);
  const [sending, setSending] = useState(false);
  const [serverError, setServerError] = useState(null);
  const set = (k, v) => {setForm((s) => ({ ...s, [k]: v }));if (errors[k]) setErrors((e) => ({ ...e, [k]: null }));};
  const submit = async (e) => {
    e.preventDefault();
    const err = {};
    if (!form.firma.trim()) err.firma = 'Firma erforderlich';
    if (!form.vorname.trim()) err.vorname = 'Vorname erforderlich';
    if (!form.nachname.trim()) err.nachname = 'Nachname erforderlich';
    if (!form.email.trim()) err.email = 'E-Mail erforderlich';else
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) err.email = 'E-Mail ungültig';
    if (!form.telefon.trim()) err.telefon = 'Telefonnummer erforderlich';
    if (!form.strasse.trim()) err.strasse = 'Bitte Strasse und Hausnummer angeben';
    if (!form.plz.trim()) err.plz = 'PLZ fehlt';
    if (!form.ort.trim()) err.ort = 'Ort fehlt';
    if (form.uid.trim() && !/^CHE-?\d{3}\.?\d{3}\.?\d{3}$/i.test(form.uid.trim())) err.uid = 'Format: CHE-123.456.789';
    setErrors(err);
    if (Object.keys(err).length > 0) return;
    setSending(true);
    setServerError(null);
    try {
      const token = await new Promise((resolve, reject) =>
        grecaptcha.ready(() =>
          grecaptcha.execute(RECAPTCHA_SITE_KEY, { action: 'contact' }).then(resolve).catch(reject)
        )
      );
      const body = new URLSearchParams({ ...form, recaptcha_token: token });
      const res = await fetch('send.php', { method: 'POST', body });
      const data = await res.json();
      if (data.ok) {
        setSent(true);
        setForm({ firma: '', vorname: '', nachname: '', email: '', telefon: '', strasse: '', plz: '', ort: '', uid: '', bemerkungen: '' });
      } else {
        setServerError(data.error || 'Unbekannter Fehler. Bitte versuche es erneut.');
      }
    } catch {
      setServerError('Verbindungsfehler. Bitte überprüfe deine Internetverbindung.');
    } finally {
      setSending(false);
    }
  };
  return (
    <section className="section" id="contact">
      <div className="wrap">
        <div className="contact-card reveal">
          <div className="contact-aside">
            <div className="c-glow"></div>
            <div>
              <span className="eyebrow" style={{ color: '#fff', opacity: 0.85 }}>Partner werden</span>
              <h2 style={{ marginTop: '14px' }}>Werde Ice Cup Partner.</h2>
              <p>Hinterlasse deine Angaben – wir melden uns innerhalb eines Werktages mit Konditionen, Sortiment und Liefermöglichkeiten für deinen Betrieb.</p>
            </div>
            <div className="contact-meta">
              <div><IcArrow s={15} /> info@icecup.ch</div>
              <div><IcArrow s={15} /> Lenzburgerstrasse 2 · 5702 Niederlenz</div>
              <div><IcArrow s={15} /> Swiss Made · Schweiz</div>
            </div>
          </div>
          <form className="contact-form" onSubmit={submit} noValidate>
            {sent && <div className="form-ok"><IcCheck /> Danke! Deine Angaben sind eingegangen — wir melden uns in Kürze.</div>}
            {serverError && <div className="form-err">{serverError}</div>}
            <div className={"field" + (errors.firma ? " err" : "")}>
              <label>Firma</label>
              <input value={form.firma} onChange={(e) => set('firma', e.target.value)} placeholder="Muster AG" />
              {errors.firma && <span className="msg">{errors.firma}</span>}
            </div>
            <div className="field-row">
              <div className={"field" + (errors.vorname ? " err" : "")}>
                <label>Vorname</label>
                <input value={form.vorname} onChange={(e) => set('vorname', e.target.value)} placeholder="Max" />
                {errors.vorname && <span className="msg">{errors.vorname}</span>}
              </div>
              <div className={"field" + (errors.nachname ? " err" : "")}>
                <label>Nachname</label>
                <input value={form.nachname} onChange={(e) => set('nachname', e.target.value)} placeholder="Muster" />
                {errors.nachname && <span className="msg">{errors.nachname}</span>}
              </div>
            </div>
            <div className={"field" + (errors.email ? " err" : "")}>
              <label>E-Mail Adresse</label>
              <input type="email" value={form.email} onChange={(e) => set('email', e.target.value)} placeholder="max@email.com" />
              {errors.email && <span className="msg">{errors.email}</span>}
            </div>
            <div className="field-row">
              <div className={"field" + (errors.telefon ? " err" : "")}>
                <label>Telefonnummer</label>
                <input type="tel" value={form.telefon} onChange={(e) => set('telefon', e.target.value)} placeholder="+41 79 000 00 00" />
                {errors.telefon && <span className="msg">{errors.telefon}</span>}
              </div>
              <div className={"field" + (errors.uid ? " err" : "")}>
                <label>UID-CHE Nummer <span className="opt">(optional)</span></label>
                <input value={form.uid} onChange={(e) => set('uid', e.target.value)} placeholder="CHE-123.456.789" />
                {errors.uid && <span className="msg">{errors.uid}</span>}
              </div>
            </div>
            <div className={"field" + (errors.strasse ? " err" : "")}>
              <label>Strasse und Hausnummer</label>
              <input value={form.strasse} onChange={(e) => set('strasse', e.target.value)} placeholder="Musterstrasse 12" />
              {errors.strasse && <span className="msg">{errors.strasse}</span>}
            </div>
            <div className="field-row plz-ort">
              <div className={"field" + (errors.plz ? " err" : "")}>
                <label>PLZ</label>
                <input value={form.plz} onChange={(e) => set('plz', e.target.value)} placeholder="8001" />
                {errors.plz && <span className="msg">{errors.plz}</span>}
              </div>
              <div className={"field" + (errors.ort ? " err" : "")}>
                <label>Ort</label>
                <input value={form.ort} onChange={(e) => set('ort', e.target.value)} placeholder="Zürich" />
                {errors.ort && <span className="msg">{errors.ort}</span>}
              </div>
            </div>
            <div className="field">
              <label>Bemerkungen <span className="opt">(optional)</span></label>
              <textarea rows="3" value={form.bemerkungen} onChange={(e) => set('bemerkungen', e.target.value)} placeholder="Deine Nachricht an uns …"></textarea>
            </div>
            <button type="submit" className="btn btn-lg btn-primary" style={{ alignSelf: 'flex-start' }} disabled={sending}>
              {sending ? 'Wird gesendet…' : <span>Anfrage senden <IcArrow /></span>}
            </button>
            <p className="recaptcha-notice">Diese Website ist durch reCAPTCHA geschützt. Es gelten die <a href="https://policies.google.com/privacy" target="_blank" rel="noopener">Datenschutzbestimmungen</a> und <a href="https://policies.google.com/terms" target="_blank" rel="noopener">Nutzungsbedingungen</a> von Google.</p>
          </form>
        </div>
      </div>
    </section>);

}

function Footer({ onShop }) {
  const cols = [
  ['Sortiment', [['Ice Cup to Go', '#products'], ['Ice Cup Bags', '#products'], ['Strohhalme', '#products'], ['Display-Tiefkühler', '#freezers']]],
  ['Unternehmen', [['Über uns', '#about'], ['Partnernetz', '#partners'], ['Nachhaltigkeit', '#about']]],
  ['Support', [['Kontakt', '#contact'], ['FAQ', '#faq']]]];

  return (
    <footer className="footer">
      <div className="wrap">
        <div className="foot-cta reveal">
          <h2>Werde Teil des<br /><span className="grad">Schweizer Eis-Netzes.</span></h2>
          <div style={{ display: 'flex', gap: '14px', justifyContent: 'center', marginTop: '30px', flexWrap: 'wrap' }}>
            <button className="btn btn-lg btn-primary" onClick={onShop}>Partner werden <IcArrow /></button>
            <a className="btn btn-lg btn-ghost" href="#products">Sortiment ansehen</a>
          </div>
        </div>
        <div className="foot-main">
          <div className="foot-brand">
            <a className="brand" href="#top"><img className="brand-logo" src={resolveAsset('assets/logo.png')} alt="Ice Cup" /></a>
            <p>Ice Cup - Schweizer Eiswürfel, die Ihren Drink veredeln und jeden Moment erfrischen.</p>
            <div className="socials">
              <a href="https://www.instagram.com/icecupswitzerland" target="_blank" rel="noopener" aria-label="Instagram"><SoIg /></a>
              <a href="https://www.tiktok.com/@icecupswitzerland" target="_blank" rel="noopener" aria-label="TikTok"><SoTk /></a>
            </div>
          </div>
          {cols.map(([h, items]) =>
          <div className="foot-col" key={h}>
              <h4>{h}</h4>
              {items.map(([label, href]) => <a key={label} href={href}>{label}</a>)}
            </div>
          )}
        </div>
        <div className="foot-bottom">
          <span>© 2026 Ice Cup AG · Swiss Made. Alle Rechte vorbehalten.</span>
          <div className="legal">
            <a href="legal/datenschutz.html">Datenschutz</a>
            <a href="legal/agb.html">AGB</a>
            <a href="legal/impressum.html">Impressum</a>
          </div>
        </div>
      </div>
    </footer>);

}

/* ---------- Cart drawer ---------- */
function CartDrawer({ open, items, onClose, onQty, onRemove }) {
  const lines = Object.values(items);
  const total = lines.reduce((s, l) => s + l.price * l.qty, 0);
  const count = lines.reduce((s, l) => s + l.qty, 0);
  return (
    <>
      <div className={"scrim" + (open ? " show" : "")} onClick={onClose}></div>
      <aside className={"drawer" + (open ? " open" : "")} aria-hidden={!open}>
        <div className="drawer-head">
          <h3>Your Cart{count > 0 ? ` · ${count}` : ''}</h3>
          <button className="drawer-close" onClick={onClose} aria-label="Close cart"><IcClose /></button>
        </div>
        {lines.length === 0 ?
        <div className="cart-empty">
            <div style={{ opacity: 0.5 }}><MiniCup /></div>
            <p>Your cart is empty.<br />Time to stock up on cold.</p>
            <button className="btn btn-dark" style={{ padding: '13px 22px' }} onClick={onClose}>Browse the range</button>
          </div> :

        <>
            <div className="drawer-body">
              {lines.map((l) =>
            <div className="cart-line" key={l.id}>
                  <div className="cart-thumb"><div style={{ transform: 'scale(0.42)' }}><MiniCup /></div></div>
                  <div className="cl-info">
                    <b>{l.name}</b>
                    <span>CHF {l.price.toFixed(2)} · {l.unit}</span>
                    <div className="qty">
                      <button onClick={() => onQty(l.id, -1)} aria-label="decrease"><IcMinus s={13} /></button>
                      <span>{l.qty}</span>
                      <button onClick={() => onQty(l.id, 1)} aria-label="increase"><IcPlus s={13} /></button>
                    </div>
                  </div>
                  <button className="cl-remove" onClick={() => onRemove(l.id)}>Remove</button>
                </div>
            )}
            </div>
            <div className="drawer-foot">
              <div className="drawer-total">
                <span>Subtotal</span>
                <b>CHF {total.toFixed(2)}</b>
              </div>
              <button className="btn btn-lg btn-primary" style={{ width: '100%' }}>Checkout <IcArrow /></button>
            </div>
          </>
        }
      </aside>
    </>);

}

Object.assign(window, { About, FAQ, Contact, Footer, CartDrawer });