/* global React */

const MENU_DATA = {
  Burgers: [
    { name: 'Classic', price: '95K' },
    { name: 'Cheese', price: '99K' },
    { name: 'BBQ', price: '105K' },
    { name: 'Bacon', price: '110K' },
    { name: 'Truffle Parm', price: '135K' },
    { name: 'Dbl. Fried Onion', price: '155K' },
    { name: 'Dbl. Chicken', price: '110K' },
    { name: 'Vegetarian', price: '110K' },
  ],
  Sides: [
    { name: 'Handcut Fries', price: '40K' },
    { name: 'Onion Rings', price: '45K' },
    { name: 'Nuggets', price: '50K' },
    { name: 'BBQ Wings', price: '55K' },
  ],
  Shakes: [
    { name: 'Nutella', price: '52K' },
    { name: 'Oreo', price: '52K' },
    { name: 'Lotus', price: '52K' },
    { name: 'Vanilla', price: '52K' },
  ],
  Sauces: [
    { name: 'Hot Mayo 🌶', price: '10K' },
    { name: 'Vang Mayo', price: '15K' },
    { name: 'BBQ', price: '15K' },
    { name: 'Truffle Mayo', price: '20K' },
    { name: 'Parmesan', price: '25K' },
  ],
  Drinks: [
    { name: 'Water', price: '20K' },
    { name: 'Orange Fanta', price: '25K' },
    { name: 'Coke / Zero', price: '25K' },
    { name: 'Beer (Bintang)', price: '35K' },
  ],
};

const LINKS = {
  instagram: 'https://www.instagram.com/crave.indonesia/',
  linktree: 'https://linktr.ee/craveindonesia',
};

const LOCATIONS = {
  Ungasan: {
    name: 'Crave Ungasan',
    addr: 'Jalan Toyanin II, Pecatu, Bali 80362',
    coords: '-8.832,115.137',
    maps: 'https://maps.app.goo.gl/8ZN9KNUWxH6qwM5a6',
    gofood: 'https://gofood.co.id/bali/restaurant/crave-burger-ungasan-4739ec58-a72c-4753-8837-a40ad3175687',
    grab: 'https://www.grab.com/id/download/?pid=inappsharing&c=6-C6VZA8CTGLCUA6',
    embedQ: 'Crave+Burger+Ungasan,+Jalan+Toyanin+II,+Pecatu,+Bali',
    hours: [
      ['Monday', '12:00 PM – 2:45 AM'],
      ['Tuesday', '6:00 PM – 1:45 AM'],
      ['Wednesday', '12:00 PM – 1:45 AM'],
      ['Thursday', '12:00 PM – 1:45 AM'],
      ['Friday', '12:00 PM – 2:45 AM'],
      ['Saturday', '12:00 PM – 2:45 AM'],
      ['Sunday', '12:00 PM – 2:45 AM'],
    ],
    blurb: "Tucked behind the cliffs of Pecatu — close to Single Fin and Suluban. Late-night surfer fuel.",
  },
  Berawa: {
    name: 'Crave Berawa',
    addr: 'Jalan Pantai Berawa 34, Badung, Bali 80361',
    coords: '-8.660,115.140',
    maps: 'https://maps.app.goo.gl/wjYUBwn5gmti5vT69',
    gofood: 'https://gofood.co.id/bali/restaurant/crave-burger-berawa-kuta-utara-badung-e7dfeb3d-0b19-4c44-9794-42389c7457f2',
    grab: 'https://food.grab.com/id/en/restaurant/crave-burger-berawa-delivery/6-C72KRXETAY3WUE?sourceID=20260311_102453_5A74EE991A2847D9A64A81368161159E_MEXMPS',
    embedQ: 'Crave+Burger+Berawa,+Jalan+Pantai+Berawa+34,+Badung,+Bali',
    hours: [
      ['Monday', '12:00 PM – 2:00 AM'],
      ['Tuesday', '6:00 PM – 2:00 AM'],
      ['Wednesday', '12:00 PM – 2:00 AM'],
      ['Thursday', '12:00 PM – 2:00 AM'],
      ['Friday', '12:00 PM – 3:00 AM'],
      ['Saturday', '12:00 PM – 3:00 AM'],
      ['Sunday', '12:00 PM – 3:00 AM'],
    ],
    blurb: "Right off Berawa beach — between Finns and Atlas. Where Canggu eats after dark.",
  },
};

