/* global React, AX */

/* -- inject range-input styles once -- */
(function () {
  if (document.getElementById('ax-range-css')) return;
  const s = document.createElement('style');
  s.id = 'ax-range-css';
  s.textContent = '.ax-r{-webkit-appearance:none;appearance:none;height:3px;border-radius:3px;outline:none;cursor:pointer;}.ax-r::-webkit-slider-thumb{-webkit-appearance:none;width:16px;height:16px;border-radius:50%;background:#FAFAFA;cursor:pointer;box-shadow:0 1px 3px rgba(0,0,0,0.5);}.ax-r::-moz-range-thumb{width:16px;height:16px;border-radius:50%;background:#FAFAFA;cursor:pointer;border:none;}';
  document.head.appendChild(s);
}());

/* ---------- SliderField ---------- */
function SliderField({ label, value, setter, min, max, step, fmt }) {
  const pct = Math.round(((value - min) / (max - min)) * 100);
  return (
    <div className="mb-6">
      <div className="flex justify-between mb-2">
        <span className="text-[13px] font-semibold text-sub">{label}</span>
        <span className="text-[14px] font-bold">{fmt(value)}</span>
      </div>
      <input type="range" min={min} max={max} step={step} value={value}
        className="ax-r w-full"
        style={{ background: `linear-gradient(to right,rgba(250,250,250,0.8) ${pct}%,rgba(250,250,250,0.12) ${pct}%)` }}
        onChange={e => setter(+e.target.value)}
      />
    </div>
  );
}

/* ============ COMMISSION CALC ============ */
function CommissionCalc() {
  const [tickets, setTickets] = React.useState(200);
  const [price, setPrice] = React.useState(25);
  const [mEvents, setMEvents] = React.useState(4);

  const annualRev = tickets * price * mEvents * 12;
  const fmtK = n => n >= 10000 ? `€${Math.round(n / 1000)}k` : n >= 1000 ? `€${(n / 1000).toFixed(1)}k` : `€${n}`;

  const comps = [
    { name: "Eventbrite", pct: 8,  note: "~8% all-in" },
    { name: "RA Tickets",  pct: 10, note: "~10% service" },
    { name: "DICE",        pct: 10, note: "~10% service" },
    { name: "Shotgun",     pct: 8,  note: "~8% ticketing" },
  ];
  const topFee = Math.round(annualRev * 0.10);

  return (
    <section id="pricing" className="relative py-20 lg:py-28">
      <div className="max-w-[1240px] mx-auto px-6 lg:px-10">

        <div className="reveal max-w-[620px] mb-14">
          <AX.Eyebrow>0% commission</AX.Eyebrow>
          <h2 className="mt-5 font-bold tracking-[-0.03em] leading-[1.02]" style={{ fontSize: "clamp(32px,4.4vw,52px)" }}>
            How much are you<br/>leaving on the table?
          </h2>
          <p className="mt-5 text-[16px] text-sub leading-relaxed max-w-[500px]">
            Every major ticketing platform takes a cut of your revenue. Axxess doesn't. Use the sliders to see exactly what you'd keep.
          </p>
        </div>

        <div className="grid lg:grid-cols-2 gap-6">
          {/* — competitor fees — */}
          <div className="reveal rounded-3xl p-7 lg:p-9" style={{ background: "rgba(255,255,255,0.025)", boxShadow: "inset 0 0 0 1px rgba(250,250,250,0.08)" }}>
            <div className="text-[11px] font-bold uppercase tracking-[0.18em] text-faint mb-7">Annual commission at your volume</div>
            <div className="space-y-5">
              {comps.map((c) => {
                const fee = Math.round(annualRev * c.pct / 100);
                const bar = topFee > 0 ? Math.min(Math.round((fee / topFee) * 100), 100) : 0;
                return (
                  <div key={c.name}>
                    <div className="flex items-baseline justify-between mb-2">
                      <div>
                        <span className="text-[14px] font-semibold">{c.name}</span>
                        <span className="ml-2 text-[10.5px] text-faint">{c.note}</span>
                      </div>
                      <span className="text-[15px] font-bold tabular-nums" style={{ color: "rgba(255,100,85,0.9)" }}>{fmtK(fee)}/yr</span>
                    </div>
                    <div className="h-1.5 rounded-full" style={{ background: "rgba(255,255,255,0.06)" }}>
                      <div className="h-full rounded-full transition-all duration-300 ease-out" style={{ width: `${bar}%`, background: "linear-gradient(90deg,rgba(255,90,70,0.5),rgba(255,60,50,0.7))" }}></div>
                    </div>
                  </div>
                );
              })}
            </div>
            <div className="mt-7 rounded-2xl p-5" style={{ background: "rgba(250,250,250,0.05)", boxShadow: "inset 0 0 0 1px rgba(250,250,250,0.22)" }}>
              <div className="flex items-center justify-between">
                <AX.Wordmark markSize={18} fontSize={14} ls={4} accent/>
                <div>
                  <span className="text-[26px] font-bold tabular-nums">€0</span>
                  <span className="text-[11px] text-faint ml-1.5">commission</span>
                </div>
              </div>
              <div className="mt-3 pt-3 text-[14px] font-semibold" style={{ borderTop: "1px solid rgba(250,250,250,0.08)" }}>
                You keep <span className="font-bold text-amberHi">{fmtK(topFee)}</span> more every year.
              </div>
            </div>
          </div>

          {/* — sliders — */}
          <div className="reveal rounded-3xl p-7 lg:p-9" data-d="1" style={{ background: "rgba(255,255,255,0.025)", boxShadow: "inset 0 0 0 1px rgba(250,250,250,0.08)" }}>
            <div className="text-[11px] font-bold uppercase tracking-[0.18em] text-faint mb-7">Your event volume</div>
            <SliderField label="Tickets per event" value={tickets} setter={setTickets} min={50} max={1000} step={10} fmt={v => v.toLocaleString()} />
            <SliderField label="Average ticket price" value={price} setter={setPrice} min={5} max={150} step={5} fmt={v => `€${v}`} />
            <SliderField label="Events per month" value={mEvents} setter={setMEvents} min={1} max={20} step={1} fmt={v => v} />
            <div className="mt-2 pt-5" style={{ borderTop: "1px solid rgba(250,250,250,0.07)" }}>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <div className="text-[11px] font-semibold uppercase tracking-[0.12em] text-faint">Annual revenue</div>
                  <div className="text-[22px] font-bold mt-1.5 tabular-nums">{fmtK(annualRev)}</div>
                </div>
                <div>
                  <div className="text-[11px] font-semibold uppercase tracking-[0.12em] text-faint">Commission saved</div>
                  <div className="text-[22px] font-bold mt-1.5 tabular-nums text-amberHi">{fmtK(topFee)}</div>
                </div>
              </div>
              <p className="mt-4 text-[11.5px] text-faint leading-relaxed">Fees approximate based on published platform pricing. Check current rates before making decisions.</p>
            </div>
          </div>
        </div>

      </div>
    </section>
  );
}

