// The Phone page — Ciao Bella
// Product description + mix-and-match configurator + pricing/bundles

const { useState: useStateTP, useEffect: useEffectTP } = React;

// Read a stashed initial quantity (set by goToConfigurator when called from
// a bundle CTA like BFF or Trio). Clamped to 1-5, consumed once.
function readStashedQty() {
  try {
    const q = parseInt(sessionStorage.getItem('cb_initial_qty') || '0', 10);
    if (q >= 1 && q <= 5) {
      sessionStorage.removeItem('cb_initial_qty');
      return q;
    }
  } catch (e) {}
  return 1;
}

function PricingSummary({ quantity, navigate, ctaLabel = 'Reserve for $25', onCta }) {
  const pricing = PRICING.bundles[quantity] || { price: PRICING.preorder * quantity, save: (PRICING.rrp - PRICING.preorder) * quantity };
  const rrpTotal = quantity * PRICING.rrp;

  return (
    <div className="pricing-summary">
      <div className="pricing-summary-head">
        <span className="label">Your order</span>
        <h3>{quantity === 1 ? '1 phone' : `${quantity} phones`}</h3>
      </div>

      <div className="pricing-rows">
        <div className="row">
          <span>{quantity} × Ciao Bella</span>
          <span style={{ textDecoration: 'line-through', color: 'var(--muted)' }}>${rrpTotal}</span>
        </div>
        <div className="row">
          <span>Pre-order discount</span>
          <span style={{ color: 'var(--accent)' }}>− ${pricing.save}</span>
        </div>
        <div className="row">
          <span>Total when it ships</span>
          <span>${pricing.price}</span>
        </div>
        <div className="row total">
          <span>Reserve today</span>
          <span>$25</span>
        </div>
      </div>

      <CTA onClick={onCta || (() => navigate('/preorder'))}>{ctaLabel}</CTA>

      <div className="pricing-fineprint">
        <p>$25 hold today — full balance charged when your phone ships. Cancel anytime before then.</p>
        <p>Free shipping in Australia. All prices in AUD, incl. GST.</p>
      </div>

      <div className="bundle-tip">
        <strong>Tip:</strong> bundles save more.
        <ul>
          <li>2 phones — save ${(PRICING.bundles[2]?.save || 60)}</li>
          <li>3 phones — save ${(PRICING.bundles[3]?.save || 90)}</li>
        </ul>
      </div>
    </div>
  );
}

function PhonePage({ navigate }) {
  const { quantity, setQuantity, phones, setPhones } = usePhoneState(readStashedQty());
  const featured = phones[0] || { top: 'buttercream', bot: 'buttercream' };

  // Listen for live quantity updates when a bundle CTA is clicked while
  // PhonePage is already mounted (so the user doesn't have to refresh).
  useEffectTP(() => {
    const onQty = (e) => {
      const q = e.detail && e.detail.qty;
      if (q >= 1 && q <= 5) setQuantity(q);
    };
    window.addEventListener('ciao:configurator-qty', onQty);
    return () => window.removeEventListener('ciao:configurator-qty', onQty);
  }, [setQuantity]);

  const goToPreorder = () => {
    // Stash config so the pre-order page can pick it up
    try {
      sessionStorage.setItem('cb_config', JSON.stringify({ quantity, phones }));
    } catch (e) {}
    navigate('/preorder?step=checkout');
  };

  return (
    <main className="phone-page">
      {/* ── Top hero ── */}
      <section className="phone-hero">
        <div className="container phone-hero-inner">
          <div className="phone-hero-copy">
            <Pill>The phone</Pill>
            <h1>One <em>beautiful</em> phone. <br />Nine colour combos.</h1>
            <p className="lede">
              A small home phone for kids, in colours they&apos;ll love. Pick a top, pick a bottom — mix and match until it&apos;s perfectly theirs.
            </p>
            <div className="phone-hero-cta">
              <CTA onClick={() => document.getElementById('configurator')?.scrollIntoView({ behavior: 'smooth' })}>
                Mix &amp; match
              </CTA>
              <span className="hand-note">from ${PRICING.preorder}</span>
            </div>
          </div>
          <div className="phone-hero-art">
            <PhonePreview top='buttercream' bot='buttercream' size='lg' />
            <img src="assets/star-doodle.svg" alt="" aria-hidden="true" className="phone-hero-doodle d1" />
          </div>
        </div>
      </section>

      {/* ── What it is ── */}
      <section className="phone-what">
        <div className="container" style={{ position: 'relative' }}>
          <EyebrowRow eyebrow="What it is" />
          <div className="what-grid">
            <div className="what-block">
              <h3>A real home phone, sized for small hands.</h3>
              <p>
                Ciao Bella is a home phone for kids — it sits on a bedside table, the kitchen bench, or a desk in the playroom. Plug it into a power outlet, plug the included Ethernet cable into your home internet router, and it&apos;s ready. It rings. It dials. It lights up when Grandma calls. That&apos;s it.
              </p>
            </div>
            <div className="what-block">
              <h3>Connects only to people you choose.</h3>
              <p>
                You manage your child's contact list from the parent app. Your child can call any approved contact with one tap, and only those numbers can call back. No strangers, no spam, no surprises.
              </p>
            </div>
            <div className="what-block">
              <h3>No screen, no apps, no internet.</h3>
              <p>
                There&apos;s nothing to scroll, no notifications, no algorithm. The phone connects to your home internet by Ethernet cable and only uses it to make calls — nothing else gets in or out.
              </p>
            </div>
          </div>
        </div>
      </section>

      {/* ── Bundles ── */}
      <Bundles navigate={navigate} currentRoute="/phone" />

      {/* ── Configurator ── */}
      <section className="phone-configurator" id="configurator">
        <div className="container">
          <EyebrowRow eyebrow="Mix &amp; match" />
          <SectionHeading>Make one that's <em>theirs</em>.</SectionHeading>
          <p className="config-intro">
            Or skip the bundles and choose any top with any bottom. Add up to 5 phones — perfect for siblings, cousins, or a whole little crew.
          </p>

          <Configurator
            quantity={quantity}
            setQuantity={setQuantity}
            phones={phones}
            setPhones={setPhones}
            summary={<PricingSummary quantity={quantity} navigate={navigate} onCta={goToPreorder} ctaLabel="Reserve for $25" />}
          />
        </div>
      </section>

    </main>
  );
}

Object.assign(window, { PhonePage, PricingSummary });
