// Retail bowls view — what renders when the second ribbon toggle is on
// "Retail bowls" (index.html). Customers get the bowl, its RRP and where to buy
// it; businesses get the bowl, its RRP and how to stock it. Wholesale prices
// and margins are deliberately NOT on the site: anyone can flip the toggle, so
// those stay for the conversation after Contact LÜP.
//
// Customer-facing wording comes from the printed poster and the pack sleeve —
// keep it in step with them rather than rewording here.

// Stockists and RRPs are NOT kept here: the app publishes them at
// /api/retail (a store is listed once Stockist is ticked AND its first delivery
// is recorded; RRPs come from Admin › Settings › Retail settings) and this page
// reads that feed on load.
const APP_URL = /^(localhost|127\.0\.0\.1)$/.test(window.location.hostname)
  ? 'http://localhost:3000'
  : 'https://app.lupit.com.au';

window.LUP_RETAIL = {
  // The poster's names for the packs, by bowls per pack.
  PACK_LABELS: { 1: 'Single bowl', 2: 'Two-pack', 3: 'Three-pack' },
  // Business "Contact LÜP" — the partner form, store version, "Sell bowls" pre-ticked.
  CONTACT_URL: 'https://app.lupit.com.au/partners/apply?interest=retail',
  // The pack sleeve's invitation to borrow, word for word.
  SLEEVE_BORROW_LEAD: 'Did you know you can also borrow a LÜP bowl when you don\'t bring your own?',
  SLEEVE_BORROW_BODY: 'Just borrow one at a participating venue and return it when you\'re done.',
  SLEEVE_BORROW_LINK: 'Discover how it works',
};

// One fetch per page load, shared by the RRP card and the stockist list.
let retailFeed = null;
function loadRetailFeed() {
  if (!retailFeed) {
    retailFeed = fetch(APP_URL + '/api/retail')
      .then(r => { if (!r.ok) throw new Error('feed ' + r.status); return r.json(); })
      .catch(() => null); // null = unavailable; callers show their fallback
  }
  return retailFeed;
}
// { status: 'loading' | 'ok' | 'error', stockists, rrp }
function useRetailFeed() {
  const [state, setState] = React.useState({ status: 'loading', stockists: [], rrp: [] });
  React.useEffect(() => {
    let live = true;
    loadRetailFeed().then(d => {
      if (!live) return;
      setState(d ? { status: 'ok', stockists: d.stockists || [], rrp: d.rrp || [] } : { status: 'error', stockists: [], rrp: [] });
    });
    return () => { live = false; };
  }, []);
  return state;
}
const formatPrice = p => '$' + (Number.isInteger(p) ? String(p) : p.toFixed(2));

const retailScrollTo = (id) => {
  const el = document.getElementById(id);
  if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
};

// Hero — the poster's title and tagline for customers; the stockist pitch for
// businesses. Same card + photo layout as the network hero.
window.RetailHero = function RetailHero() {
  const { audience } = React.useContext(window.AudienceContext);
  const isBusiness = audience === 'venue';
  const R = window.LUP_RETAIL;

  const cta = isBusiness
    ? { label: 'Contact LÜP', props: { href: R.CONTACT_URL } }
    : { label: 'Where to buy', props: { href: '#stockists', onClick: (e) => { e.preventDefault(); retailScrollTo('stockists'); } } };

  return React.createElement('section', {
    id: 'top',
    style: { padding: '12px 24px 60px', position: 'relative', overflow: 'hidden' }
  },
    React.createElement('div', { className: 'container' },
      React.createElement('div', {
        className: 'hero-grid',
        style: { display: 'grid', gridTemplateColumns: '1.05fr 1fr', gap: 20, alignItems: 'stretch' }
      },
        React.createElement(Reveal, { as: 'div',
          className: 'hero-copy-card',
          style: {
            background: 'var(--ivory)', borderRadius: 28,
            padding: 'clamp(28px, 5vw, 52px)', border: '1px solid var(--border-cream)',
            display: 'flex', flexDirection: 'column', justifyContent: 'space-between', gap: 28,
          }
        },
          React.createElement('div', null,
            React.createElement('div', {
              style: {
                fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontWeight: 500,
                fontSize: 'clamp(21px, 2.4vw, 28px)', color: 'var(--terracotta)',
                lineHeight: 1.15, letterSpacing: '-0.01em', marginBottom: 20,
              }
            }, 'A better way to takeaway'),
            React.createElement('h1', {
              className: 'hero-headline',
              style: {
                fontFamily: 'var(--font-serif)', fontSize: 'clamp(33px, 3.9vw, 57px)',
                fontWeight: 500, lineHeight: 1.08, color: 'var(--charcoal)',
                letterSpacing: '-0.02em', marginBottom: isBusiness ? 20 : 0,
              }
            },
              isBusiness
                ? ['Sell LÜP bowls — ', React.createElement('span', { key: 'a', style: { fontStyle: 'italic', color: 'var(--terracotta)' } }, 'no stock to buy.')]
                : [React.createElement('span', { key: 'a', style: { fontStyle: 'italic', color: 'var(--terracotta)' } }, 'Reusable'), ' Takeaway Bowl with Lid'],
            ),
            isBusiness && React.createElement('p', {
              style: { fontSize: 18, color: 'var(--stone)', lineHeight: 1.6, maxWidth: 460 }
            }, 'Reusable Takeaway Bowl with Lid, on your shelf. We stock it, you set the price, and you only pay for packs that sell.'),
          ),
          React.createElement('div', null,
            React.createElement('a', {
              className: 'btn btn-terracotta btn-cta-prominent',
              ...cta.props,
              style: { borderRadius: 100, padding: '14px 22px', fontSize: 15 }
            }, cta.label, React.createElement(IconArrowRight, { size: 16 })),
          ),
        ),
        React.createElement(Reveal, { as: 'div', delay: 1,
          className: 'img-hover',
          style: {
            borderRadius: 28, overflow: 'hidden', minHeight: 320,
            backgroundImage: 'url(assets/bowl-salad.webp?v=6)',
            backgroundSize: 'cover', backgroundPosition: 'center',
          },
          role: 'img', 'aria-label': 'A LÜP bowl with lid',
        }),
      ),
    ),
  );
};

