/* global React, RadialMenuSVG */
const { useState: useStateP, useEffect: useEffectP } = React;

// ============================================================================
// Shopify config
// ============================================================================
const SHOPIFY_STOREFRONT_DOMAIN = 'pablander.myshopify.com'; // for API calls
const SHOPIFY_CART_DOMAIN = 'store.pablander.academy'; // for cart URLs
const STOREFRONT_TOKEN = '9e78359d87e2428e491b77cd6fa637c6';
const PRODUCT_ID = '9603898409189';
const LICENCE_TERMS_URL = 'https://store.pablander.academy/pages/licences';
const CONTACT_EMAIL = 'licences@radialz.app';

// Synthetic "Enterprise" entry appended to whatever Shopify returns. Drives the
// Contact-us flow without needing a variant in the store.
const ENTERPRISE_VARIANT = {
  id: '__enterprise__',
  title: 'Enterprise — Contact us',
  price: null,
  isEnterprise: true
};

// Friendly caption shown under the price for each tier. We match by substring
// so the store can keep its real variant names ("Individual licence", etc.)
const captionFor = (v) => {
  if (!v) return '';
  if (v.isEnterprise) return '15+ users · we’ll set up a custom plan';
  const t = (v.title || '').toLowerCase();
  if (t.includes('studio')) return 'Studio licence · up to 15 users';
  if (t.includes('team')) return 'Team licence';
  if (t.includes('individual')) return 'Individual licence · one user';
  return v.title || 'Licence';
};

// What to show in the dropdown for each variant.
const displayTitleFor = (v) => {
  if (!v) return '';
  if (v.isEnterprise) return v.title;
  // Hide the dummy "Default Title" Shopify uses for single-variant products.
  if (!v.title || /^default(\s+title)?$/i.test(v.title)) return 'Individual licence';
  return v.title;
};

const fetchProductVariants = async () => {
  const url = `https://${SHOPIFY_STOREFRONT_DOMAIN}/api/2024-01/graphql.json`;
  const r = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Shopify-Storefront-Access-Token': STOREFRONT_TOKEN
    },
    body: JSON.stringify({
      query: `{
        product(id: "gid://shopify/Product/${PRODUCT_ID}") {
          variants(first: 20) {
            edges {
              node {
                id
                title
                availableForSale
                price { amount currencyCode }
              }
            }
          }
        }
      }`
    })
  });
  if (!r.ok) throw new Error('shopify fetch failed: ' + r.status);
  const json = await r.json();
  const edges = json?.data?.product?.variants?.edges || [];
  return edges.map((e) => e.node);
};

// Fallback variants used if the Storefront API is unreachable. Keeps the card
// useful even when offline / behind a strict network.
const FALLBACK_VARIANTS = [
{ id: 'fallback-individual', title: 'Individual licence', isFallback: true,
  price: { amount: '39.00', currencyCode: 'USD' } },
{ id: 'fallback-studio', title: 'Studio licence', isFallback: true,
  price: { amount: '299.00', currencyCode: 'USD' } }];


