const PRODUCERS = [
  { name: 'La Cadalora',       region: 'Trentino',     mono: 'serif-caps',   logo: 'https://images.squarespace-cdn.com/content/v1/589b041c1e5b6c546fd6d6ec/1498729827440-YWY1Z9EA03KMD9GWLVCH/Cadalora+col+nero+960px+%230.png' },
  { name: 'Prendina',          region: 'Lombardia',    mono: 'serif-italic', logo: 'https://marcdegrazia.com/wp-content/uploads/2021/07/logo_prendoina.png' },
  { name: 'San Cristofaro',    region: 'Franciacorta', mono: 'serif-caps',   logo: 'https://www.sancristoforo.eu/franciacorta/wp-content/uploads/2020/06/SC_logo_white-2.png', logoInvert: true },
  { name: 'Terre del Faet',    region: 'Collio',       mono: 'script' },
  { name: 'Tenuta Stella',     region: 'Friuli',       mono: 'serif-caps',   logo: 'https://www.tenutastellacollio.it/cms/wp-content/themes/tenutastella/images/stella.png' },
  { name: 'Cavalchina',        region: 'Veneto',       mono: 'serif-italic', logo: 'https://marcdegrazia.com/wp-content/uploads/2021/05/logo_cavalchina.png' },
  { name: 'Martignago',        region: 'Asolo',        mono: 'serif-caps',   logo: 'https://martignago.wine/wp-content/uploads/2022/02/logo-martignago-vinaioli-1.png' },
  { name: "Torre d'Orti",      region: 'Valpolicella', mono: 'serif-italic', logo: 'https://marcdegrazia.com/wp-content/uploads/2021/07/logo_torre_dorti-1.png' },
  { name: 'Cascina Sot',       region: 'Barolo',       mono: 'initials',     logo: 'https://cascinasot.com/wp-content/uploads/CascinaSot_Nero@05x.png' },
  { name: 'La Smeralda',       region: 'Colline Novaresi', mono: 'script', logo: 'https://www.cantinalasmeralda.it/cdn/shop/files/La-Smeralda-Logo.png?v=1730739788&width=300' },
  { name: 'Malabaila',         region: 'Roero',        mono: 'serif-italic', logo: 'https://marcdegrazia.com/wp-content/uploads/2021/05/logo_malabaila-1.png' },
  { name: 'Negri',             region: 'Piemonte',     mono: 'serif-caps',   logo: 'https://marcdegrazia.com/wp-content/uploads/2022/10/logo_negri.png' },
  { name: 'Le Origini dal 1919', region: 'Emilia Romagna', mono: 'serif-italic', logo: 'https://www.tenutaleorigini1919.it/wp-content/uploads/2024/02/logo-tenuta-le-origini-1919-modena.png', logoBoost: true },
  { name: 'Tenuta La Viola',    region: 'Romagna',        mono: 'serif-caps',  logo: 'https://www.consorziovinidiromagna.it/wpsite/wp-content/uploads/tenuta-la-viola.png' },
  { name: 'Barbicaia',         region: 'Montepulciano', mono: 'serif-caps',  logo: 'https://marcdegrazia.com/wp-content/uploads/2021/11/logo_barbicaia.png' },
  { name: 'G. Meletti Cavallari', region: 'Bolgheri',  mono: 'initials',     logo: 'https://giorgiomeletticavallari.com/wp-content/uploads/2016/05/logo_meletti.png' },
  { name: 'Girasasso',         region: 'Toscana',      mono: 'script' },
  { name: 'Il Fauno',          region: 'Bolgheri',     mono: 'serif-caps' },
  { name: 'Il Palazzino',      region: 'Chianti Classico', mono: 'serif-caps', logo: 'https://marcdegrazia.com/wp-content/uploads/2021/07/logo_il_palazzino.png' },
  { name: 'Il Pino',           region: 'Montalcino',   mono: 'serif-italic', logo: 'https://marcdegrazia.com/wp-content/uploads/2021/05/logo_del_pino.png' },
  { name: 'Villa i Cipressi',  region: 'Montalcino',   mono: 'script',       logo: 'https://marcdegrazia.com/wp-content/uploads/2024/05/logo_VILLA_I_CIPRESSI.png' },
  { name: 'Villanoviana',      region: 'Bolgheri',     mono: 'serif-caps',   logo: 'https://villanoviana.it/wp-content/uploads/2020/06/VILLANOVIANA_logo-1-1.png' },
  { name: 'New producer',      region: 'Bolgheri',     mono: 'serif-caps',   logo: 'https://static.wixstatic.com/media/d11548_ca1a158d43234674aba474b4c3454180~mv2.png' },
  { name: 'Villa Ligi',        region: 'Pergola',      mono: 'serif-italic', logo: 'https://www.villaligi.it/img/logo-villa-ligi.png' },
  { name: 'Zena',              region: 'Castelli di Jesi', mono: 'initials', logo: 'https://zenavini.it/wp-content/uploads/2023/07/logo-zena-450.png' },
  { name: 'Filomusi',          region: 'Abruzzo',      mono: 'script',       logo: 'https://www.filomusiguelfi.it/wp-content/uploads/2019/08/cropped-logoprova6sito-1-2.png' },
  { name: 'San Donatino',      region: 'Chianti Classico', mono: 'serif-caps', logo: 'https://www.sandonatino.com/wp-content/uploads/2024/06/logo-san-donatino.svg', logoBoost: true },
  { name: 'Neri',              region: 'Piemonte',     mono: 'serif-caps',   logo: 'https://www.pscdn.it/img/169/25/04/11244-logo-footer.webp' },
];

