// Product page — full Shopify-connected product view.
// URL: product.html?id=japanese  (id matches MOTOMELLI_HOODIES[n].id)

const _PP_STORE = '58a6d8-e5.myshopify.com';
const _PP_TOKEN = 'f665e892fda478a7e3978d958c973140';

async function _ppFetch(query, variables = {}) {
  const res = await fetch(`https://${_PP_STORE}/api/2024-10/graphql.json`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Shopify-Storefront-Access-Token': _PP_TOKEN,
    },
    body: JSON.stringify({ query, variables }),
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

const _Q_VARIANTS = `query Product($id: ID!) {
  product(id: $id) {
    variants(first: 20) {
      edges { node { id title availableForSale price { amount currencyCode } } }
    }
  }
}`;

const _M_CART = `mutation CartCreate($lines: [CartLineInput!]!) {
  cartCreate(input: { lines: $lines }) {
    cart { checkoutUrl }
    userErrors { message }
  }
}`;

// ── Reviews — sourced from data.jsx ───────────────────────────────
const Stars = ({ value, size = 14 }) => {
  const full = Math.round(value);
  return (
    <span className="mm-stars" style={{ fontSize: size }} aria-label={`${value.toFixed(1)} out of 5 stars`}>
      {[1, 2, 3, 4, 5].map(i => (
        <span key={i} className={`mm-stars__s${i <= full ? ' is-on' : ''}`}>★</span>
      ))}
    </span>
  );
};

const _avg = (reviews) => reviews.reduce((s, r) => s + r.stars, 0) / reviews.length;

// Inline rating beside the product title.
const ProductStarRating = ({ reviews }) => {
  if (!reviews?.length) return null;
  const avg = _avg(reviews);
  return (
    <span className="mmp-rating">
      <Stars value={avg} size={14} />
      <span className="mm-mono mmp-rating__count">{reviews.length} REVIEW{reviews.length === 1 ? '' : 'S'}</span>
    </span>
  );
};

// Full reviews section.
const ProductReviews = ({ reviews, productName }) => {
  if (!reviews?.length) return null;
  const avg = _avg(reviews);
  return (
    <section className="mmp-reviews" id="mmp-reviews">
      <div className="mmp-reviews__inner">
        <div className="mmp-reviews__head">
          <div>
            <span className="mm-mono mmp-reviews__label">CUSTOMER REVIEWS</span>
            <h2 className="mmp-reviews__title">What riders say about the {productName}.</h2>
            <div className="mmp-reviews__summary">
              <Stars value={avg} size={20} />
              <span className="mmp-reviews__avg">{avg.toFixed(1)}</span>
              <span className="mm-mono mmp-reviews__total">based on {reviews.length} review{reviews.length === 1 ? '' : 's'}</span>
            </div>
          </div>
          <a
            href="https://instagram.com/motomelli"
            target="_blank"
            rel="noopener noreferrer"
            className="mmp-reviews__write mm-mono"
          >
            SHARE YOURS @MOTOMELLI →
          </a>
        </div>
        <ul className="mmp-reviews__list">
          {reviews.map((r, i) => (
            <li key={i} className="mmp-review">
              <div className="mmp-review__head">
                <Stars value={r.stars} size={13} />
                <span className="mm-mono mmp-review__date">{r.date}</span>
              </div>
              <p className="mmp-review__text">"{r.text}"</p>
              <span className="mm-mono mmp-review__name">— {r.name}</span>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
};

// ── Accordion ─────────────────────────────────────────────────────
const Accordion = React.forwardRef(({ title, children, defaultOpen = false, ...rest }, ref) => {
  const [open, setOpen] = React.useState(defaultOpen);
  return (
    <div className={`mmp-accordion${open ? ' is-open' : ''}`} ref={ref} {...rest}>
      <button className="mmp-accordion__trigger" onClick={() => setOpen(o => !o)}>
        <span className="mm-mono">{title}</span>
        <span className="mmp-accordion__icon">{open ? '−' : '+'}</span>
      </button>
      <div className="mmp-accordion__body">{open && children}</div>
    </div>
  );
});

// ── Image Gallery ─────────────────────────────────────────────────
const MediaGallery = ({ images }) => {
  const [active, setActive] = React.useState(0);
  return (
    <div className="mmp-gallery">
      <div className="mmp-gallery__main">
        <img src={images[active]} alt="Product" />
      </div>
      {images.length > 1 && (
        <div className="mmp-gallery__thumbs">
          {images.map((src, i) => (
            <button
              key={i}
              className={`mmp-gallery__thumb${i === active ? ' is-on' : ''}`}
              onClick={() => setActive(i)}
            >
              <img src={src} alt={`View ${i + 1}`} />
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

// ── Product Info Panel ────────────────────────────────────────────
const ProductInfo = ({ product, variants, selected, setSelected, phase, onCheckout }) => {
  const btnLabel = phase === 'redirecting' ? 'REDIRECTING…'
    : phase === 'no-shop'    ? 'COMING SOON'
    : phase === 'error'      ? 'TRY AGAIN'
    : !selected              ? 'SELECT A SIZE'
    :                          'ADD TO CART →';

  return (
    <div className="mmp-info">
      <div className="mmp-info__inner">

        <span className="mm-mono mmp-info__collection">MOTOMELLI ORIGINALS</span>

        <h1 className="mmp-info__title">{product.name}</h1>

        {product.reviews?.length > 0 && (
          <a href="#mmp-reviews" className="mmp-info__rating">
            <ProductStarRating reviews={product.reviews} />
          </a>
        )}

        <div className="mmp-info__price-row">
          <span className="mmp-info__price">{product.price}</span>
          <span className="mm-mono mmp-info__gsm">440 GSM · OVERSIZED</span>
        </div>

        <div className="mmp-info__divider" />

        {phase === 'loading' && (
          <p className="mm-mono mmp-info__status">LOADING SIZES…</p>
        )}
        {phase === 'error' && (
          <p className="mm-mono mmp-info__status mmp-info__status--err">SHOP UNAVAILABLE — TRY AGAIN</p>
        )}

        {(phase === 'ready' || phase === 'no-shop') && (
          <div className="mmp-info__sizes">
            <div className="mmp-info__sizes-head">
              <span className="mm-mono mmp-info__sizes-label">SIZE</span>
              <a href="#mmp-size-guide" className="mm-mono mmp-info__size-guide-link"
                onClick={e => { e.preventDefault(); document.querySelector('.mmp-accordion[data-id="size-guide"] .mmp-accordion__trigger')?.click(); }}>
                SIZE GUIDE ↓
              </a>
            </div>
            {phase === 'no-shop' ? (
              <p className="mmp-info__coming-soon mm-mono">AVAILABLE SOON</p>
            ) : (
              <div className="mmp-info__size-grid">
                {variants.map(v => (
                  <button
                    key={v.id}
                    className={`mmp-size-btn mm-mono${selected === v.id ? ' is-on' : ''}${!v.availableForSale ? ' is-sold' : ''}`}
                    onClick={() => v.availableForSale && setSelected(v.id)}
                    disabled={!v.availableForSale}
                    title={!v.availableForSale ? 'Sold out' : ''}
                  >{v.title}</button>
                ))}
              </div>
            )}
          </div>
        )}

        <button
          className={`mmp-info__add${phase === 'redirecting' ? ' is-loading' : ''}`}
          onClick={onCheckout}
          disabled={phase !== 'ready' || !selected}
        >
          <span className="mm-mono">{btnLabel}</span>
        </button>

        <div className="mmp-info__trust">
          <span className="mm-mono">🚚 FREE UK DELIVERY</span>
          <span className="mm-mono">↩ 30-DAY RETURNS</span>
          <span className="mm-mono">🖨 DTG PRINTED TO ORDER</span>
        </div>

        <div className="mmp-info__divider" />

        {product.description && (
          <p className="mmp-info__desc">{product.description}</p>
        )}

        <div className="mmp-info__accordions">
          {product.features?.length > 0 && (
            <Accordion title="PRODUCT DETAILS" defaultOpen>
              <ul className="mmp-features">
                {product.features.map((f, i) => <li key={i}>{f}</li>)}
              </ul>
              {product.material && (
                <p className="mm-mono mmp-material">{product.material}</p>
              )}
            </Accordion>
          )}

          <Accordion title="SIZE GUIDE" data-id="size-guide">
            <p className="mmp-accordion__intro">Unisex oversized boxy fit. Order your normal size — these are designed to be big.</p>
            <table className="mmp-sizeguide">
              <thead>
                <tr><th>SIZE</th><th>CHEST</th><th>LENGTH</th><th>SLEEVE</th></tr>
              </thead>
              <tbody>
                {[
                  ['S',   '96–101 cm', '67 cm', '63 cm'],
                  ['M',   '104–109 cm','69 cm', '65 cm'],
                  ['L',   '112–117 cm','71 cm', '67 cm'],
                  ['XL',  '120–125 cm','73 cm', '69 cm'],
                  ['2XL', '128–133 cm','75 cm', '71 cm'],
                ].map(([s, c, l, sl]) => (
                  <tr key={s}><td>{s}</td><td>{c}</td><td>{l}</td><td>{sl}</td></tr>
                ))}
              </tbody>
            </table>
          </Accordion>

          <Accordion title="SHIPPING &amp; RETURNS">
            <div className="mmp-shipping">
              <div className="mmp-shipping__row">
                <span className="mm-mono">UK</span>
                <span>5–7 business days</span>
              </div>
              <div className="mmp-shipping__row">
                <span className="mm-mono">EUROPE</span>
                <span>7–10 business days</span>
              </div>
              <div className="mmp-shipping__row">
                <span className="mm-mono">INTERNATIONAL</span>
                <span>10–14 business days</span>
              </div>
              <p className="mmp-shipping__note">Free returns within 30 days. Unworn and unwashed only. See full returns policy.</p>
            </div>
          </Accordion>
        </div>

      </div>
    </div>
  );
};


// ── Related Products ──────────────────────────────────────────────
const RelatedProducts = ({ currentId }) => {
  const { MOTOMELLI_HOODIES } = window.MOTO_DATA;
  const others = MOTOMELLI_HOODIES.filter(h => h.id !== currentId).slice(0, 3);
  return (
    <section className="mmp-related">
      <div className="mmp-related__inner">
        <span className="mm-mono mmp-related__label">YOU MIGHT ALSO LIKE</span>
        <div className="mmp-related__grid">
          {others.map(h => (
            <a key={h.id} href={`product.html?id=${h.id}`} className="mmp-related__card">
              <div className="mmp-related__img">
                <img src={h.image} alt={h.name} />
              </div>
              <div className="mmp-related__meta">
                <span className="mmp-related__name">{h.name}</span>
                <span className="mmp-related__price">{h.price}</span>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
};

// ── Full Product View ─────────────────────────────────────────────
const ProductView = ({ product }) => {
  const [variants, setVariants] = React.useState([]);
  const [selected, setSelected] = React.useState(null);
  const [phase, setPhase] = React.useState(product.shopifyId ? 'loading' : 'no-shop');

  React.useEffect(() => {
    if (!product.shopifyId) return;
    const gid = `gid://shopify/Product/${product.shopifyId}`;
    _ppFetch(_Q_VARIANTS, { id: gid })
      .then(d => {
        const vs = (d.data?.product?.variants?.edges || []).map(e => e.node);
        setVariants(vs);
        setSelected((vs.find(v => v.availableForSale) || vs[0])?.id ?? null);
        setPhase('ready');
      })
      .catch(() => setPhase('error'));
  }, [product.shopifyId]);

  const handleCheckout = async () => {
    if (!selected || phase !== 'ready') return;
    setPhase('redirecting');
    try {
      const d = await _ppFetch(_M_CART, {
        lines: [{ merchandiseId: selected, quantity: 1 }],
      });
      const url = d.data?.cartCreate?.cart?.checkoutUrl;
      if (url) { window.location.href = url; }
      else { setPhase('error'); }
    } catch { setPhase('error'); }
  };

  const images = product.images?.length ? product.images : [product.image];

  return (
    <div className="mmp">

      {/* Nav */}
      <nav className="mmp-nav">
        <a href="hoodies.html" className="mmp-nav__back mm-mono">← BACK</a>
        <a href="Motomelli.html" className="mmp-nav__logo">
          <MotomelliWordmark height={20} />
        </a>
        <a href={`https://58a6d8-e5.myshopify.com/collections/all`} className="mmp-nav__shop mm-mono">
          SHOP ALL →
        </a>
      </nav>

      {/* Breadcrumb */}
      <div className="mmp-breadcrumb">
        <a href="Motomelli.html" className="mm-mono">HOME</a>
        <span className="mm-mono">/</span>
        <a href="hoodies.html" className="mm-mono">HOODIES</a>
        <span className="mm-mono">/</span>
        <span className="mm-mono">{product.name.toUpperCase()}</span>
      </div>

      {/* Product grid — image left, info right */}
      <div className="mmp-product">
        <MediaGallery images={images} />
        <ProductInfo
          product={product}
          variants={variants}
          selected={selected}
          setSelected={setSelected}
          phase={phase}
          onCheckout={handleCheckout}
        />
      </div>

      {/* Reviews — sourced from data.jsx */}
      <ProductReviews reviews={product.reviews} productName={product.name} />

      {/* Related */}
      <RelatedProducts currentId={product.id} />

      {/* Footer */}
      <footer className="mmp-footer">
        <a href="Motomelli.html" className="mmp-footer__logo">
          <MotomelliWordmark height={18} />
        </a>
        <span className="mm-mono mmp-footer__copy">FOR THE GIRLS</span>
        <span className="mm-mono mmp-footer__legal">© MOTOMELLI 2026. All Rights Reserved.<br />MotoMelli is a trading name of Align Ops Ltd. Registered in England and Wales No. 16090781.<br />Registered Office: Suite A, 82 James Carter Road, Mildenhall, IP28 7DE.</span>
        <div className="mmp-footer__links">
          <a href="hoodies.html" className="mm-mono">HOODIES</a>
          <a href="Motomelli.html#find" className="mm-mono">FIND GEAR</a>
          <a href="Motomelli.html#compare" className="mm-mono">COMPARE</a>
        </div>
        <div className="mmp-footer__links mmp-footer__links--legal">
          <a href="Privacy.html" className="mm-mono">Privacy Policy</a>
          <a href="Cookies.html" className="mm-mono">Cookies Policy</a>
          <a href="Terms.html" className="mm-mono">Terms &amp; Conditions</a>
        </div>
      </footer>
    </div>
  );
};

// ── Entry Point ───────────────────────────────────────────────────
const ProductPage = () => {
  const id = new URLSearchParams(window.location.search).get('id');
  const { MOTOMELLI_HOODIES } = window.MOTO_DATA;
  const product = MOTOMELLI_HOODIES.find(h => h.id === id);

  if (!product) {
    return (
      <div className="mmp mmp--404">
        <nav className="mmp-nav">
          <div />
          <a href="Motomelli.html" className="mmp-nav__logo"><MotomelliWordmark height={20} /></a>
          <div />
        </nav>
        <div className="mmp-404">
          <span className="mm-mono mmp-404__code">404</span>
          <h1>Product not found.</h1>
          <a href="hoodies.html" className="mmp-404__back mm-mono">← BACK TO HOODIES</a>
        </div>
      </div>
    );
  }

  return <ProductView product={product} />;
};

window.ProductPage = ProductPage;