// ============================================================================
// Pricing card
// ============================================================================
const Pricing = () => {
  const [variants, setVariants] = useStateP([]);
  const [selectedIdx, setSelectedIdx] = useStateP(0);
  const [agreed, setAgreed] = useStateP(false);
  const [status, setStatus] = useStateP('loading'); // loading | ok | error
  // Local shake animation on the checkbox when user clicks the disabled button
  const [shake, setShake] = useStateP(false);

  useEffectP(() => {
    let cancelled = false;
    fetchProductVariants().
    then((vs) => {
      if (cancelled) return;
      const real = vs.length ? vs : FALLBACK_VARIANTS;
      setVariants([...real, ENTERPRISE_VARIANT]);
      setStatus(vs.length ? 'ok' : 'error');
    }).
    catch(() => {
      if (cancelled) return;
      setVariants([...FALLBACK_VARIANTS, ENTERPRISE_VARIANT]);
      setStatus('error');
    });
    return () => {cancelled = true;};
  }, []);

  const selected = variants[selectedIdx] || null;
  const isEnterprise = !!selected?.isEnterprise;

  // Strip GID prefix to get the numeric ID for the cart permalink.
  const variantNumericId = selected && !isEnterprise && !selected.isFallback ?
  String(selected.id).split('/').pop() :
  null;
  const checkoutUrl = variantNumericId ?
  `https://${SHOPIFY_CART_DOMAIN}/cart/${variantNumericId}:1` :
  null;

  // Display price (no trailing .00 if whole). Currency code shown next to it.
  const priceAmount = selected?.price?.amount;
  const priceWhole = priceAmount ?
  Number.isInteger(parseFloat(priceAmount)) ?
  String(parseInt(priceAmount, 10)) :
  parseFloat(priceAmount).toFixed(2) :
  null;
  const currencyCode = selected?.price?.currencyCode || 'USD';

  // Buy button is enabled only when:
  //   - terms agreed
  //   - non-enterprise variant
  //   - we have a checkout URL (variant came from Shopify, not fallback)
  const canBuy = agreed && !isEnterprise && !!checkoutUrl;

  const handleBuyClick = (e) => {
    if (canBuy) return; // let the link navigate
    e.preventDefault();
    if (!agreed) {
      setShake(true);
      setTimeout(() => setShake(false), 600);
    }
  };

  return (
    <section className="pricing-wrap" id="pricing" data-screen-label="07 Pricing">
      <div className="section-head section-head--centered">
        <div>
          <div className="lead">Pricing</div>
          <h2>One payment. <span className="it">
no subscriptions</span></h2>
        </div>
      </div>

      <div className="pricing-card">
        <h2>RadialZ</h2>
        <div className="sub">The radial brush menu for ZBrush</div>

        {/* Variant dropdown */}
        <div className="pricing-variant">
          <label className="pricing-variant-label" htmlFor="rz-variant">Licence</label>
          <div className="pricing-variant-select-wrap">
            <select id="rz-variant"
            className="pricing-variant-select"
            value={selectedIdx}
            onChange={(e) => setSelectedIdx(parseInt(e.target.value, 10))}
            disabled={status === 'loading'}>
              
              {status === 'loading' && <option>Loading licences…</option>}
              {variants.map((v, i) =>
              <option key={v.id} value={i}>{displayTitleFor(v)}</option>
              )}
            </select>
            <span className="pricing-variant-caret" aria-hidden="true">▾</span>
          </div>
        </div>

        {/* Big price */}
        <div className="price-row">
          {isEnterprise ?
          <span className="price-enterprise">Custom pricing</span> :
          priceWhole ?
          <>
              <span className="price-cur">$</span>
              <span className="price">{priceWhole}</span>
              <span className="price-currency">{currencyCode}</span>
            </> :

          <span className="price-enterprise">—</span>
          }
        </div>
        <div className="price-note">{captionFor(selected)}</div>

        <ul className="pricing-feats">
          <li><span className="ck">✓</span> Radial brush menu, triggered by hotkey</li>
          <li><span className="ck">✓</span> Unlimited custom menus, one per workflow</li>
          <li><span className="ck">✓</span> Child slots, 3 brushes nested per slot</li>
          <li><span className="ck">✓</span> Auto-scanning brush library with search and filters</li>
          <li><span className="ck">✓</span> ZBrush Bridge for direct, scriptless brush loading</li>
          <li><span className="ck">✓</span> Windows installer with automatic setup</li>
          <li><span className="ck">✓</span> ZBrush 2025 &amp; 2026</li>
          <li><span className="ck">✓</span> Popup library window with every brush you own</li>
        </ul>

        {/* Terms agreement */}
        <label className={`pricing-terms ${shake ? 'is-shaking' : ''}`}>
          <input
            type="checkbox"
            checked={agreed}
            onChange={(e) => setAgreed(e.target.checked)}
            aria-describedby="rz-terms-text" />
          
          <span id="rz-terms-text">
            I have read and agree to the{' '}
            <a href={LICENCE_TERMS_URL} target="_blank" rel="noopener noreferrer">Licence Terms</a>.
          </span>
        </label>

        {/* Buy button (changes mode for Enterprise) */}
        {isEnterprise ?
        <a
          href={`mailto:${CONTACT_EMAIL}?subject=RadialZ%20Enterprise%20Licence%20Enquiry`}
          className="btn-primary pricing-cta">
          
            Contact us for Enterprise
            <span className="price-tag">15+ users</span>
          </a> :

        <a
          href={canBuy ? checkoutUrl : '#'}
          className={`btn-primary pricing-cta ${canBuy ? '' : 'is-disabled'}`}
          target="_blank"
          rel="noopener noreferrer"
          aria-disabled={!canBuy}
          onClick={handleBuyClick}>
          
            Buy RadialZ
            <span className="price-tag">
              {priceWhole ? `$${priceWhole} ${currencyCode}` : '—'}
            </span>
          </a>
        }

        <div className="pricing-foot">WINDOWS ONLY</div>
      </div>
    </section>);

};

