/* Pōda Ksamil — menu website app */

const I18N = {
  EN: {
    reserve: 'Reserve', all: 'All', cocktails: 'Cocktails', menuNav: 'Menu',
    heroEyebrow: 'Beach Bar · Ksamil',
    heroTitle: 'Cocktails by the Ionian',
    heroSub: 'A read-only digital menu for the terrace at Pōda — scan, browse and order with the sunset on the water.',
    heroHours: 'Open till late', heroSeaview: 'Sea-view terrace',
    timeNote: 'From 23:00 · Long drinks only',
    barNav: 'Our list', footFind: 'Find us', footHours: 'Hours', footReach: 'Reach us',
    galEyebrow: 'The place', galTitle: 'Poda Bay', galSwing: 'The swing, Ksamil', galEntrance: 'Beach-bar entrance', galPineapple: 'Pineapple Coconut', galNight: 'After sunset',
    footNote: 'Prices in Albanian Lekë · Service included',
    cats: { 'non-alcoholic': 'Non-alcoholic', signature: 'Signatures', classics: 'Classics' },
    toast: 'Reservations: call +355 69 896 6814',
  },
  SQ: {
    reserve: 'Rezervo', all: 'Të gjitha', cocktails: 'Kokteile', menuNav: 'Menu',
    heroEyebrow: 'Bar Plazhi · Ksamil',
    heroTitle: 'Kokteil buzë Jonit',
    heroSub: 'Menu dixhitale vetëm për lexim në tarracën e Pōda — skano, shfleto dhe porosit me perëndimin mbi det.',
    heroHours: 'Hapur deri vonë', heroSeaview: 'Tarracë me pamje deti',
    timeNote: 'Nga ora 23:00 · Vetëm long drinks',
    barNav: 'Lista jonë', footFind: 'Na gjeni', footHours: 'Orari', footReach: 'Na kontaktoni',
    galEyebrow: 'Vendi', galTitle: 'Gjiri i Podës', galSwing: 'Lëkundësja, Ksamil', galEntrance: 'Hyrja e bar-plazhit', galPineapple: 'Ananas & Kokos', galNight: 'Pas perëndimit',
    footNote: 'Çmimet në Lekë · Shërbimi i përfshirë',
    cats: { 'non-alcoholic': 'Pa alkool', signature: 'Speciale', classics: 'Klasike' },
    toast: 'Rezervime: telefono +355 69 896 6814',
  },
  IT: {
    reserve: 'Prenota', all: 'Tutti', cocktails: 'Cocktail', menuNav: 'Menu',
    heroEyebrow: 'Beach Bar · Ksamil',
    heroTitle: 'Cocktail sullo Ionio',
    heroSub: 'Un menù digitale di sola lettura per la terrazza del Pōda — scansiona, sfoglia e ordina al tramonto sul mare.',
    heroHours: 'Aperto fino a tardi', heroSeaview: 'Terrazza vista mare',
    timeNote: 'Dalle 23:00 · Solo long drinks',
    barNav: 'La nostra lista', footFind: 'Dove siamo', footHours: 'Orari', footReach: 'Contatti',
    galEyebrow: 'Il luogo', galTitle: 'Baia di Poda', galSwing: "L'altalena, Ksamil", galEntrance: 'Ingresso del beach bar', galPineapple: 'Ananas e Cocco', galNight: 'Dopo il tramonto',
    footNote: 'Prezzi in Lekë · Servizio incluso',
    cats: { 'non-alcoholic': 'Analcolici', signature: 'Signature', classics: 'Classici' },
    toast: 'Prenotazioni: chiama +355 69 896 6814',
  },
};

/* Inline lucide SVGs, rendered/owned entirely by React (no data-lucide / no
   lucide.createIcons mutation). The rail mounts, unmounts and recolors its
   icons on every interaction, and letting lucide swap <i> for <svg> under
   React's feet caused "removeChild: node is not a child" crashes. */
