/* global React, window */
const { useState, useEffect, useMemo, useRef } = React;

// ── Icon SVGs (inline) ──
const Check = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
    <polyline points="20 6 9 17 4 12" />
  </svg>
);
const Lock = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" />
  </svg>
);
const Info = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="10" /><line x1="12" y1="16" x2="12" y2="12" /><line x1="12" y1="8" x2="12.01" y2="8" />
  </svg>
);
// 2026-05-28: Info with a filled dot (tittle) instead of a hairline. Reads
// better at small sizes. Use this for inline "(i)" tooltip triggers.
// Replaces the 7+ inline copies across sections.v2.jsx — new code should
// use <window.InfoFilled /> instead of pasting the SVG.
const InfoFilled = ({ size = 13, strokeWidth = 2.2 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <circle cx="12" cy="12" r="10" /><line x1="12" y1="16" x2="12" y2="12" /><circle cx="12" cy="8" r="0.6" fill="currentColor" />
  </svg>
);
const Chev = ({ dir = 'down', size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{transform: dir==='up' ? 'rotate(180deg)' : dir==='right' ? 'rotate(-90deg)' : 'none'}}>
    <polyline points="6 9 12 15 18 9" />
  </svg>
);
const Spark = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor">
    <path d="M12 2l2.4 6.6L21 11l-6.6 2.4L12 20l-2.4-6.6L3 11l6.6-2.4L12 2z" />
  </svg>
);
const Arrow = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>
);

// ── Currency ──
// 2026-05-29: show 2 decimal places when the value actually has a
// non-zero fractional part (e.g. Premium Sourcing addons priced £1.25,
// £2.50, £4.50). Integer values still render as £1,795 / £99 / £0 —
// no extra zeros. The 0.005 tolerance handles floating-point fuzz so
// 2.4999998 displays as £2.50, not £2.4999998 or £2.
const fmt = (n) => {
  if (n === 0) return '£0';
  const abs = Math.abs(n);
  const hasDecimals = Math.abs(abs - Math.round(abs)) > 0.005;
  const opts = hasDecimals
    ? { minimumFractionDigits: 2, maximumFractionDigits: 2 }
    : { maximumFractionDigits: 0 };
  const s = abs.toLocaleString('en-GB', opts);
  return (n < 0 ? '−£' : '£') + s;
};

// ── Animated number hook ──
function useAnimatedValue(target) {
  const [display, setDisplay] = useState(target);
  const displayRef = useRef(target);
  const rafRef = useRef();
  useEffect(() => {
    cancelAnimationFrame(rafRef.current);
    const from = displayRef.current;
    const to = target;
    if (from === to) return;
    const start = performance.now();
    const dur = 400;
    const tick = (t) => {
      const p = Math.min(1, (t - start) / dur);
      const eased = 1 - Math.pow(1 - p, 3);
      const v = from + (to - from) * eased;
      // 2026-05-29: during the animation we still round to int (keeps
      // the ticker visually steady), but on the final frame snap to the
      // exact target. Without this, totals with decimals (e.g. £1,907.25
      // when summing £2.50/£1.75 line items) would always settle on
      // their rounded int and not match the per-line breakdown.
      const next = p >= 1 ? to : Math.round(v);
      displayRef.current = next;
      setDisplay(next);
      if (p < 1) rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [target]);
  return display;
}

// ── Nav ──
function Nav() {
  return (
    <header className="nav">
      <div className="container nav__inner">
        <div className="nav__brand">
          <div className="nav__logo">G</div>
          <span>GoGorilla<span className="nav__brand-dot">.com</span></span>
        </div>
        <nav className="nav__links">
          <a href="#">Growth <Chev /></a>
          <a href="#">Creative <Chev /></a>
          <a href="#">Talent <Chev /></a>
          <a href="#">Solutions <Chev /></a>
          <a href="#" style={{color: 'var(--gg-heading)', fontWeight: 700}}>Pricing</a>
          <a href="#">Company <Chev /></a>
        </nav>
        <div className="nav__actions">
          <div className="nav__globe" title="Language">🌐</div>
          <span className="nav__login">Log In</span>
          <button className="btn btn--primary btn--sm">Book a Call <span className="btn__arrow">›</span></button>
        </div>
      </div>
    </header>
  );
}

// ── Plan tile ──
function PlanTile({ plan, active, onClick }) {
  return (
    <button className={`plan ${active ? 'plan--active' : ''}`} onClick={onClick} aria-pressed={active}>
      {plan.badge && <img src={`assets/badges/${plan.badge}.webp`} alt={plan.badge} className="plan__badge" />}
      <div className="plan__check"><Check /></div>
      <div className="plan__name">{plan.name}</div>
      <div>
        <div className="plan__price">{plan.priceLabel}</div>
        {!plan.isEnterprise && plan.basePrice > 0 && <div className="plan__price-sub">/ month</div>}
        {plan.isEnterprise && <div className="plan__price-sub">pricing</div>}
      </div>
      <p className="plan__desc">{plan.blurb}</p>
    </button>
  );
}

// ── Service tile ──
function ServiceTile({ service, active, qty, onToggle, onQty, agencyMode, multiplier }) {
  const rawPrice = service.price;
  const discounted = agencyMode ? rawPrice * 0.6 : rawPrice;
  const commitPrice = discounted * multiplier;
  const showQty = service.qty && active;
  const displayPrice = showQty ? commitPrice * qty : commitPrice;
  return (
    <button className={`service ${active ? 'service--active' : ''}`} onClick={onToggle} aria-pressed={active}>
      <div className="service__icon"><img src={service.icon} alt="" /></div>
      <div className="service__body">
        <div className="service__title">
          {service.name}
          {service.badge && <img src={`assets/badges/${service.badge}.webp`} alt={service.badge} className="service__badge" />}
        </div>
        <div className="service__desc">{service.desc}</div>
        <div className="service__price">
          <span className="service__price-from">from</span>
          {rawPrice < 0 ? fmt(rawPrice) : fmt(displayPrice)}
          <span className="service__price-from">/mo</span>
        </div>
        {showQty && (
          <div className="qty" onClick={e => e.stopPropagation()}>
            <span className="qty__btn" onClick={() => onQty(Math.max(1, qty - 1))}>−</span>
            <span className="qty__val">{qty} {service.qtyUnit}{qty > 1 ? 's' : ''}</span>
            <span className="qty__btn" onClick={() => onQty(Math.min(10, qty + 1))}>+</span>
          </div>
        )}
      </div>
      <div className="service__check"><Check size={12} /></div>
    </button>
  );
}

// ── Addon tile (reuses service structure) ──
function AddonTile({ addon, active, onToggle }) {
  return (
    <button className={`service ${active ? 'service--active' : ''}`} onClick={onToggle} aria-pressed={active}>
      <div className="service__icon"><img src={addon.icon} alt="" /></div>
      <div className="service__body">
        <div className="service__title">
          {addon.name}
          {addon.badge && <img src={`assets/badges/${addon.badge}.webp`} alt={addon.badge} className="service__badge" />}
        </div>
        <div className="service__desc">{addon.desc}</div>
        <div className="service__price" style={addon.negative ? {color: 'var(--gg-success)'} : {}}>
          {addon.priceLabel || (addon.price > 0 ? '+' + fmt(addon.price) + ' /mo' : 'Included')}
        </div>
      </div>
      <div className="service__check"><Check size={12} /></div>
    </button>
  );
}

Object.assign(window, { Check, Lock, Info, InfoFilled, Chev, Spark, Arrow, fmt, useAnimatedValue, Nav, PlanTile, ServiceTile, AddonTile });