// The RRP card — the poster's panel, shown in both retail views. No wholesale
// figures, by design.
// Hidden until the feed answers, so it never shows a stale price; if the feed
// is down the card is left out rather than guessed.
window.RetailPriceCard = function RetailPriceCard() {
  const R = window.LUP_RETAIL;
  const feed = useRetailFeed();
  if (feed.status !== 'ok' || !feed.rrp.length) return null;
  return React.createElement('div', {
    'data-testid': 'rrp',
    style: {
      background: 'var(--terracotta)', color: 'var(--ivory)',
      borderRadius: 20, padding: '24px 26px', minWidth: 240, maxWidth: 360,
    }
  },
    React.createElement('div', {
      style: { fontFamily: 'var(--font-serif)', fontSize: 22, fontWeight: 600, marginBottom: 12 }
    }, 'RRP'),
    feed.rrp.map(r => React.createElement('div', {
      key: r.code,
      style: { display: 'flex', justifyContent: 'space-between', gap: 28, fontSize: 17, padding: '4px 0', fontWeight: 500 }
    },
      React.createElement('span', null, R.PACK_LABELS[r.bowlsPerPack] || r.bowlsPerPack + '-pack'),
      React.createElement('span', null, formatPrice(r.price)),
    )),
  );
};

// Customer + Retail: where to buy, then the sleeve's invitation to borrow.
window.Stockists = function Stockists() {
  const { setAudience, setView } = React.useContext(window.AudienceContext);
  const R = window.LUP_RETAIL;
  const feed = useRetailFeed();
  const mapUrl = s => 'https://www.google.com/maps/search/?api=1&query=' + encodeURIComponent([s.name, s.address || s.suburb].filter(Boolean).join(', '));
  const note = (text) => React.createElement('p', {
    'data-testid': 'stockists-note',
    style: { fontSize: 17, color: 'var(--stone)', lineHeight: 1.6, marginBottom: 40 }
  }, text);

  return React.createElement('section', { id: 'stockists', style: { background: 'var(--ivory)', borderTop: '1px solid var(--border-cream)' } },
    React.createElement('div', { className: 'container' },
      React.createElement(Reveal, { as: 'div', style: { maxWidth: 760, marginBottom: 28 } },
        React.createElement('div', { className: 'eyebrow', style: { marginBottom: 18 } },
          React.createElement('span', { className: 'dot' }), 'Where to buy'
        ),
        React.createElement('h2', {
          style: { fontSize: 'clamp(36px, 4vw, 56px)', lineHeight: 1.05, letterSpacing: '-0.02em' }
        }, 'Find a ', React.createElement('span', { className: 'serif-accent' }, 'stockist.')),
      ),
      feed.status === 'loading' ? note('Finding stockists…')
      : !feed.stockists.length ? note('Ask at your local LÜP venue.')
      : React.createElement('div', {
        style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 14, marginBottom: 40 }
      },
        feed.stockists.map(s => React.createElement('div', {
          key: s.name, className: 'card', 'data-testid': 'stockist',
          style: { padding: '22px 22px', background: 'var(--parchment)' }
        },
          React.createElement('div', {
            style: { fontFamily: 'var(--font-serif)', fontSize: 22, fontWeight: 500, color: 'var(--charcoal)' }
          }, s.name),
          React.createElement('div', { style: { fontSize: 15, color: 'var(--stone)', marginTop: 4 } }, s.suburb),
          React.createElement('a', {
            href: mapUrl(s), target: '_blank', rel: 'noopener noreferrer',
            style: { display: 'inline-block', marginTop: 12, fontSize: 14, fontWeight: 600, color: 'var(--terracotta)', textDecoration: 'none' }
          }, 'Directions ↗'),
        )),
      ),
      React.createElement(Reveal, { as: 'div',
        'data-testid': 'borrow-nudge',
        style: {
          background: 'var(--parchment)', border: '1px solid var(--border-cream)',
          borderRadius: 24, padding: '28px 28px', maxWidth: 760,
        }
      },
        React.createElement('p', {
          style: { fontFamily: 'var(--font-serif)', fontSize: 24, color: 'var(--terracotta)', lineHeight: 1.3 }
        }, R.SLEEVE_BORROW_LEAD),
        React.createElement('p', { style: { fontSize: 16, color: 'var(--stone)', marginTop: 8, lineHeight: 1.6 } }, R.SLEEVE_BORROW_BODY),
        React.createElement('a', {
          href: '?as=customer&view=network',
          onClick: e => { e.preventDefault(); setAudience('customer'); setView('network'); },
          style: { display: 'inline-block', marginTop: 14, fontSize: 16, fontWeight: 600, color: 'var(--terracotta)', textDecoration: 'none' }
        }, R.SLEEVE_BORROW_LINK + ' →'),
      ),
    ),
  );
};