const RAIL_ICONS = {
  'martini': '<path d="M8 22h8"/><path d="M12 11v11"/><path d="m19 3-7 8-7-8Z"/>',
  'chevron-left': '<path d="m15 18-6-6 6-6"/>',
  'chevron-right': '<path d="m9 18 6-6-6-6"/>',
  'list': '<path d="M3 5h18"/><path d="M3 12h18"/><path d="M3 19h18"/>',
  'x': '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
  'coffee': '<path d="M10 2v2"/><path d="M14 2v2"/><path d="M16 8a1 1 0 0 1 1 1v8a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1h14a4 4 0 1 1 0 8h-1"/><path d="M6 2v2"/>',
  'cup-soda': '<path d="m6 8 1.75 12.28a2 2 0 0 0 2 1.72h4.54a2 2 0 0 0 2-1.72L18 8"/><path d="M5 8h14"/><path d="M7 15a6.47 6.47 0 0 1 5 0 6.47 6.47 0 0 0 5 0"/><path d="m12 8 1-6h2"/>',
  'beer': '<path d="M17 11h1a3 3 0 0 1 0 6h-1"/><path d="M9 12v6"/><path d="M13 12v6"/><path d="M14 7.5c-1 0-1.44.5-3 .5s-2-.5-3-.5-1.72.5-2.5.5a2.5 2.5 0 0 1 0-5c.78 0 1.57.5 2.5.5S9.44 2 11 2s2 1.5 3 1.5 1.72-.5 2.5-.5a2.5 2.5 0 0 1 0 5c-.78 0-1.5-.5-2.5-.5Z"/><path d="M5 8v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"/>',
  'wine': '<path d="M8 22h8"/><path d="M7 10h10"/><path d="M12 15v7"/><path d="M12 15a5 5 0 0 0 5-5c0-2-.5-4-2-8H9c-1.5 4-2 6-2 8a5 5 0 0 0 5 5Z"/>',
  'glass-water': '<path d="M5.116 4.104A1 1 0 0 1 6.11 3h11.78a1 1 0 0 1 .994 1.105L17.19 20.21A2 2 0 0 1 15.2 22H8.8a2 2 0 0 1-2-1.79z"/><path d="M6 12a5 5 0 0 1 6 0 5 5 0 0 0 6 0"/>',
  'citrus': '<path d="M21.66 17.67a1.08 1.08 0 0 1-.04 1.6A12 12 0 0 1 4.73 2.38a1.1 1.1 0 0 1 1.61-.04z"/><path d="M19.65 15.66A8 8 0 0 1 8.35 4.34"/><path d="m14 10-5.5 5.5"/><path d="M14 17.85V10H6.15"/>',
  'sparkles': '<path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/><path d="M20 3v4"/><path d="M22 5h-4"/><path d="M4 17v2"/><path d="M5 18H3"/>',
};

function RailIcon({ name, size = 16, color = 'currentColor', style = {} }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24"
      fill="none" stroke={color} strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"
      style={{ flex: '0 0 auto', display: 'block', ...style }}
      dangerouslySetInnerHTML={{ __html: RAIL_ICONS[name] || '' }} />
  );
}

/* Floating right-edge navigation rail. Collapsed by default to icons-only so
   the menu stays readable; the header "Menu" button expands it to icon+label.
   Cocktail categories collapse into one "Cocktails" entry whose click opens a
   flyout of its sub-groups. Picking any item navigates and re-collapses. */