/* ============ SECURITY PROOF ============ */
function SecurityProof() {
  const features = [
    {
      icon: (
        <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
          <path d="M11 2L4 5v5c0 4.55 3.02 8.55 7 9.5 3.98-.95 7-4.95 7-9.5V5L11 2z" stroke="#FAFAFA" strokeWidth="1.6" strokeLinejoin="round"/>
          <path d="M8 11l2 2 4-4" stroke="#FAFAFA" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      ),
      tag: "Offline validated",
      title: "Works with no signal",
      body: "Tickets are verified cryptographically on-device. No network request per scan — your door keeps working through an outage, dead zone, or basement venue.",
      checks: ["Sub-1s scan time", "Syncs when back online", "No scanner hardware"],
    },
    {
      icon: (
        <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
          <circle cx="11" cy="11" r="8.2" stroke="#FAFAFA" strokeWidth="1.6"/>
          <path d="M7.5 7.5l7 7M14.5 7.5l-7 7" stroke="#FAFAFA" strokeWidth="1.7" strokeLinecap="round"/>
        </svg>
      ),
      tag: "Duplicate blocked",
      title: "One ticket, one entry",
      body: "Every scan is recorded in real time. The moment a duplicate or screenshot is presented, the scanner shows red — before the legitimate holder even arrives.",
      checks: ["Real-time state sync", "Screenshot detection", "Instant rejection"],
    },
    {
      icon: (
        <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
          <rect x="3" y="5" width="16" height="13" rx="2" stroke="#FAFAFA" strokeWidth="1.6"/>
          <path d="M3 10h16M8 3v4M14 3v4" stroke="#FAFAFA" strokeWidth="1.6" strokeLinecap="round"/>
          <path d="M7 14h3M12 14h3" stroke="#FAFAFA" strokeWidth="1.5" strokeLinecap="round"/>
        </svg>
      ),
      tag: "Full audit trail",
      title: "Every scan attributed",
      body: "Each admission is timestamped and tied to the staff member who approved it. If anything is disputed, you have a complete digital log — names, times, decisions.",
      checks: ["Per-staff attribution", "Timestamped entries", "Export-ready log"],
    },
  ];

  return (
    <section id="security" className="relative py-20 lg:py-28">
      <div className="max-w-[1240px] mx-auto px-6 lg:px-10">
        <div className="reveal flex flex-wrap items-end justify-between gap-6 mb-14">
          <div className="max-w-[540px]">
            <AX.Eyebrow>Door security</AX.Eyebrow>
            <h2 className="mt-5 font-bold tracking-[-0.03em] leading-[1.02]" style={{ fontSize: "clamp(32px,4.4vw,52px)" }}>
              Fraud-proof<br/>at the door.
            </h2>
          </div>
          <p className="text-[15px] text-sub max-w-[360px] leading-relaxed">
            Cryptographic signatures make every ticket forgery-resistant. Screenshots fail. Duplicates fail. No extra hardware required.
          </p>
        </div>

        <div className="grid md:grid-cols-3 gap-5">
          {features.map((f, i) => (
            <div key={i} className="reveal rounded-3xl p-7 lg:p-8 flex flex-col" data-d={i + 1}
              style={{ background: "rgba(255,255,255,0.025)", boxShadow: "inset 0 0 0 1px rgba(250,250,250,0.08)" }}>
              <div className="w-12 h-12 rounded-2xl flex items-center justify-center mb-5"
                style={{ background: "rgba(250,250,250,0.07)", boxShadow: "inset 0 0 0 1px rgba(250,250,250,0.14)" }}>
                {f.icon}
              </div>
              <div className="text-[10px] font-bold uppercase tracking-[0.18em] text-faint mb-2.5">{f.tag}</div>
              <h3 className="text-[18px] font-bold tracking-[-0.01em] leading-snug mb-3">{f.title}</h3>
              <p className="text-[14px] text-sub leading-relaxed flex-1">{f.body}</p>
              <div className="mt-5 pt-5 space-y-2.5" style={{ borderTop: "1px solid rgba(250,250,250,0.07)" }}>
                {f.checks.map(c => (
                  <div key={c} className="flex items-center gap-2.5">
                    <AX.IconCheck size={13} stroke={2.5} style={{ color: "rgba(250,250,250,0.55)", flexShrink: 0 }}/>
                    <span className="text-[12.5px] text-sub">{c}</span>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============ SETUP FLOW ============ */
function SetupFlow() {
  const steps = [
    { n: "01", time: "< 2 min",  title: "Create your event",  body: "Name, date, venue, description. Copy from a past event in one tap." },
    { n: "02", time: "< 3 min",  title: "Set ticket tiers",   body: "Early bird, general, VIP — price, capacity, and sale windows per tier." },
    { n: "03", time: "Instant",  title: "Share your link",    body: "Copy your event URL. Post to Instagram, WhatsApp, or wherever your audience is." },
    { n: "04", time: "Night of", title: "Open your door",     body: "Staff open the app. Scan tickets and reservations from the same screen. Live." },
  ];

  return (
    <section id="setup" className="relative py-20 lg:py-28" style={{ background: "linear-gradient(180deg,transparent,rgba(250,250,250,0.022) 40%,transparent)" }}>
      <div className="max-w-[1240px] mx-auto px-6 lg:px-10">
        <div className="reveal text-center max-w-[600px] mx-auto mb-16">
          <AX.Eyebrow className="justify-center">30 minutes to live</AX.Eyebrow>
          <h2 className="mt-5 font-bold tracking-[-0.03em] leading-[1.02]" style={{ fontSize: "clamp(32px,4.4vw,52px)" }}>
            First event live.<br/>No setup call needed.
          </h2>
          <p className="mt-5 text-[16px] text-sub leading-relaxed">
            No onboarding meeting, no account manager, no waiting. Create, configure, share — that's the whole process.
          </p>
        </div>

        <div className="reveal relative" data-d="1">
          <div className="hidden lg:block absolute top-[34px] inset-x-0 h-px mx-20" style={{ background: "linear-gradient(to right,transparent,rgba(250,250,250,0.12) 10%,rgba(250,250,250,0.12) 90%,transparent)" }}></div>
          <div className="grid lg:grid-cols-4 gap-6 lg:gap-8">
            {steps.map((s, i) => (
              <div key={i}>
                <div className="flex lg:flex-col items-start gap-5 lg:gap-0">
                  <div className="relative z-10 flex-shrink-0 w-[68px] h-[68px] rounded-2xl flex flex-col items-center justify-center"
                    style={{ background: "#0A0A0A", boxShadow: "inset 0 0 0 1px rgba(250,250,250,0.2), 0 0 0 5px #0A0A0A" }}>
                    <span className="text-[10px] font-bold tracking-[0.14em] text-faint leading-none">{s.n}</span>
                    <span className="text-[10px] font-semibold mt-1 leading-tight text-center px-1" style={{ color: "rgba(250,250,250,0.75)" }}>{s.time}</span>
                  </div>
                  <div className="lg:mt-7">
                    <h3 className="text-[16px] font-bold leading-tight">{s.title}</h3>
                    <p className="mt-2 text-[13.5px] text-sub leading-relaxed">{s.body}</p>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="reveal mt-14 text-center" data-d="2">
          <p className="text-[15px] text-sub mb-5">Free through launch · No contract · No hardware required</p>
          <AX.CTA primary href="mailto:contact@yellogem.ma">Get started tonight</AX.CTA>
        </div>
      </div>
    </section>
  );
}

/* ============ FAQ ============ */
function FAQ() {
  const [open, setOpen] = React.useState(null);

  const items = [
    {
      q: "What hardware do I need at the door?",
      a: "None beyond the phones your staff already carry. Axxess works on any modern iPhone or Android — no dedicated scanner rentals, no upfront equipment cost, no vendor lock-in on devices.",
    },
    {
      q: "What if the internet cuts out mid-event?",
      a: "Axxess validates tickets cryptographically on-device. No network call is needed per scan — your door keeps working through an outage, dead zone, or basement venue. Scans sync automatically when connectivity returns.",
    },
    {
      q: "A guest forgot their phone. Can they still get in?",
      a: "Yes. Staff can search by guest name directly in the app and admit manually. The name-search fallback is built into every door screen — no extra step, no separate flow.",
    },
    {
      q: "Can guests share screenshots or forward tickets?",
      a: "No. Each ticket contains a cryptographic signature tied to the buyer's account. A screenshot fails instantly on the first scan. Your door staff don't need to tell the difference — the app tells them.",
    },
    {
      q: "How does Axxess handle refunds?",
      a: "Venue staff issue refunds directly from the Axxess dashboard. You set the policy — full refund anytime, partial, or no-refund after a defined cutoff date. Funds return to the buyer via their original payment method.",
    },
    {
      q: "When does the venue receive payouts?",
      a: "Payouts are processed within 2–5 business days of each event via Stripe. You see a full breakdown per event: tickets sold, deposits collected, and refunds issued.",
    },
    {
      q: "Is there a contract or minimum commitment?",
      a: "No contract, no minimum term. You can stop using Axxess after any event. We earn your business every night.",
    },
    {
      q: "What does Axxess cost after launch?",
      a: "Ticket sales remain at 0% commission permanently — that's a founding principle, not a launch promotion. Axxess will generate revenue through optional analytics upgrades, premium integrations, and white-label features announced separately.",
    },
  ];

  return (
    <section id="faq" className="relative py-20 lg:py-28">
      <div className="max-w-[1240px] mx-auto px-6 lg:px-10">
        <div className="reveal max-w-[480px] mb-12">
          <AX.Eyebrow>FAQ</AX.Eyebrow>
          <h2 className="mt-5 font-bold tracking-[-0.03em] leading-[1.02]" style={{ fontSize: "clamp(30px,3.8vw,48px)" }}>
            Everything you're<br/>about to ask.
          </h2>
        </div>

        <div className="reveal max-w-[780px]" data-d="1">
          {items.map((item, i) => (
            <div key={i} style={{ borderTop: "1px solid rgba(250,250,250,0.07)" }}>
              <button
                className="focusable w-full flex items-center justify-between gap-4 py-5 text-left"
                onClick={() => setOpen(open === i ? null : i)}
                aria-expanded={open === i}
              >
                <span className="text-[15.5px] font-semibold leading-snug pr-2">{item.q}</span>
                <svg width="18" height="18" viewBox="0 0 18 18" fill="none" className="flex-shrink-0"
                  style={{ transform: open === i ? "rotate(180deg)" : "none", transition: "transform .22s ease", color: "rgba(250,250,250,0.45)" }}>
                  <path d="M4 7l5 4.5L14 7" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
              {open === i && (
                <p className="pb-6 text-[15px] text-sub leading-relaxed max-w-[660px]">{item.a}</p>
              )}
            </div>
          ))}
          <div style={{ borderTop: "1px solid rgba(250,250,250,0.07)" }}></div>
        </div>
      </div>
    </section>
  );
}

window.AX = Object.assign(window.AX || {}, { CommissionCalc, SecurityProof, SetupFlow, FAQ });