function MenuSection({ onOpenFull }) {
  const [tab, setTab] = React.useState('Burgers');
  const items = MENU_DATA[tab];
  return (
    <section id="menu" className="menu-wrap" data-screen-label="Menu">
      <div className="container">
        <div className="menu-head reveal">
          <span className="label eyebrow">★ The Cravings ★</span>
          <h2>SMASH <span className="red">MENU.</span></h2>
          <p style={{maxWidth:560, margin:'0 auto', fontSize:17, lineHeight:1.5, color:'var(--ink)'}}>
            All beef burgers served with 100% imported Australian Angus.
            Sauces made from scratch, fries hand-cut, shakes blended thick.
          </p>
        </div>

        <div style={{display:'flex', justifyContent:'center'}}>
          <div className="menu-tabs reveal">
            {Object.keys(MENU_DATA).map(k => (
              <button key={k} className={`menu-tab ${tab===k?'active':''}`} onClick={()=>setTab(k)}>
                {k}
              </button>
            ))}
          </div>
        </div>

        <div className="menu-grid" style={{marginTop: 28}}>
          <div className="menu-card reveal">
            <div className="top-strip check-rw" />
            <div className="body">
              <h3>{tab}</h3>
              <div>
                {items.map((it, i) => (
                  <div className="row leader" key={i}>
                    <span className="name">{it.name}</span>
                    <span className="dots" />
                    <span className="price">{it.price}</span>
                  </div>
                ))}
              </div>
              {tab==='Burgers' && (
                <div style={{marginTop: 26, padding:'18px 0', borderTop: '2px dotted var(--black)'}}>
                  <h3 style={{fontSize: 24, marginBottom: 14}}>CUSTOM IT</h3>
                  {[
                    ['Fried Egg', '10K'],
                    ['Crunchy Bacon', '20K'],
                    ['Cheddar', '15K'],
                    ['Beef Smash', '75K'],
                    ['Chicken Smash', '35K'],
                  ].map(([n,p],i)=>(
                    <div className="row leader" key={i}>
                      <span className="name">{n}</span>
                      <span className="dots" />
                      <span className="price">{p}</span>
                    </div>
                  ))}
                </div>
              )}
              <div className="menu-foot">Gov tax 11% not included in prices</div>
            </div>
          </div>

          <div className="menu-aside">
            <div className="aside-photo reveal">
              <img src="assets/photo-saucing.jpeg" alt="Crave saucing the bun" />
              <span className="pill pill-red tag">House Sauces</span>
            </div>
            <div className="aside-quote reveal">
              "No shortcuts.<br/>
              Just <span className="red">bold flavors</span><br/>
              from scratch."
            </div>
            <button className="btn btn-primary reveal" onClick={onOpenFull} style={{justifyContent:'center'}}>
              Open Full Menu ↗
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

function LocationsSection() {
  const [active, setActive] = React.useState('Ungasan');
  const loc = LOCATIONS[active];
  // Dark-themed Google Maps embed via CSS filter. Use coordinates with a label
  // so the pin always lands at the right place (text-only queries can fail to
  // resolve for less-indexed venues).
  const embedSrc = `https://maps.google.com/maps?q=${loc.coords}(${encodeURIComponent(loc.name)})&t=&z=16&ie=UTF8&iwloc=&output=embed`;
  return (
    <section id="locations" className="loc-wrap" data-screen-label="Locations">
      <div className="container">
        <div className="loc-head reveal">
          <div>
            <span className="label" style={{color:'var(--red)'}}>★ Two Outposts ★</span>
            <h2 style={{marginTop: 10}}>FIND <span className="red">CRAVE.</span></h2>
          </div>
          <div className="loc-tabs">
            {Object.keys(LOCATIONS).map(k=>(
              <button key={k} className={`loc-tab ${active===k?'active':''}`} onClick={()=>setActive(k)}>
                {k}
              </button>
            ))}
          </div>
        </div>

        <div className="loc-grid">
          <div className="loc-card reveal">
            <div className="row" style={{justifyContent:'space-between'}}>
              <span className="pill pill-red">● Open Now</span>
              <span className="label" style={{opacity:.7}}>{active==='Ungasan'?'No.001':'No.002'}</span>
            </div>
            <div>
              <div className="name">{loc.name.split(' ')[0]} <span className="red">{loc.name.split(' ')[1]}</span></div>
              <p className="addr" style={{marginTop: 12}}>{loc.addr}</p>
              <p className="addr" style={{opacity:.75, marginTop: 8}}>{loc.blurb}</p>
            </div>
            <div className="loc-hours">
              {loc.hours.map(([d,t],i)=>(
                <React.Fragment key={i}>
                  <span className="day">{d}</span>
                  <span className="time">{t}</span>
                </React.Fragment>
              ))}
            </div>
            <div className="loc-actions">
              <a className="btn btn-primary" href={loc.maps} target="_blank" rel="noopener">Directions ↗</a>
              <a className="btn btn-ghost" href={loc.gofood} target="_blank" rel="noopener">GoFood ↗</a>
              <a className="btn btn-ghost" href={loc.grab} target="_blank" rel="noopener">GrabFood ↗</a>
            </div>
          </div>

          <div className="loc-map reveal">
            <div className="map-frame">
              <iframe
                src={embedSrc}
                title={loc.name}
                loading="lazy"
                referrerPolicy="no-referrer-when-downgrade"
                style={{border:0, width:'100%', height:'100%'}}
              />
              <div className="map-pin">
                <div className="pin-stamp">
                  <span style={{fontFamily:'Bagel Fat One, serif'}}>crave</span>
                </div>
              </div>
            </div>
            <div className="footer">
              <span>{active.toUpperCase()} · BALI</span>
              <a href={loc.maps} target="_blank" rel="noopener" style={{color:'var(--red)'}}>OPEN IN MAPS ↗</a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function GallerySection() {
  return (
    <section className="gal-wrap" data-screen-label="Gallery">
      <div className="container">
        <div className="gal-head reveal">
          <div>
            <span className="label" style={{color:'var(--red)'}}>★ The Vibes ★</span>
            <h2 style={{marginTop:10}}>EAT <span className="red">LOUD.</span></h2>
          </div>
          <a className="btn" href={LINKS.instagram} target="_blank" rel="noopener">@crave.indonesia ↗</a>
        </div>

        <div className="gal-grid">
          <div className="gal-tile tall reveal">
            <img src="assets/photo-laughing.jpeg" alt="Customer laughing" />
            <span className="pill pill-red stamp">Bite no mercy</span>
          </div>
          <div className="gal-tile reveal">
            <img src="assets/photo-trays.jpeg" alt="Trays of burgers" />
            <span className="pill stamp">House Trays</span>
          </div>
          <div className="gal-tile reveal">
            <img src="assets/photo-shake.jpeg" alt="Oreo shake" />
            <span className="pill stamp">Oreo Shake</span>
          </div>
          <div className="gal-tile reveal">
            <img src="assets/photo-bear-tee.jpeg" alt="Customer with fries" />
            <span className="pill pill-red stamp">Late Night</span>
          </div>
          <div className="gal-tile wide reveal">
            <img src="assets/photo-family.jpeg" alt="Family eating" />
            <span className="pill stamp">All ages welcome</span>
          </div>
          <div className="gal-tile reveal">
            <img src="assets/photo-bite.jpeg" alt="Bite of burger" />
            <span className="pill pill-red stamp">First bite</span>
          </div>
          <div className="gal-tile reveal">
            <img src="assets/photo-saucing.jpeg" alt="Saucing the bun" />
            <span className="pill stamp">Made fresh</span>
          </div>
        </div>
      </div>
    </section>
  );
}

function StorySection() {
  return (
    <section id="story" className="story-wrap" data-screen-label="Story">
      <div className="container">
        <div className="story-grid">
          <div className="story-head reveal">
            <span className="label">Our Story</span>
            <h2>BORN IN BALI.<br/>BUILT TO <em>SMASH.</em></h2>
            <p>
              Crave started with one obsession: a burger that hits like a wave at Uluwatu — bold,
              hot, impossible to ignore. So we sourced 100% imported Australian Angus, learned to
              smash it on a screaming-hot grill, and built every sauce in-house from scratch.
              No fluff. No pretense. Just quality smashed loud and served fast.
            </p>
            <div className="story-stats">
              <div className="stat">
                <div className="num">2</div>
                <div className="lbl">Outposts</div>
              </div>
              <div className="stat">
                <div className="num">100%</div>
                <div className="lbl">Aussie Angus</div>
              </div>
              <div className="stat">
                <div className="num">3 AM</div>
                <div className="lbl">Latest Close</div>
              </div>
            </div>
          </div>
          <div className="story-photo reveal">
            <img src="assets/photo-bite.jpeg" alt="Crave team smashing burger" />
          </div>
        </div>
      </div>
    </section>
  );
}

function OrderSection() {
  return (
    <section id="order" className="order-wrap" data-screen-label="Order">
      <div className="container">
        <div className="order-card reveal">
          <div>
            <span className="pill pill-red">Get it delivered</span>
            <h2 style={{marginTop:14}}>STILL <span className="red">HUNGRY?</span></h2>
            <p style={{fontSize:17, lineHeight:1.55, maxWidth: 460, color:'rgba(246,242,234,.85)'}}>
              We deliver across Uluwatu and Canggu. Pick your location, then pick your app.
            </p>
            <div className="row" style={{marginTop: 22}}>
              <a className="btn btn-primary" href={LINKS.linktree} target="_blank" rel="noopener">All Links ↗</a>
              <a className="btn btn-ghost" href="#locations">Visit Us ↗</a>
            </div>
          </div>
          <div className="platforms">
            <a className="order-platform" href={LOCATIONS.Ungasan.gofood} target="_blank" rel="noopener">
              <span className="label">Ungasan</span>
              <span className="name">GoFood</span>
              <span style={{fontSize:12, opacity:.7}}>Order ↗</span>
            </a>
            <a className="order-platform" href={LOCATIONS.Ungasan.grab} target="_blank" rel="noopener">
              <span className="label">Ungasan</span>
              <span className="name">GrabFood</span>
              <span style={{fontSize:12, opacity:.7}}>Order ↗</span>
            </a>
            <a className="order-platform" href={LOCATIONS.Berawa.gofood} target="_blank" rel="noopener">
              <span className="label">Berawa</span>
              <span className="name">GoFood</span>
              <span style={{fontSize:12, opacity:.7}}>Order ↗</span>
            </a>
            <a className="order-platform" href={LOCATIONS.Berawa.grab} target="_blank" rel="noopener">
              <span className="label">Berawa</span>
              <span className="name">GrabFood</span>
              <span style={{fontSize:12, opacity:.7}}>Order ↗</span>
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="foot" data-screen-label="Footer">
      <div className="container">
        <div className="foot-grid">
          <div>
            <img src="assets/logo-flames.png" alt="Crave" style={{height: 80, filter:'brightness(1.1)'}} />
            <p style={{fontSize:14, lineHeight:1.6, marginTop: 16, maxWidth: 360, opacity:.8}}>
              Bali's loudest smash burger joint. Hand-smashed Angus, sauce from scratch, eaten with no mercy.
            </p>
          </div>
          <div>
            <h4>Visit</h4>
            <ul>
              <li><a href={LOCATIONS.Ungasan.maps} target="_blank" rel="noopener">Crave Ungasan ↗</a></li>
              <li><a href={LOCATIONS.Berawa.maps} target="_blank" rel="noopener">Crave Berawa ↗</a></li>
              <li><a href="#locations">Hours</a></li>
            </ul>
          </div>
          <div>
            <h4>Eat</h4>
            <ul>
              <li><a href="#menu">Smash Burgers</a></li>
              <li><a href="#menu">Sides</a></li>
              <li><a href="#menu">Shakes</a></li>
              <li><a href="#menu">Sauces</a></li>
            </ul>
          </div>
          <div>
            <h4>Follow</h4>
            <ul>
              <li><a href={LINKS.instagram} target="_blank" rel="noopener">Instagram ↗</a></li>
              <li><a href={LINKS.linktree} target="_blank" rel="noopener">Linktree ↗</a></li>
              <li><a href={LOCATIONS.Ungasan.gofood} target="_blank" rel="noopener">GoFood Ungasan ↗</a></li>
              <li><a href={LOCATIONS.Berawa.gofood} target="_blank" rel="noopener">GoFood Berawa ↗</a></li>
            </ul>
          </div>
        </div>
      </div>

      <h2 className="foot-mega">CRAVE · CRAVE · CRAVE ·</h2>

      <div className="container">
        <div className="foot-bottom">
          <span>© {new Date().getFullYear()} Crave Burger Co. · Stay Hungry.</span>
          <span>Made in Bali · 🇮🇩</span>
        </div>
        <div className="foot-credit">
          <a href="https://baliole.com" target="_blank" rel="noopener">
            Made with{' '}
            <svg className="foot-heart" viewBox="0 0 24 24" width="13" height="13" aria-hidden="true">
              <path d="M12 21s-7-4.35-7-10a4 4 0 017-2.65A4 4 0 0119 11c0 5.65-7 10-7 10z" fill="currentColor"/>
            </svg>{' '}
            by Baliole.com
          </a>
        </div>
      </div>
    </footer>
  );
}

function FullMenuModal({ open, onClose }) {
  if (!open) return null;
  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e=>e.stopPropagation()}>
        <button className="modal-close" onClick={onClose}>✕</button>
        <div className="check-strip check-rw" />
        <div style={{padding: '40px 48px 48px'}}>
          <div style={{textAlign:'center', marginBottom: 32}}>
            <span className="label" style={{color:'var(--red)'}}>★ The Full Menu ★</span>
            <h2 style={{fontFamily:'Bagel Fat One, serif', fontSize: 56, color:'var(--red)', margin:'8px 0 0', lineHeight:0.95}}>
              SMASH BURGER
            </h2>
          </div>

          <div className="modal-twocol">
            <div>
              {MENU_DATA.Burgers.map((it,i)=>(
                <div className="row leader" key={i}>
                  <span className="name" style={{textTransform:'uppercase', fontWeight:800}}>{it.name}</span>
                  <span className="dots" style={{flex:1, borderBottom:'2px dotted var(--black)', transform:'translateY(-5px)'}} />
                  <span style={{fontFamily:'Bagel Fat One, serif', color:'var(--red)', fontSize:22}}>{it.price}</span>
                </div>
              ))}
            </div>
            <div>
              <h3 style={{fontFamily:'Bagel Fat One, serif', color:'var(--red)', fontSize:24, margin:'0 0 14px'}}>CUSTOM IT</h3>
              {[['Fried Egg','10K'],['Crunchy Bacon','20K'],['Cheddar','15K'],['Beef Smash','75K'],['Chicken Smash','35K']].map(([n,p],i)=>(
                <div className="row leader" key={i}>
                  <span className="name" style={{textTransform:'uppercase', fontWeight:800}}>{n}</span>
                  <span className="dots" style={{flex:1, borderBottom:'2px dotted var(--black)', transform:'translateY(-5px)'}} />
                  <span style={{fontFamily:'Bagel Fat One, serif', color:'var(--red)', fontSize:20}}>{p}</span>
                </div>
              ))}
              <p style={{marginTop: 24, padding: 16, border: '2px solid var(--black)', textAlign:'center', fontSize:13, fontWeight:800, letterSpacing:'0.08em', textTransform:'uppercase'}}>
                All beef burgers served with 100% imported Australian Angus.
              </p>
            </div>
          </div>

          <div className="modal-threecol">
            {['Sides','Shakes','Sauces'].map(cat=>(
              <div key={cat}>
                <h3 style={{fontFamily:'Bagel Fat One, serif', color:'var(--red)', fontSize:22, margin:'0 0 12px'}}>{cat.toUpperCase()}</h3>
                {MENU_DATA[cat].map((it,i)=>(
                  <div className="row leader" key={i} style={{fontSize:13}}>
                    <span style={{textTransform:'uppercase', fontWeight:800}}>{it.name}</span>
                    <span className="dots" style={{flex:1, borderBottom:'2px dotted var(--black)', transform:'translateY(-5px)'}} />
                    <span style={{fontFamily:'Bagel Fat One, serif', color:'var(--red)', fontSize:16}}>{it.price}</span>
                  </div>
                ))}
              </div>
            ))}
          </div>

          <p style={{textAlign:'center', marginTop: 32, fontSize:11, letterSpacing:'0.12em', textTransform:'uppercase', color:'var(--mute)'}}>
            Gov tax 11% not included in prices
          </p>
        </div>
        <div className="check-strip check-rw" />
      </div>
    </div>
  );
}

function ContactSection() {
  const [status, setStatus] = React.useState('idle');  // idle | sending | success | error
  const [errorMsg, setErrorMsg] = React.useState('');
  const startedAt = React.useRef(Date.now());

  async function handleSubmit(e) {
    e.preventDefault();
    setStatus('sending');
    setErrorMsg('');

    const form = e.target;
    const fd = new FormData(form);
    const data = Object.fromEntries(fd.entries());

    const p = new URLSearchParams(window.location.search);
    Object.assign(data, {
      utm_source: p.get('utm_source') || '',
      utm_medium: p.get('utm_medium') || '',
      utm_campaign: p.get('utm_campaign') || '',
      utm_content: p.get('utm_content') || '',
      utm_term: p.get('utm_term') || '',
      _t: String(Date.now() - startedAt.current),
    });

    try {
      const res = await fetch(window.location.origin + '/__api/contact/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });
      const json = await res.json();
      if (json.ok) { form.reset(); setStatus('success'); }
      else { setStatus('error'); setErrorMsg(json.error || 'Something went wrong.'); }
    } catch (err) {
      setStatus('error');
      setErrorMsg('Network error. Please try again.');
    }
  }

  return (
    <section id="contact" className="contact-wrap" data-screen-label="Contact">
      <div className="container">
        <div className="contact-card reveal">
          <div className="contact-head">
            <span className="label" style={{color:'var(--red)'}}>★ Hit Us Up ★</span>
            <h2>SAY <span className="red">HELLO.</span></h2>
            <p>
              Catering. Private events. Press. Collabs.
              Drop a line — we read every one.
            </p>
            <div className="contact-direct">
              <span className="label">Or DM</span>
              <a href={LINKS.instagram} target="_blank" rel="noopener" className="contact-handle">
                @crave.indonesia ↗
              </a>
            </div>
          </div>

          <form onSubmit={handleSubmit} className="contact-form" noValidate>
            <input type="hidden" name="slug" value="crave" />

            <div className="form-row">
              <label className="field">
                <span>Name</span>
                <input name="name" required placeholder="Your name" autoComplete="name" />
              </label>
              <label className="field">
                <span>Email</span>
                <input name="email" type="email" required placeholder="you@example.com" autoComplete="email" />
              </label>
            </div>

            <label className="field">
              <span>What's up?</span>
              <textarea name="message" required rows={5} placeholder="Catering for 30, private dinner, press feature, collab idea…" />
            </label>

            {/* Honeypot — bots fill this, real users don't see it */}
            <input name="website" tabIndex={-1} autoComplete="off"
                   style={{position:'absolute',left:'-9999px',width:1,height:1,opacity:0}}
                   aria-hidden="true" />

            <button type="submit" className="btn btn-primary contact-submit" disabled={status==='sending'}>
              {status==='sending' ? 'Sending…' : 'Send Message ↗'}
            </button>

            {status==='success' && (
              <div className="contact-msg success">
                Got it. We'll come back to you within 24h.
              </div>
            )}
            {status==='error' && (
              <div className="contact-msg error">{errorMsg}</div>
            )}
          </form>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { MenuSection, LocationsSection, GallerySection, StorySection, OrderSection, ContactSection, Footer, FullMenuModal });