function SideRail({ DATA, lang, t, active, goTo, expanded, setExpanded, flyoutOpen, setFlyoutOpen }) {
  const lc = (lang || 'EN').toLowerCase();
  const cocktails = DATA.categories.filter((c) => !c.simple);
  const simples = DATA.categories.filter((c) => c.simple);
  const cocktailActive = cocktails.some((c) => c.id === active);
  const cocktailsHot = cocktailActive || flyoutOpen;

  const btn = (isActive, accent) => ({
    display: 'flex', alignItems: 'center', gap: expanded ? 9 : 0,
    justifyContent: expanded ? 'flex-start' : 'center',
    width: expanded ? '100%' : 40, height: 40,
    padding: expanded ? '0 12px' : 0, borderRadius: 'var(--radius-pill)', textAlign: 'left',
    border: '1px solid ' + (isActive ? 'transparent' : 'var(--border-subtle)'),
    background: isActive ? (accent || 'var(--brand-primary)') : 'transparent',
    color: isActive ? 'var(--text-on-dark)' : 'var(--text-body)',
    font: 'var(--weight-semibold) 11px/1 var(--font-body)',
    letterSpacing: '0.05em', textTransform: 'uppercase', whiteSpace: 'nowrap',
    cursor: 'pointer', appearance: 'none',
    transition: 'background var(--dur-fast) var(--ease-soft), color var(--dur-fast), border-color var(--dur-fast), width var(--dur-fast)',
  });
  const ink = (on) => (on ? 'var(--text-on-dark)' : 'var(--sea-600)');

  const pick = (id) => { setFlyoutOpen(false); setExpanded(false); goTo(id); };

  return (
    <React.Fragment>
      {flyoutOpen ? (
        <div onClick={() => setFlyoutOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 39 }} aria-hidden="true" />
      ) : null}

      <div style={{ position: 'fixed', right: 12, top: '50%', transform: 'translateY(-50%)', zIndex: 41, display: 'flex', alignItems: 'flex-start', gap: 10 }}>
        {/* flyout — cocktail sub-groups, rendered on top to the left of the rail (always labelled) */}
        {flyoutOpen ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4, padding: 10, background: '#fff', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)', border: '1px solid var(--border-subtle)', minWidth: 188 }}>
            <span style={{ font: 'var(--role-overline)', letterSpacing: 'var(--tracking-wider)', textTransform: 'uppercase', color: 'var(--text-accent)', padding: '2px 8px 6px' }}>{t.cocktails}</span>
            {cocktails.map((c) => {
              const on = c.id === active;
              return (
                <button key={c.id} type="button" onClick={() => pick(c.id)}
                  style={{ display: 'flex', alignItems: 'center', gap: 9, width: '100%', height: 'auto', padding: '8px 12px', borderRadius: 'var(--radius-pill)', textAlign: 'left', border: '1px solid ' + (on ? 'transparent' : 'var(--border-subtle)'), background: on ? 'var(--brand-primary)' : 'transparent', color: on ? 'var(--text-on-dark)' : 'var(--text-body)', font: 'var(--weight-semibold) 11px/1 var(--font-body)', letterSpacing: '0.05em', textTransform: 'uppercase', whiteSpace: 'nowrap', cursor: 'pointer', appearance: 'none' }}>
                  <RailIcon name={c.icon} size={16} color={ink(on)} />
                  <span style={{ flex: 1 }}>{c.label[lc]}</span>
                </button>
              );
            })}
          </div>
        ) : null}

        {/* rail */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, padding: 8, background: expanded ? 'rgba(255,255,255,0.94)' : 'transparent', backdropFilter: expanded ? 'saturate(140%) blur(8px)' : 'none', borderRadius: 'var(--radius-lg)', boxShadow: expanded ? 'var(--shadow-lg)' : 'none', border: expanded ? '1px solid var(--border-subtle)' : '1px solid transparent', maxHeight: '88vh', overflowY: 'auto', transition: 'background var(--dur-fast), box-shadow var(--dur-fast)' }}>
          {/* open/close arrow — expands the rail to icon+label and back */}
          <button type="button" aria-label={t.menuNav} title={expanded ? t.menuNav : t.menuNav} onClick={() => { setFlyoutOpen(false); setExpanded((v) => !v); }}
            style={{ display: 'flex', alignItems: 'center', justifyContent: expanded ? 'space-between' : 'center', width: expanded ? '100%' : 40, height: 32, padding: expanded ? '0 11px' : 0, border: 'none', background: 'transparent', color: 'var(--sea-600)', cursor: 'pointer', appearance: 'none', font: 'var(--weight-semibold) 10px/1 var(--font-body)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
            {expanded ? <span>{t.menuNav}</span> : null}
            <RailIcon name={expanded ? 'chevron-right' : 'chevron-left'} size={18} color="var(--sea-600)" />
          </button>
          <div style={{ height: 1, background: 'var(--border-subtle)', margin: '0 3px 3px' }} aria-hidden="true" />

          <button type="button" title={t.cocktails} onClick={() => setFlyoutOpen((v) => !v)}
            style={btn(cocktailsHot, cocktailActive ? 'var(--brand-primary)' : 'var(--sea-700)')}>
            <RailIcon name="martini" size={16} color={cocktailsHot ? 'var(--text-on-dark)' : 'var(--sea-600)'} />
            {expanded ? <span style={{ flex: 1 }}>{t.cocktails}</span> : null}
            {expanded ? (
              <RailIcon name="chevron-left" size={13} color={cocktailsHot ? 'var(--text-on-dark)' : 'var(--slate-400)'}
                style={{ transform: flyoutOpen ? 'rotate(-90deg)' : 'none', transition: 'transform var(--dur-fast)' }} />
            ) : null}
          </button>

          {simples.map((c) => {
            const on = c.id === active;
            return (
              <button key={c.id} type="button" title={c.label[lc]} onClick={() => pick(c.id)} style={btn(on)}>
                <RailIcon name={c.icon} size={16} color={ink(on)} />
                {expanded ? <span style={{ flex: 1 }}>{c.label[lc]}</span> : null}
              </button>
            );
          })}
        </div>
      </div>
    </React.Fragment>
  );
}