const LANGUAGES = [
  { code: 'en', label: 'EN' },
];

function ProducerLogo({ p }) {
  const [failed, setFailed] = React.useState(false);

  if (p.logo && !failed) {
    return (
      <div className="plogo plogo--img">
        <div className="plogo__body">
          <img
            className={'plogo__img' + (p.logoInvert ? ' plogo__img--invert' : '') + (p.logoBoost ? ' plogo__img--boost' : '')}
            src={p.logo}
            alt={p.name}
            loading="lazy"
            onError={() => setFailed(true)}
          />
        </div>
        <span className="plogo__region">{p.region}</span>
      </div>
    );
  }

  const initials = p.name
    .split(/[\s']/).filter(Boolean)
    .map(w => w[0])
    .join('')
    .toUpperCase()
    .slice(0, 3);

  if (p.mono === 'initials') {
    return (
      <div className="plogo plogo--initials">
        <div className="plogo__body">
          <span className="plogo__big">{initials}</span>
          <span className="plogo__rule"/>
          <span className="plogo__name">{p.name}</span>
        </div>
        <span className="plogo__region">{p.region}</span>
      </div>
    );
  }
  if (p.mono === 'script') {
    return (
      <div className="plogo plogo--script">
        <div className="plogo__body">
          <span className="plogo__script">{p.name}</span>
        </div>
        <span className="plogo__region">est. · {p.region}</span>
      </div>
    );
  }
  if (p.mono === 'serif-caps') {
    return (
      <div className="plogo plogo--caps">
        <div className="plogo__body">
          <span className="plogo__caps">{p.name}</span>
          <span className="plogo__rule"/>
        </div>
        <span className="plogo__region">{p.region} · Italia</span>
      </div>
    );
  }
  // serif-italic
  const [first, ...rest] = p.name.split(' ');
  return (
    <div className="plogo plogo--italic">
      <div className="plogo__body">
        <span className="plogo__italic">
          <em>{first}</em>{rest.length ? ' ' + rest.join(' ') : ''}
        </span>
      </div>
      <span className="plogo__region">— {p.region} —</span>
    </div>
  );
}

const HERO_IMG = (typeof window !== 'undefined' && window.__resources && window.__resources.heroImg) || 'https://images.unsplash.com/photo-1504279577054-acfeccf8fc52?w=2000&q=80';
const MID_IMG  = (typeof window !== 'undefined' && window.__resources && window.__resources.midImg)  || 'https://images.unsplash.com/photo-1506377247377-2a5b3b417ebb?w=2000&q=80';

const R = (typeof window !== 'undefined' && window.__resources) || {};
const JOURNAL = [
  {
    href: 'journal-neri.html',
    img: 'https://marcdegrazia.com/wp-content/uploads/2026/01/header_neri.jpg',
    kicker: 'Producer profile',
    date: 'April 2026',
    title: 'Neri \u2014 Etna Nord, fourth generation.',
    excerpt: 'Over a century ago, a knight named Vincenzo returned from America and bought volcanic land above Linguaglossa. His great-grandchildren are still there \u2014 making wine at 600 metres on the north-east slope.',
  },
  {
    href: 'journal-villanoviana.html',
    img: 'https://villanoviana.it/wp-content/uploads/2025/10/DSC04388_botte.jpg',
    kicker: 'Producer profile',
    date: 'March 2026',
    title: 'Villanoviana \u2014 built from scratch in Bolgheri.',
    excerpt: 'Marco Belli and Barbara Monacelli bought raw land near the famous cypress avenue in 2006. No existing winery, no inherited vines \u2014 and now some of the most serious wine in the appellation.',
  },
  {
    href: 'Journal-Post.html',
    img: 'https://images.squarespace-cdn.com/content/v1/589b041c1e5b6c546fd6d6ec/1489404279520-FFY77GIF37Z2GNFSGUAT/La+Cadalora+-+Panorama+Primavera.jpg',
    kicker: 'Producer profile',
    date: 'February 2026',
    title: 'La Cadalora \u2014 Vallagarina, cru by cru.',
    excerpt: 'The Tomasi family farms twelve hectares above the Adige at altitudes from 180 to 350 metres. Five named crus, seven wines, and a pre-phylloxera indigenous variety that almost nobody else still makes.',
  },
];

function Header({ lang, setLang, t }) {
  const [navOpen, setNavOpen] = React.useState(false);
  const close = () => setNavOpen(false);
  return (
    <header className="list-hero__head">
      <a className="list-hero__logo-wrap" href="#top" aria-label="Enovia Selections" onClick={close}>
        <img className="list-hero__logo" src="assets/logo-enovia.png" alt="Enovia Selections"/>
      </a>
      <button
        className="list-nav-toggle"
        type="button"
        aria-expanded={navOpen}
        aria-controls="primary-nav"
        aria-label={navOpen ? 'Close menu' : 'Open menu'}
        onClick={() => setNavOpen(v => !v)}
      >
        {navOpen ? 'CLOSE' : 'MENU'}
      </button>
      <nav
        id="primary-nav"
        className={'list-nav' + (navOpen ? ' is-open' : '')}
        aria-label="Primary"
      >
        <a href="#producers" onClick={close}>{t.nav_producers}</a>
        <a href="#how" onClick={close}>{t.nav_how}</a>
        <a href="#journal" onClick={close}>{t.nav_journal}</a>
        <a href="#events" onClick={close}>Events</a>
        <a href="#contact" onClick={close}>{t.nav_contact}</a>
      </nav>
    </header>
  );
}

function ProducerSlider({ producers, label, count }) {
  const trackRef = React.useRef(null);
  const [paused, setPaused] = React.useState(false);
  const manualOffsetRef = React.useRef(0); // px, relative to zero = animation start
  const loopWidthRef = React.useRef(0);

  // compute one-loop width once on mount/layout
  React.useEffect(() => {
    const el = trackRef.current;
    if (!el) return;
    const update = () => { loopWidthRef.current = el.scrollWidth / 2; };
    update();
    const ro = new ResizeObserver(update);
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  const applyPausedState = (isPaused) => {
    const el = trackRef.current;
    if (!el) return;
    if (isPaused) {
      // Freeze at current visual position, kill animation
      const m = new DOMMatrix(getComputedStyle(el).transform);
      manualOffsetRef.current = m.m41;
      el.style.animation = 'none';
      el.style.transform = `translate3d(${m.m41}px, 0, 0)`;
    } else {
      // Resume from animation start (simpler, avoids animation-delay math drift)
      el.style.animation = '';
      el.style.transform = '';
      manualOffsetRef.current = 0;
    }
  };

  const togglePause = () => {
    const next = !paused;
    setPaused(next);
    applyPausedState(next);
  };

  const step = (dir) => {
    const el = trackRef.current;
    if (!el) return;
    // Force paused state if not already
    if (!paused) {
      setPaused(true);
      applyPausedState(true);
    }
    const cell = el.querySelector('.plogo-cell');
    if (!cell) return;
    const cs = getComputedStyle(cell);
    const w = cell.offsetWidth + parseFloat(cs.marginLeft || 0) + parseFloat(cs.marginRight || 0);
    const loop = loopWidthRef.current || (el.scrollWidth / 2);
    let next = manualOffsetRef.current + (dir === 'next' ? -w : w);
    // keep within [-loop, 0] for seamless looping
    if (next <= -loop) next += loop;
    if (next > 0) next -= loop;
    manualOffsetRef.current = next;
    el.style.transform = `translate3d(${next}px, 0, 0)`;
  };

  const onEnter = () => {
    if (paused) return;
    const el = trackRef.current;
    if (el) el.style.animationPlayState = 'paused';
  };
  const onLeave = () => {
    if (paused) return;
    const el = trackRef.current;
    if (el) el.style.animationPlayState = 'running';
  };

  return (
    <section className="pslider" aria-label={label} onMouseEnter={onEnter} onMouseLeave={onLeave}>
      <div className="pslider__track" ref={trackRef}>
        {[...producers, ...producers].map((p, i) => (
          <div className="plogo-cell" key={i} aria-hidden={i >= producers.length}>
            <ProducerLogo p={p} />
          </div>
        ))}
      </div>
      <div className="pslider__ctrls">
        <span className="pslider__count">{count}</span>
        <div className="pslider__btns" role="group" aria-label="Slider controls">
          <button type="button" className="pslider__btn" onClick={() => step('prev')} aria-label="Previous">‹</button>
          <button type="button" className="pslider__btn pslider__btn--play" onClick={togglePause} aria-label={paused ? 'Play' : 'Pause'}>
            {paused ? '▶' : '❚❚'}
          </button>
          <button type="button" className="pslider__btn" onClick={() => step('next')} aria-label="Next">›</button>
        </div>
      </div>
    </section>
  );
}

function ContactTabs({ t }) {
  const [tab, setTab] = React.useState('importer');
  return (
    <>
      <div className="ctabs">
        <button className={'ctab' + (tab === 'importer' ? ' is-active' : '')} onClick={() => setTab('importer')}>
          I&#8217;m an importer
        </button>
        <button className={'ctab' + (tab === 'producer' ? ' is-active' : '')} onClick={() => setTab('producer')}>
          I&#8217;m a producer
        </button>
      </div>

      {tab === 'importer' && (
        <footer className="listino__foot">
          <div className="listino__foot-copy">
            {t.foot_copy_l1}<br/>{t.foot_copy_l2}<br/>{t.foot_copy_l3}<br/><em>{t.foot_copy_em}</em>
          </div>
          <div className="listino__contact">
            <span className="listino__contact-lbl">{t.lbl_office}</span>
            <span>{t.office_val}</span>
            <span className="listino__contact-lbl">{t.lbl_email}</span>
            <a className="big" href="mailto:info@enoviaselections.com">info@enoviaselections.com</a>
            <span className="listino__contact-lbl">{t.lbl_catalogue}</span>
            <a href="https://enoviaselections.com/catalog/" target="_blank" rel="noreferrer">enoviaselections.com/catalog &#8594;</a>
          </div>
        </footer>
      )}

      {tab === 'producer' && (
        <div className="growers growers--embed">
          <div className="growers__inner">
            <header className="growers__head">
              <span className="growers__eyebrow">For Italian winemakers</span>
              <h2>If you make wine worth drinking,<br/><em>we would like to meet you.</em></h2>
              <p className="growers__lede">We add one or two growers to the book each year &#8212; no more. The list below is not a checklist; it is how we think. Read it, and if you still recognise your cellar in it, write to us. A real person reads every message.</p>
            </header>
            <div className="growers__cols">
              <section className="growers__col">
                <h3>What we look for</h3>
                <ul>
                  <li><strong>A family, or something close to it.</strong> We prefer domaines where the person who takes the call is also the person who picks the grapes.</li>
                  <li><strong>A place that means something.</strong> Native grapes, honest appellations, a slope we can point to on a map.</li>
                  <li><strong>Wines that taste of somewhere.</strong> We will forgive a short label before we will forgive an anonymous wine.</li>
                  <li><strong>Production at human scale.</strong> Five thousand to a hundred and fifty thousand bottles, give or take.</li>
                  <li><strong>An opening in the Benelux.</strong> We can&#8217;t fight an existing importer for your stock. We&#8217;d rather find a grower who needs us.</li>
                </ul>
              </section>
              <section className="growers__col">
                <h3>What we won&#8217;t do</h3>
                <ul>
                  <li><strong>Private label or contract bottlings.</strong> We sell wines with a grower&#8217;s name on the front.</li>
                  <li><strong>Industrial volumes at industrial prices.</strong> That market is well served. It isn&#8217;t us.</li>
                  <li><strong>Exclusivity we can&#8217;t honour.</strong> If we can&#8217;t place your wines properly, we won&#8217;t hold them back from someone who can.</li>
                  <li><strong>Six-month payment terms.</strong> You get paid when the wine ships. Always.</li>
                  <li><strong>Silence.</strong> If we pass, we write back and tell you why.</li>
                </ul>
              </section>
            </div>
            <div className="growers__foot">
              <div className="growers__how">
                <span className="growers__how-lbl">How to write</span>
                <p>A paragraph is enough. Tell us who you are, where you are, and which wine you would pour first. Send a tech sheet if you have one &#8212; otherwise just a photo of the label works.</p>
              </div>
              <a className="growers__btn" href="mailto:growers@enoviaselections.com?subject=Grower%20submission%20%E2%80%94%20[your%20estate]">
                <span>Write to growers@enoviaselections.com</span>
                <span aria-hidden="true">&#8594;</span>
              </a>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

function Listino() {
  const [lang, setLang] = React.useState('en');
  React.useEffect(() => {
    try { localStorage.setItem('enovia-lang', lang); } catch {}
    document.documentElement.lang = lang;
  }, [lang]);
  const t = STRINGS[lang] || STRINGS.en;

  return (
    <div className="listino-wrap" id="top">

      {/* =============== HERO — full-bleed photograph =============== */}
      <section className="list-hero">
        <div className="list-hero__photo" style={{ backgroundImage: `url(${HERO_IMG})` }}/>
        <div className="list-hero__veil"/>
        <Header lang={lang} setLang={setLang} t={t} />
        <div className="list-hero__title">
          <span className="list-hero__eyebrow">{t.eyebrow}</span>
          <h1 style={{ fontSize: '100px' }}>
            {t.hero_l1}<em>{t.hero_em}</em>{t.hero_l2}
          </h1>
        </div>
        <figcaption className="list-hero__caption">
          <em>{t.hero_caption}</em>
        </figcaption>
      </section>

      {/* =============== PAPER BODY =============== */}
      <article className="listino">

        {/* MANIFESTO — no kicker, no signoff */}
        <section className="listino__manifesto">
          <p>{t.m1}</p>
          <p>{t.m2}</p>
          <p className="listino__sign">{t.m3_line}</p>
        </section>

        {/* CHAPTER I */}
        <header className="listino__chapter" id="producers">
          <span className="listino__chapter-n">{t.ch1_n}</span>
          <h2>{t.ch1_h}</h2>
          <p>{t.ch1_p}</p>
        </header>
      </article>

      {/* ============ PRODUCER LOGO SLIDER — full width, continuous marquee ============ */}
      <ProducerSlider producers={PRODUCERS} label={t.ch1_h} count={t.slider_count} t={t} />

      {/* MID-BREAK PHOTO */}
      <figure className="list-break">
        <div className="list-break__photo" style={{ backgroundImage: `url(${MID_IMG})` }}/>
        <figcaption><em>{t.cap_mid}</em></figcaption>
      </figure>

      <article className="listino listino--continued">

        {/* CATALOGUE LINK */}
        <aside className="listino__more">
          <span className="listino__more-rule"/>
          <p style={{ whiteSpace: 'pre-line' }}>{t.more_p}</p>
          <a href="https://enoviaselections.com/catalog/" target="_blank" rel="noreferrer">
            {t.more_a}
          </a>
        </aside>

        {/* HOW WE WORK */}
        <header className="listino__chapter" id="how">
          <span className="listino__chapter-n">{t.ch2_n}</span>
          <h2>{t.ch2_h}</h2>
          <p>{t.ch2_p}</p>
        </header>

        <section className="how">
          {t.how.map(([n, h, p], i) => (
            <div className="how__row" key={i}>
              <span className="how__n">{n}</span>
              <h3>{h}</h3>
              <p>{p}</p>
            </div>
          ))}
        </section>
      </article>

      {/* JOURNAL TEASER */}
      <article className="listino listino--journal" id="journal">
        <div className="listino--journal__inner">
          <header className="listino__chapter">
            <span className="listino__chapter-n">{t.ch3_n || 'III.'}</span>
            <h2>{t.ch3_h || 'From the journal.'}</h2>
            <p>{t.ch3_p || 'Notes from the road \u2014 producer profiles, vintage reports, the occasional opinion.'}</p>
          </header>

          <section className="journal-grid">
            {JOURNAL.map((p, i) => (
              <a className="jcard" href={p.href} key={i}>
                <div className="jcard__img" style={{ backgroundImage: `url(${p.img})` }}/>
                <div className="jcard__body">
                  <span className="jcard__meta">
                    <span>{p.kicker}</span>
                    <span className="jcard__dot">·</span>
                    <span>{p.date}</span>
                  </span>
                  <h3 className="jcard__title">{p.title}</h3>
                  <p className="jcard__excerpt">{p.excerpt}</p>
                  <span className="jcard__more">{t.journal_more || 'Read \u2192'}</span>
                </div>
              </a>
            ))}
          </section>

          <div className="journal-all">
            <a href="Journal.html">{t.journal_all || 'All entries in the journal \u2192'}</a>
          </div>
        </div>
      </article>

      {/* EVENTS — teaser + link to dedicated page */}
      <article className="listino" id="events">
        <header className="listino__chapter">
          <span className="listino__chapter-n">IV.</span>
          <h2>Where you’ll find us this year.</h2>
          <p>International B2B trade fairs — five events in 2026. <a href="Events.html" className="listino__chapter-link">See the full calendar &#8594;</a></p>
        </header>
      </article>

      {/* GROWERS TEASER — visual break between events and contact */}
      <article className="growers" id="growers">
        <div className="growers__inner growers__inner--slim">
          <header className="growers__head">
            <span className="growers__eyebrow">For Italian winemakers</span>
            <h2>If you make wine worth drinking,<br/><em>we would like to meet you.</em></h2>
            <p className="growers__lede">We add one or two growers to the book each year &#8212; no more. A real person reads every message.</p>
          </header>
          <a className="growers__btn" href="#contact">
            <span>Find out how to apply &#8594;</span>
          </a>
        </div>
      </article>

      {/* CONTACT */}
      <article className="listino" id="contact">
        <footer className="listino__foot">
          <div className="listino__foot-copy">
            {t.foot_copy_l1}<br/>{t.foot_copy_l2}<br/>{t.foot_copy_l3}<br/><em>{t.foot_copy_em}</em>
          </div>
          <div className="listino__contact">
            <span className="listino__contact-lbl">{t.lbl_office}</span>
            <span>{t.office_val}</span>
            <span className="listino__contact-lbl">{t.lbl_email}</span>
            <a className="big" href="mailto:info@enoviaselections.com">info@enoviaselections.com</a>
            <span className="listino__contact-lbl">{t.lbl_catalogue}</span>
            <a href="https://enoviaselections.com/catalog/" target="_blank" rel="noreferrer">enoviaselections.com/catalog &#8594;</a>
          </div>
        </footer>
        <div className="listino__base listino__base--center">
          <span className="listino__base-copy">&#169; {new Date().getFullYear()} Horecarte BV &#183; <a href="https://enoviaselections.com/legal-notice/" target="_blank" rel="noreferrer">{t.legal}</a> &#183; KVK 69696985 &#183; Reeuwijk, NL</span>
        </div>
      </article>

    </div>
  );
}

window.Listino = Listino;
