/* ============================================================
   app.jsx — shared sections, nav, theme/mode shell, root
   ============================================================ */
const { useState: apState, useEffect: apEffect, useRef: apRef } = React;

/* ---------------- Partners ---------------- */
const PARTNERS = [
  ['riviera', 'Riviera'], ['galeria-krakowska', 'Galeria Krakowska'], ['manufaktura', 'Manufaktura'],
  ['magnolia-park', 'Magnolia Park'], ['santander', 'Santander'], ['orange', 'Orange'], ['targi-kielce', 'Targi Kielce'],
  ['fabryka-norblina', 'Fabryka Norblina'], ['poznan-travel', 'Poznań Travel'], ['aquapark-fala', 'Aquapark Fala'],
  ['mtp', 'MTP'], ['pyrkon', 'Pyrkon'], ['moxy', 'Moxy Hotels'], ['habeshawi', 'Habeshawi'], ['nocny-targ', 'Nocny Targ'],
  ['korona', 'Korona'], ['ratuszova', 'Ratuszova'], ['hopalupa', 'Hopalupa'], ['rzeszowskie-juwenalia', 'Rzeszowskie Juwenalia'],
  ['bittersweet', 'Bittersweet'], ['strona', 'Strona'], ['act', 'Act'], ['prywatka', 'Prywatka'], ['gramofon', 'Gramofon'], ['mm-monogram', 'Partner'],
];
function Partners() {
  const rot = (a, n) => [...a.slice(n), ...a.slice(0, n)];
  const r1 = [...PARTNERS, ...PARTNERS];
  const r2 = [...rot(PARTNERS, 9), ...rot(PARTNERS, 9)];
  const Hex = (p, i) => (
    <div className="hexpartner" key={i}>
      <div className="hex-cell"><img src={`assets/partners/${p[0]}.png`} alt={p[1]} loading="lazy" /></div>
    </div>
  );
  return (
    <section className="section">
      <div className="wrap">
        <Reveal className="sec-head" style={{}}>
          <span className="eyebrow">Trusted by</span>
          <h2 className="h2">Our partners.</h2>
        </Reveal>
      </div>
      <div className="honeycomb" style={{ marginTop: 44 }}>
        <div className="comb-row">
          <div className="comb-shift"><div className="comb-track">{r1.map(Hex)}</div></div>
        </div>
        <div className="comb-row r2">
          <div className="comb-shift"><div className="comb-track">{r2.map(Hex)}</div></div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- FAQ ---------------- */
function FAQ({ items }) {
  const [open, setOpen] = apState(0);
  return (
    <section className="section section--alt" id="faq">
      <div className="wrap">
        <div className="media-2" style={{ alignItems: 'start' }}>
          <Reveal>
            <span className="eyebrow">FAQ</span>
            <h2 className="h2" style={{ marginTop: 16 }}>Frequently asked questions.</h2>
            <p className="lead" style={{ marginTop: 18 }}>Can't find your answer? Reach us at <a className="text-grad" style={{ fontWeight: 700 }} href="mailto:team@hellocharge.pl">team@hellocharge.pl</a></p>
            <button className="btn btn-primary" style={{ marginTop: 26 }} onClick={() => document.getElementById('contact').scrollIntoView({ behavior: 'smooth' })}>Contact us<Icon name="arrow" size={18} className="arrow" /></button>
          </Reveal>
          <Reveal delay="d2">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {items.map((it, i) => (
                <div className={`acc-item ${open === i ? 'open' : ''}`} key={i}>
                  <button className="acc-q" onClick={() => setOpen(open === i ? -1 : i)}>
                    <span>{it.q}</span>
                    <span className="acc-ic"><Icon name="plus" size={16} /></span>
                  </button>
                  <div className="acc-a" style={{ maxHeight: open === i ? 260 : 0 }}>
                    <div className="acc-a-inner">{it.a}</div>
                  </div>
                </div>
              ))}
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* ---------------- CTA band ---------------- */
function CtaBand({ mode, onSwitch }) {
  const isCust = mode === 'customer';
  return (
    <section className="section tight">
      <div className="wrap">
        <Reveal className="cta-band" style={{}}>
          <div className="ring" style={{ width: 320, height: 320, right: -80, top: -120 }}></div>
          <div className="ring" style={{ width: 200, height: 200, right: 60, bottom: -110 }}></div>
          <div style={{ position: 'relative', zIndex: 2, maxWidth: 640 }}>
            <h2 className="h2">{isCust ? 'Never run out of battery again.' : 'Turn your space into a revenue stream.'}</h2>
            <p style={{ fontSize: 18, lineHeight: 1.55, marginTop: 16, color: '#0b2e16', fontWeight: 500 }}>
              {isCust ? 'Download the app and find a power bank near you in seconds.' : 'Host a HelloCharge station — we install, maintain and stock it, you earn.'}
            </p>
            <div className="row" style={{ marginTop: 28 }}>
              {isCust
                ? <AppStoreButtons />
                : <button className="btn btn-primary" onClick={() => onSwitch()}>Become a partner<Icon name="arrow" size={18} className="arrow" /></button>}
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------------- Contact ---------------- */
function Contact() {
  const [status, setStatus] = apState('idle'); // idle | sending | sent | error
  const submit = async (e) => {
    e.preventDefault();
    if (status === 'sending' || status === 'sent') return;
    const form = e.currentTarget;
    const data = new FormData(form);
    const get = (k) => (data.get(k) || '').toString().trim();
    setStatus('sending');
    try {
      const res = await fetch('https://api.hsforms.com/submissions/v3/integration/submit/48544666/3bfdee23-8046-47c7-ae08-90c9021ca380', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          fields: [
            { name: 'firstname', value: get('name') },
            { name: 'email', value: get('email') },
            { name: 'phone', value: get('phone') },
            { name: 'message', value: get('message') },
          ].filter((f) => f.value),
          context: { pageUri: window.location.href, pageName: 'Contact Page' },
        }),
      });
      if (!res.ok) throw new Error('HubSpot responded ' + res.status);
      setStatus('sent');
      form.reset();
    } catch (err) {
      console.error('Contact form submission failed:', err);
      setStatus('error');
    }
  };
  return (
    <section className="section" id="contact">
      <div className="wrap">
        <Reveal className="sec-head center" style={{}}>
          <span className="eyebrow center">Contact us</span>
          <h2 className="h2">Get in touch.</h2>
          <p className="lead">We're here to help — reach out and we'll get back fast.</p>
        </Reveal>
        <Reveal className="contact-cards" style={{ marginTop: 48 }}>
          <div className="cc card">
            <div className="cc-ic"><Icon name="pin" size={22} /></div>
            <div className="cc-k">Address</div>
            <div className="cc-v">Głogowska 31/33</div>
            <div className="cc-sub">Poznań, Poland</div>
          </div>
          <div className="cc card">
            <div className="cc-ic"><Icon name="mail" size={22} /></div>
            <div className="cc-k">Email</div>
            <div className="cc-v">team@hellocharge.pl</div>
            <div className="cc-sub">We reply within a day</div>
          </div>
          <div className="cc card">
            <div className="cc-ic"><Icon name="phone" size={22} /></div>
            <div className="cc-k">Phone</div>
            <a className="cc-v" href="tel:+48660212616" style={{ color: 'var(--accent-ink)', display: 'block', textDecoration: 'none' }}>+48 660 212 616</a>
            <div className="cc-sub">8:00–18:00</div>
          </div>
        </Reveal>
        <Reveal className="contact-form card" style={{ marginTop: 24 }}>
          <h3 className="h2" style={{ fontSize: 'clamp(24px,2.4vw,32px)', textAlign: 'center' }}>Send us a message</h3>
          <p className="muted center" style={{ marginTop: 10, marginBottom: 30 }}>Fill out the form and we'll get back to you as soon as possible.</p>
          <form onSubmit={submit}>
            <div className="form-grid">
              <div className="field"><label>Name *</label><input name="name" required placeholder="Your name" /></div>
              <div className="field"><label>Email *</label><input name="email" required type="email" placeholder="you@email.com" /></div>
              <div className="field full"><label>Phone number</label><input name="phone" placeholder="+48 ..." /></div>
              <div className="field full"><label>Message</label><textarea name="message" rows="5" placeholder="How can we help?"></textarea></div>
            </div>
            <button className="btn btn-primary" type="submit" style={{ marginTop: 24 }} disabled={status === 'sending' || status === 'sent'}>
              {status === 'sent' ? <>Message sent<Icon name="check" size={18} /></> : status === 'sending' ? <>Sending…</> : <>Send message<Icon name="arrow" size={18} className="arrow" /></>}
            </button>
            {status === 'error' && <p className="muted center" style={{ marginTop: 14, color: '#DC2626' }}>Something went wrong. Please try again or email team@hellocharge.pl.</p>}
            {status === 'sent' && <p className="muted center" style={{ marginTop: 14 }}>Thanks — we'll be in touch shortly.</p>}
          </form>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------------- Footer ---------------- */
function Footer({ onSwitch, mode }) {
  const SOC = [
    { label: 'Instagram', href: 'https://www.instagram.com/hellocharge.app/', icon: (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <rect x="2" y="2" width="20" height="20" rx="5" ry="5"></rect>
        <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"></path>
        <line x1="17.5" y1="6.5" x2="17.51" y2="6.5"></line>
      </svg>
    ) },
    { label: 'Facebook', href: 'https://www.facebook.com/p/Hellocharge-61575259236537/', icon: (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
        <path d="M22 12a10 10 0 1 0-11.56 9.88v-6.99H7.9V12h2.54V9.8c0-2.5 1.49-3.89 3.78-3.89 1.09 0 2.24.2 2.24.2v2.46h-1.26c-1.24 0-1.63.77-1.63 1.56V12h2.78l-.45 2.89h-2.33v6.99A10 10 0 0 0 22 12z"></path>
      </svg>
    ) },
    { label: 'LinkedIn', href: 'https://pl.linkedin.com/company/hello-charge', icon: (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
        <path d="M20.45 20.45h-3.56v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.14 1.45-2.14 2.94v5.67H9.35V9h3.41v1.56h.05a3.74 3.74 0 0 1 3.37-1.85c3.6 0 4.27 2.37 4.27 5.46v6.28zM5.34 7.43a2.06 2.06 0 1 1 0-4.13 2.06 2.06 0 0 1 0 4.13zM7.12 20.45H3.55V9h3.57v11.45zM22.22 0H1.77C.79 0 0 .77 0 1.73v20.54C0 23.23.79 24 1.77 24h20.45c.98 0 1.78-.77 1.78-1.73V1.73C24 .77 23.2 0 22.22 0z"></path>
      </svg>
    ) },
    { label: 'TikTok', href: 'https://www.tiktok.com/@hellocharge.app', icon: (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
        <path d="M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-5.2 1.74 2.89 2.89 0 0 1 2.31-4.64c.3 0 .59.04.86.13V9.4a6.33 6.33 0 0 0-1-.05A6.34 6.34 0 0 0 5.91 20.3a6.34 6.34 0 0 0 10.86-4.43V8.91a8.16 8.16 0 0 0 4.77 1.52V7a4.85 4.85 0 0 1-1.95-.31z"></path>
      </svg>
    ) },
  ];
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div>
            <Logo />
            <p className="muted" style={{ marginTop: 18, maxWidth: 260, lineHeight: 1.6, fontSize: 15 }}>Professional power bank rental solutions for modern businesses and people on the move.</p>
            <div className="socials">
              {SOC.map((s) => <a key={s.label} href={s.href} target="_blank" rel="noopener noreferrer" aria-label={s.label}>{s.icon}</a>)}
            </div>
          </div>
          <div>
            <h4>Customer</h4>
            <a className="fl" href="#" onClick={(e) => { e.preventDefault(); onSwitch('customer'); }}>Home</a>
            <a className="fl" href="#pricing">Pricing</a>
            <a className="fl" href="#about">About</a>
            <a className="fl" href="#contact">Contact</a>
          </div>
          <div>
            <h4>Business</h4>
            <a className="fl" href="#" onClick={(e) => { e.preventDefault(); onSwitch('business'); }}>Franchise</a>
            <a className="fl" href="#" onClick={(e) => { e.preventDefault(); onSwitch('business'); }}>Station types</a>
            <a className="fl" href="#" onClick={(e) => { e.preventDefault(); onSwitch('business'); }}>Locations</a>
            <a className="fl" href="#contact">Contact</a>
          </div>
          <div>
            <h4>Legal</h4>
            <a className="fl" href="terms.html">Terms of Use</a>
            <a className="fl" href="privacy.html">Privacy</a>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 HelloCharge. All rights reserved.</span>
          <span>Made in Poznań · team@hellocharge.pl</span>
        </div>
      </div>
    </footer>
  );
}

/* ---------------- Navigation ---------------- */
function Nav({ mode, theme, onSwitchMode, onToggleTheme, onNav }) {
  const [scrolled, setScrolled] = apState(false);
  const [menuOpen, setMenuOpen] = apState(false);
  apEffect(() => {
    const f = () => setScrolled(window.scrollY > 24);
    f(); window.addEventListener('scroll', f, { passive: true });
    return () => window.removeEventListener('scroll', f);
  }, []);
  apEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);
  const links = mode === 'customer'
    ? [['Home', 'top'], ['How it works', 'how'], ['Pricing', 'pricing'], ['About', 'about'], ['Contact', 'contact']]
    : [['Home', 'top'], ['Franchise', 'top'], ['Stations', 'stations'], ['Locations', 'map'], ['Contact', 'contact']];
  const go = (id) => { setMenuOpen(false); onNav(id); };
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="wrap">
        <Logo onClick={() => go('top')} />
        <div className="nav-links">
          {links.map((l, i) => (
            <a key={i} className={`nav-link ${i === 0 ? 'active' : ''}`} onClick={() => onNav(l[1])}>{l[0]}</a>
          ))}
        </div>
        <div className="nav-actions">
          <AppStoreButtons compact />
          <button className="switch-pill" onClick={onSwitchMode}>
            <Icon name={mode === 'customer' ? 'building' : 'user'} size={15} />
            {mode === 'customer' ? 'For business' : 'For customers'}
          </button>
          <button className="icon-btn" onClick={onToggleTheme} aria-label="Toggle theme" title="Toggle theme">
            <Icon name={theme === 'dark' ? 'sun' : 'moon'} size={18} />
          </button>
        </div>
        <button
          className={`nav-burger ${menuOpen ? 'open' : ''}`}
          onClick={() => setMenuOpen((o) => !o)}
          aria-label={menuOpen ? 'Close menu' : 'Open menu'}
          aria-expanded={menuOpen}
        >
          <span></span><span></span><span></span>
        </button>
      </div>
      <div className={`mobile-menu ${menuOpen ? 'open' : ''}`}>
        <div className="mm-backdrop" onClick={() => setMenuOpen(false)}></div>
        <div className="mm-panel" role="dialog" aria-modal="true">
          <div className="mm-links">
            {links.map((l, i) => (
              <a key={i} className={`mm-link ${i === 0 ? 'active' : ''}`} onClick={() => go(l[1])}>
                {l[0]}<Icon name="arrow" size={18} />
              </a>
            ))}
          </div>
          <div className="mm-foot">
            <button className="switch-pill mm-switch" onClick={() => { setMenuOpen(false); onSwitchMode(); }}>
              <Icon name={mode === 'customer' ? 'building' : 'user'} size={16} />
              {mode === 'customer' ? 'For business' : 'For customers'}
            </button>
            <div className="mm-store">
              <span>Download the app</span>
              <a href="https://apps.apple.com/pl/app/hellocharge/id6742231208" target="_blank" rel="noopener noreferrer" aria-label="App Store"><Icon name="apple" size={20} /></a>
              <a href="#" aria-label="Google Play"><Icon name="google" size={19} /></a>
            </div>
            <button className="mm-theme" onClick={onToggleTheme}>
              <Icon name={theme === 'dark' ? 'sun' : 'moon'} size={18} />
              {theme === 'dark' ? 'Light mode' : 'Dark mode'}
            </button>
          </div>
        </div>
      </div>
    </nav>
  );
}

const CUST_FAQ = [
  { q: 'How long can I rent a power bank?', a: 'As long as you need, up to a maximum of 2 days. You pay 3.99 PLN per hour with a daily cap of 24.99 PLN, so a long rental never gets expensive.' },
  { q: 'Do I have to return it to the same station?', a: 'No — that\'s the beauty of the network. Return your power bank to any HelloCharge station across Poland, wherever is most convenient for you.' },
  { q: 'Do I need a special app to rent?', a: 'Not at all. Tap your card or scan the QR code on any station to start. The HelloCharge app simply makes finding stations and tracking rentals easier.' },
  { q: 'How is the fee calculated?', a: 'You\'re billed 3.99 PLN per hour, capped at 24.99 PLN per day. A refundable 25 PLN deposit is held and released the moment you return the power bank.' },
];
const BIZ_FAQ = [
  { q: 'How much does it cost to host a station?', a: 'Hosting is low-commitment — you provide the spot and a power outlet, we provide the station. Talk to our team for partnership terms tailored to your venue.' },
  { q: 'Who handles maintenance and restocking?', a: 'We do, entirely. Servicing, repairs, replacements and keeping every slot stocked with charged banks are all managed by the HelloCharge team.' },
  { q: 'What do I need to provide?', a: 'Just a power outlet and a visible spot in your venue. We handle delivery, installation, software, support and upkeep.' },
  { q: 'How quickly can I get started?', a: 'Order a station and we coordinate delivery and installation fast — most partners are live and earning within days.' },
];

function App() {
  const [theme, setTheme] = apState(() => localStorage.getItem('hc-theme') || 'dark');
  const [mode, setMode] = apState(() => localStorage.getItem('hc-mode') || 'customer');

  apEffect(() => { document.documentElement.setAttribute('data-theme', theme); localStorage.setItem('hc-theme', theme); }, [theme]);
  apEffect(() => { localStorage.setItem('hc-mode', mode); }, [mode]);

  // Global reveal observer — catches every .reveal (bare or wrapped), re-runs per mode.
  apEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } });
    }, { threshold: 0.12, rootMargin: '0px 0px -6% 0px' });
    const els = document.querySelectorAll('.reveal:not(.in)');
    els.forEach((el) => io.observe(el));
    // Safety net: anything still hidden after 2.5s (e.g. throttled timeline) is forced visible.
    const t = setTimeout(() => { document.querySelectorAll('.reveal:not(.in)').forEach((el) => el.classList.add('in')); }, 2500);
    return () => { io.disconnect(); clearTimeout(t); };
  }, [mode]);

  const onNav = (id) => {
    if (id === 'top') { window.scrollTo({ top: 0, behavior: 'smooth' }); return; }
    const el = document.getElementById(id);
    if (el) { const y = el.getBoundingClientRect().top + window.scrollY - 70; window.scrollTo({ top: y, behavior: 'smooth' }); }
  };
  const switchMode = (to) => {
    setMode((m) => to || (m === 'customer' ? 'business' : 'customer'));
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  return (
    <AppCtx.Provider value={{ theme, mode }}>
      <Nav mode={mode} theme={theme} onSwitchMode={() => switchMode()} onToggleTheme={() => setTheme((t) => t === 'dark' ? 'light' : 'dark')} onNav={onNav} />
      <main key={mode} id="top">
        {mode === 'customer' ? (
          <>
            <CustomerHero onNav={onNav} />
            <StatStrip items={[
              { to: 35, label: 'Stations across Poland' },
              { to: 30, suffix: ' min', label: 'To a fast charge' },
              { to: 3, label: 'Cables on every bank' },
              { to: 25, prefix: '', suffix: ' PLN', decimals: 0, label: 'Refundable deposit' },
            ]} />
            <VenueTypes />
            <HowItWorks />
            <RentPowerbank />
            <TapAndGo />
            <Pricing />
            <AboutOffer />
            <Partners />
            <FAQ items={CUST_FAQ} />
            <CtaBand mode={mode} onSwitch={() => switchMode('business')} />
          </>
        ) : (
          <>
            <BusinessHero onNav={onNav} />
            <BusinessModel />
            <WhyWorth />
            <StationTypes onContact={() => onNav('contact')} />
            <CoBranding onContact={() => onNav('contact')} />
            <Locations />
            <WhatWeOffer />
            <Partners />
            <FAQ items={BIZ_FAQ} />
            <CtaBand mode={mode} onSwitch={() => switchMode('business')} />
          </>
        )}
        <Contact />
        <Footer onSwitch={switchMode} mode={mode} />
      </main>
    </AppCtx.Provider>
  );
}

const __hcRootEl = document.getElementById('root');
if (!__hcRootEl.__hcRoot) __hcRootEl.__hcRoot = ReactDOM.createRoot(__hcRootEl);
__hcRootEl.__hcRoot.render(<App />);