function App() {
  const DATA = window.PODA_MENU;
  const [lang, setLang] = React.useState('EN');
  const [active, setActive] = React.useState('non-alcoholic');
  const [navExpanded, setNavExpanded] = React.useState(false);
  const [flyoutOpen, setFlyoutOpen] = React.useState(false);
  const [toast, setToast] = React.useState(null);
  const t = I18N[lang];
  const narrow = useIsNarrow();
  const refs = React.useRef({});
  const rootRef = React.useRef(null);
  const lockUntil = React.useRef(0);

  const registerRef = (id, el) => { if (el) refs.current[id] = el; };

  // hydrate Lucide icons after every render
  React.useEffect(() => {
    if (window.lucide && window.lucide.createIcons) {
      window.lucide.createIcons({ attrs: { 'stroke-width': 1.6 } });
    }
  });

  const goTo = (id) => {
    setActive(id);
    const el = refs.current[id];
    const root = rootRef.current;
    if (!el || !root) return;
    lockUntil.current = Date.now() + 700;
    // direct assignment always moves the container; CSS scroll-behavior adds easing where supported
    root.scrollTop = Math.max(0, el.offsetTop - 74);
  };

  // scroll-spy
  React.useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    const onScroll = () => {
      if (Date.now() < lockUntil.current) return;
      const y = root.scrollTop + 130;
      let current = DATA.categories[0].id;
      for (const c of DATA.categories) {
        const el = refs.current[c.id];
        if (el && el.offsetTop <= y) current = c.id;
      }
      setActive(current);
    };
    root.addEventListener('scroll', onScroll, { passive: true });
    return () => root.removeEventListener('scroll', onScroll);
  }, []);

  const showToast = () => { setToast(t.toast); clearTimeout(showToast._tid); showToast._tid = setTimeout(() => setToast(null), 3200); };

  return (
    <div ref={rootRef} data-scroll-root style={{ height: '100%', overflowY: 'auto', overflowX: 'hidden', background: 'var(--surface-page)', position: 'relative' }}>
      <div style={{ position: 'relative', background: 'var(--sea-700)' }}>
        <SiteHeader lang={lang} setLang={setLang} t={t} onReserve={showToast} />
        <Hero t={t} />
      </div>

      <SideRail DATA={DATA} lang={lang} t={t} active={active} goTo={goTo}
        expanded={navExpanded} setExpanded={setNavExpanded}
        flyoutOpen={flyoutOpen} setFlyoutOpen={setFlyoutOpen} />

      <main style={{ maxWidth: 'var(--container-wide)', margin: '0 auto', padding: '8px 72px 20px 28px' }}>
        {(() => {
          const parts = t.timeNote.split(' · ');
          return (
            <div style={{ display: 'flex', justifyContent: 'center', margin: '28px 0 8px' }}>
              <span style={{
                display: 'inline-flex',
                flexDirection: narrow ? 'column' : 'row',
                alignItems: 'center', gap: narrow ? 5 : 9,
                padding: narrow ? '11px 22px' : '9px 20px', borderRadius: 'var(--radius-pill)',
                border: '1px solid var(--gold-500)',
                background: 'linear-gradient(135deg, rgba(196,150,58,0.16), rgba(196,150,58,0.04))',
                color: 'var(--gold-600)',
                fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 12.5, lineHeight: 1,
                letterSpacing: '0.16em', textTransform: 'uppercase', textAlign: 'center',
                boxShadow: '0 2px 12px rgba(196,150,58,0.2)',
              }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                  <window.Icon name="moon" size={15} strokeWidth={1.6} color="var(--gold-600)" />
                  {parts[0]}
                </span>
                {parts[1] ? (
                  narrow
                    ? <span>{parts[1]}</span>
                    : <React.Fragment><span aria-hidden="true">·</span><span>{parts[1]}</span></React.Fragment>
                ) : null}
              </span>
            </div>
          );
        })()}
        {DATA.categories.map((c, i) => (
          <React.Fragment key={c.id}>
            <MenuSection category={c} items={DATA.items[c.id]} registerRef={registerRef} lang={lang} />
            {i < DATA.categories.length - 1 ? (
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <window.KsamilMenuDesignSystem_d0403b.OrnamentDivider tone="gold" width={90} />
              </div>
            ) : null}
          </React.Fragment>
        ))}
      </main>

      <Gallery t={t} />
      <SiteFooter t={t} />

      {/* reserve toast */}
      <div style={{
        position: 'fixed', left: '50%', bottom: toast ? 28 : -80, transform: 'translateX(-50%)',
        transition: 'bottom var(--dur-base) var(--ease-out)', zIndex: 50,
        background: 'var(--navy-800)', color: '#fff', padding: '13px 20px', borderRadius: 'var(--radius-pill)',
        boxShadow: 'var(--shadow-lg)', font: 'var(--weight-medium) 13px/1 var(--font-body)', letterSpacing: '0.02em',
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <window.Icon name="phone" size={15} color="var(--gold-500)" /> {toast}
      </div>
    </div>
  );
}

window.App = App;