// ============================================================================
// FAQ + Footer (unchanged)
// ============================================================================
const FAQ = () => {
  const items = [
  {
    q: 'Which ZBrush versions does RadialZ support?',
    a: 'RadialZ supports ZBrush 2025 and 2026 on Windows. Older versions are not officially supported.'
  },
  {
    q: 'How is it different from ZBrush\'s built-in custom hotkeys?',
    a: 'Custom hotkeys make you memorize key combinations across a flat list. RadialZ gives you a visual radial menu at your cursor, organized by workflow, with thumbnails you can see. You pick a brush by gesture instead of recalling a key. You can also build multiple menus for different stages of a sculpt, which built-in hotkeys can\'t do.'
  },
  {
    q: 'Does RadialZ work with my custom and IMM brushes?',
    a: 'Yes. RadialZ scans your full ZBrush brush library, including custom brushes, VDMs, IMM brushes, etc., and they can all be assigned to radial menu slots.'
  },
  {
    q: 'Do I need to know scripting or ZScript to use it?',
    a: 'No. The installer wires RadialZ to ZBrush automatically. You bind one hotkey and build menus by dragging brushes. There is no scripting involved at any point.'
  },
  {
    q: 'How many menus and brushes can I set up?',
    a: 'You can build as many menus as you want, one per workflow or one per feature. Each menu has up to 10 slots, and each slot can hold up to three child brushes or even another nested full radial menu.'
  },
  {
    q: 'Will it slow down ZBrush?',
    a: 'No. RadialZ runs as a lightweight overlay alongside ZBrush, not as a heavy plugin inside it. The menu only appears when you press your hotkey and disappears the moment you pick a brush. It has no measurable impact on sculpting performance.'
  },
  {
    q: 'Can I use it with a Wacom tablet, Stream Deck, or left-hand controller?',
    a: 'Yes. RadialZ is built for pen workflows and works naturally with a Wacom tablet. You can trigger the menu from any key, so a Stream Deck or left-hand controller key works fine as your hotkey.'
  },
  {
    q: 'What gets installed on my machine?',
    a: 'Two things: the RadialZ overlay application, and a lightweight Bridge plugin inside ZBrush that lets RadialZ load brushes. The installer sets both up for you.'
  },
  {
    q: 'How do I activate RadialZ?',
    a: 'As soon as you purchase RadialZ we\'ll send you an email containing your activation key. Just copy and paste it into the first window that appears when you finish the RadialZ installation.'
  },
  {
    q: 'What if I move to a new machine?',
    a: 'Your licence belongs to you. Send us a quick note at support@radialz.app and we\'ll release the activation key from your old machine so you can re-activate on the new one. Usually same-day.'
  }];

  const [open, setOpen] = useStateP(0);

  return (
    <section className="faq-wrap" id="faq" data-screen-label="08 FAQ">
      <div className="section-head section-head--centered faq-head">
        <div>
          <div className="lead lead--cyan">Questions</div>
          <h2>Things <span className="it" style={{ color: '#4dc8e9' }}>you might be wondering.</span></h2>
        </div>
      </div>

      <div className="faq-list">
        {items.map((it, i) =>
        <div
          key={i}
          className="faq-item"
          data-open={open === i ? 'true' : 'false'}
          onClick={() => setOpen(open === i ? -1 : i)}>
          
            <div className="faq-q">
              <span>{it.q}</span>
              <span className="icon">+</span>
            </div>
            <div className="faq-a">{it.a}</div>
          </div>
        )}
      </div>

      <p className="faq-guide-link">
        Already own RadialZ?{' '}
        <a href="https://guide.radialz.app" target="_blank" rel="noopener noreferrer">
          Check out the guide →
        </a>
      </p>
    </section>);

};

const Footer = () =>
<footer className="footer">
    <div className="footer-grid">
      <div className="footer-logo">
        <img className="footer-mark" src={window.__resources['footer-icon']} alt="RadialZ" />
        <div className="nav-name">Radial<span>Z</span></div>
      </div>
      <div className="footer-links">
        <a href="#features">Features</a>
        <a href="#how">How it works</a>
        <a href="#pricing">Pricing</a>
        <a href="#faq">FAQ</a>
        <a href="mailto:support@radialz.app">Contact</a>
      </div>
      <div className="footer-meta">© 2026 · RadialZ · v1.0</div>
    </div>
  </footer>;


window.Pricing = Pricing;
window.FAQ = FAQ;
window.Footer = Footer;