// Business + Retail: how stocking works, in words only, and Contact LÜP.
window.SellBowls = function SellBowls() {
  const { setView } = React.useContext(window.AudienceContext);
  const R = window.LUP_RETAIL;
  const points = [
    { title: 'We stock your shelf', desc: 'Packs of one, two and three bowls, delivered and restocked by LÜP. Nothing to buy upfront.' },
    { title: 'You set the price', desc: 'Sell at the RRP or set your own — the shelf price is yours.' },
    { title: 'Pay only for what sells', desc: 'We count the shelf and you pay for the packs that sold, on your regular LÜP invoice.' },
  ];
  return React.createElement('section', { id: 'sell', style: { background: 'var(--ivory)', borderTop: '1px solid var(--border-cream)' } },
    React.createElement('div', { className: 'container' },
      React.createElement(Reveal, { as: 'div', style: { maxWidth: 760, marginBottom: 28 } },
        React.createElement('div', { className: 'eyebrow', style: { marginBottom: 18 } },
          React.createElement('span', { className: 'dot' }), 'Sell LÜP bowls'
        ),
        React.createElement('h2', {
          style: { fontSize: 'clamp(36px, 4vw, 56px)', lineHeight: 1.05, letterSpacing: '-0.02em' }
        }, 'Want to sell LÜP bowls ', React.createElement('span', { className: 'serif-accent' }, 'in your store?')),
      ),
      React.createElement('div', {
        className: 'grid-3-md-1',
        style: { display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginBottom: 32 }
      },
        points.map((p, i) => React.createElement(Reveal, { key: p.title, delay: i + 1, className: 'card', style: { padding: '22px 22px', background: 'var(--parchment)' } },
          React.createElement('h3', { style: { fontFamily: 'var(--font-serif)', fontSize: 22, fontWeight: 500, color: 'var(--terracotta)' } }, p.title),
          React.createElement('p', { style: { fontSize: 15, color: 'var(--stone)', marginTop: 8, lineHeight: 1.55 } }, p.desc),
        )),
      ),
      React.createElement('div', { style: { display: 'flex', gap: 18, alignItems: 'center', flexWrap: 'wrap' } },
        React.createElement('a', {
          className: 'btn btn-terracotta', href: R.CONTACT_URL,
          style: { padding: '14px 22px', fontSize: 15, borderRadius: 100 }
        }, 'Contact LÜP', React.createElement(IconArrowRight, { size: 14 })),
        React.createElement('a', {
          href: '?as=business&view=network',
          onClick: e => { e.preventDefault(); setView('network'); },
          style: { fontSize: 15, fontWeight: 600, color: 'var(--terracotta)', textDecoration: 'none' }
        }, 'Want to lend bowls too? See the LÜP Network →'),
      ),
    ),
  );
};
