// Claim submission screen — wires to POST /api/submissions

const MY_STATES = [
  'Johor', 'Kedah', 'Kelantan', 'Kuala Lumpur', 'Labuan', 'Melaka',
  'Negeri Sembilan', 'Pahang', 'Perak', 'Perlis', 'Penang', 'Putrajaya',
  'Sabah', 'Sarawak', 'Selangor', 'Terengganu',
];

function ClaimScreen({ onBack, onSubmitted, onNavigateTrack }) {
  const [sn, setSn] = React.useState('');
  const [snPhotos, setSnPhotos] = React.useState([]);
  const [purchaseDate, setPurchaseDate] = React.useState('');
  const [invoicePhotos, setInvoicePhotos] = React.useState([]);
  const [giftSelected, setGiftSelected] = React.useState(true);
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [addr1, setAddr1] = React.useState('');
  const [addr2, setAddr2] = React.useState('');
  const [city, setCity] = React.useState('');
  const [state, setState] = React.useState('');
  const [postcode, setPostcode] = React.useState('');
  const [agreed, setAgreed] = React.useState(false);
  const [tncOpen, setTncOpen] = React.useState(false);
  const [scannerOpen, setScannerOpen] = React.useState(false);
  const [sampleOpen, setSampleOpen] = React.useState(false);
  const [invoiceSampleOpen, setInvoiceSampleOpen] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submittedRef, setSubmittedRef] = React.useState(null);
  const [submittedUpstreamRef, setSubmittedUpstreamRef] = React.useState(null);
  const [error, setError] = React.useState('');

  const productDone = sn.trim().length >= 10 && snPhotos.length > 0;
  const purchaseDone = !!purchaseDate && invoicePhotos.length > 0;
  const giftDone = giftSelected;
  const shippingDone = name && email && phone && addr1 && city && state && postcode && agreed;
  const allValid = productDone && purchaseDone && giftDone && shippingDone;

  const disabledReason =
    !productDone ? 'Scan serial to continue'
    : !purchaseDone ? 'Add purchase details'
    : !shippingDone ? 'Complete shipping details'
    : null;

  const handleSubmit = async () => {
    if (!allValid || submitting) return;
    setError('');
    setSubmitting(true);
    try {
      const fd = new FormData();
      fd.append('campaign_slug', 'bambu-x2d-combo-preorder');
      fd.append('serial_number', sn.trim().toUpperCase());
      fd.append('product_series', 'Bambu Lab X2D Combo');
      fd.append('gift_choice', 'Bambu Filament Bundle');
      fd.append('purchase_source', 'Smith3D');
      fd.append('purchase_date', purchaseDate);
      fd.append('full_name', name.trim());
      fd.append('email', email.trim());
      fd.append('contact_number', `+60 ${phone}`.trim());
      fd.append('addr_line1', addr1.trim());
      fd.append('addr_line2', addr2.trim());
      fd.append('city', city.trim());
      fd.append('state', state);
      fd.append('postcode', postcode);
      fd.append('country', 'Malaysia');
      fd.append('agreed', '1');
      snPhotos.forEach(it => it.file && fd.append('sn_photo', it.file));
      invoicePhotos.forEach(it => it.file && fd.append('invoice_photo', it.file));

      const res = await fetch('/api/submissions', { method: 'POST', body: fd });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError(data.message || data.error || 'Submission failed. Please try again.');
        setSubmitting(false);
        return;
      }
      setSubmittedRef(data.smith3d_ref);
      setSubmittedUpstreamRef(data.upstream_ref || null);
      onSubmitted?.(data.smith3d_ref);
    } catch (e) {
      setError('Network error — please check your connection and try again.');
    } finally {
      setSubmitting(false);
    }
  };

  if (submittedRef) return <SuccessCard onTrack={() => onNavigateTrack(submittedRef)} smith3dRef={submittedRef} upstreamRef={submittedUpstreamRef}/>;

  const remaining = [
    productDone ? '1 printer' : null,
    (snPhotos.length + invoicePhotos.length) > 0 ? `${snPhotos.length + invoicePhotos.length} photo${(snPhotos.length + invoicePhotos.length) === 1 ? '' : 's'}` : null,
    city ? `ships to ${city}` : null,
  ].filter(Boolean).join(' · ');

  return (
    <div className="min-h-full bg-neutral-50 relative">
      <div className="bg-white border-b border-neutral-100">
        <div className="max-w-[520px] mx-auto px-5 pt-4 pb-4">
          <div className="flex items-center gap-2 mb-2">
            <button onClick={onBack} className="w-8 h-8 -ml-2 rounded-lg hover:bg-neutral-100 grid place-items-center text-neutral-600">
              <IconChevronLeft size={18}/>
            </button>
            <div className="flex items-center gap-2 text-[11px] font-medium text-[var(--s3-orange)] uppercase tracking-wider">
              <span className="w-1.5 h-1.5 rounded-full bg-[var(--s3-orange)]"/>
              Campaign · Distributor Reward
            </div>
          </div>
          <h1 className="text-[20px] font-bold tracking-tight text-neutral-900 leading-tight">
            Bambu Lab X2D Combo — free filament bundle claim
          </h1>
          <div className="text-[13.5px] text-neutral-600 mt-1">
            Get 3× PLA Lite + 3× PETG Basic <span className="text-neutral-400">(worth RM 354)</span>
          </div>
          <div className="mt-3 inline-flex items-center gap-1.5 text-[11.5px] text-neutral-500 bg-neutral-100 px-2 py-1 rounded-md">
            Rewards are handled by the Bambulab Official Distributor
            <DistributorInfo/>
          </div>
        </div>
      </div>

      <div className="max-w-[520px] mx-auto px-4 py-4 space-y-3 pb-36">

        {/* Section 1 — Product */}
        <Card>
          <CardHeader title="Your printer" subtitle="Scan the serial sticker on the back of your X2D."/>
          <div className="px-5 pb-5 space-y-4">
            <Button variant="primary" size="lg" className="w-full" onClick={() => setScannerOpen(true)}>
              <IconBarcode size={20}/>
              Scan serial number
            </Button>
            <div className="flex items-center gap-3 text-[11px] text-neutral-400">
              <div className="flex-1 h-px bg-neutral-200"/>
              or enter manually
              <div className="flex-1 h-px bg-neutral-200"/>
            </div>
            <div>
              <Label htmlFor="sn" required>Serial number</Label>
              <Input id="sn" mono placeholder="01P00C4A..." value={sn}
                autoCapitalize="characters" autoCorrect="off" spellCheck={false}
                onChange={e => setSn(e.target.value.toUpperCase())}/>
            </div>
            <div className="flex items-start gap-3 p-3 rounded-lg bg-neutral-50 border border-neutral-100">
              <button type="button"
                onClick={() => setSampleOpen(true)}
                className="shrink-0 w-12 h-12 rounded-md bg-white border border-neutral-200 grid place-items-center hover:border-[var(--s3-orange)] active:scale-95 transition-all overflow-hidden"
                aria-label="Show sample photo of the SN sticker">
                <img src="/assets/sn-sticker-sample.png" alt="sample"
                  className="w-full h-full object-cover"/>
              </button>
              <div className="text-[12.5px] text-neutral-600 leading-snug pt-0.5">
                A <b className="text-neutral-800">product label</b> is a tag attached to the product or its container — found on the <b>back</b>, <b>side</b>, or <b>inside the box</b> — and contains the Serial Number.{' '}
                <button type="button" onClick={() => setSampleOpen(true)}
                  className="text-[var(--s3-orange)] font-medium underline-offset-2 hover:underline">
                  See sample
                </button>
                <span className="text-neutral-500"> — both <b>Product Serial No.</b> and <b>Product Type</b> must be visible in your photo.</span>
              </div>
            </div>
            <div>
              <Label required>Photo of SN sticker</Label>
              <PhotoTile
                accept="image/*" capture="environment"
                label="Tap to take photo or upload"
                helper="PNG or JPEG · up to 5 MB"
                onChange={files => setSnPhotos(files || [])}
              />
            </div>
          </div>
        </Card>

        {/* Section 2 — Purchase */}
        <Card>
          <CardHeader title="Your purchase" subtitle="Where and when you bought the printer."/>
          <div className="px-5 pb-5 space-y-4">
            <div>
              <Label>Purchased from</Label>
              <div className="flex items-center gap-2 h-11 px-3 rounded-lg bg-neutral-50 border border-neutral-200">
                <div className="w-7 h-7 rounded-md bg-[var(--s3-navy)] text-white grid place-items-center text-[11px] font-bold">S3D</div>
                <span className="text-[14.5px] text-neutral-800 font-medium">Smith3D</span>
                <span className="group relative ml-auto">
                  <IconInfo size={15} className="text-neutral-400 cursor-help"/>
                  <div className="absolute bottom-full right-0 mb-2 w-60 p-2 rounded-md bg-neutral-900 text-white text-[11.5px] leading-relaxed opacity-0 group-hover:opacity-100 pointer-events-none transition-opacity shadow-lg">
                    Your reward is fulfilled by the official distributor, Pali Pali Trading Sdn Bhd.
                  </div>
                </span>
              </div>
            </div>
            <div>
              <Label htmlFor="date" required>Purchase date</Label>
              <DateField id="date" value={purchaseDate} onChange={setPurchaseDate} maxToday/>
            </div>
            <div>
              <Label required>Photo of invoice / receipt</Label>
              <div className="flex items-start gap-3 p-3 rounded-lg bg-neutral-50 border border-neutral-100 mb-3">
                <button type="button"
                  onClick={() => setInvoiceSampleOpen(true)}
                  className="shrink-0 w-12 h-12 rounded-md bg-white border border-neutral-200 grid place-items-center hover:border-[var(--s3-orange)] active:scale-95 transition-all overflow-hidden"
                  aria-label="Show sample invoice">
                  <img src="/assets/invoice-sample.png" alt="sample"
                    className="w-full h-full object-cover"/>
                </button>
                <div className="text-[12.5px] text-neutral-600 leading-snug pt-0.5">
                  Your Smith3D Sdn Bhd invoice showing this X2D Combo purchase.{' '}
                  <button type="button" onClick={() => setInvoiceSampleOpen(true)}
                    className="text-[var(--s3-orange)] font-medium underline-offset-2 hover:underline">
                    See sample
                  </button>
                  <span className="text-neutral-500"> — <b>Seller Name</b>, <b>Invoice No.</b>, <b>Purchase Date</b>, <b>Product Type &amp; SN</b>, and <b>Purchase Price</b> must all be visible.</span>
                </div>
              </div>
              <PhotoTile
                accept="image/*,application/pdf" capture="environment"
                label="Tap to take photo or upload"
                helper="PNG, JPEG or PDF · up to 5 MB"
                onChange={files => setInvoicePhotos(files || [])}
              />
            </div>
          </div>
        </Card>

        {/* Section 3 — Gift */}
        <Card>
          <CardHeader title="Your reward" subtitle="One free bundle included with your X2D Combo purchase."/>
          <div className="px-5 pb-5">
            <button type="button"
              onClick={() => setGiftSelected(s => !s)}
              className={`w-full text-left rounded-xl border-2 transition-all p-3 flex gap-3
                ${giftSelected ? 'border-[var(--s3-orange)] bg-orange-50/40 ring-4 ring-orange-100'
                  : 'border-neutral-200 hover:border-neutral-300'}`}>
              <div className="shrink-0 w-20 h-20 rounded-lg bg-white grid place-items-center border border-neutral-200 overflow-hidden">
                <img src="/assets/filament-pla-matte.png" alt="PLA Matte filament"
                  className="w-full h-full object-cover"/>
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-start justify-between gap-2">
                  <div className="min-w-0">
                    <div className="text-[14.5px] font-semibold text-neutral-900 leading-snug">Bambu Filament Bundle</div>
                    <div className="text-[11.5px] font-medium text-neutral-500 mt-0.5">Worth RM 354</div>
                  </div>
                  <div className={`shrink-0 w-5 h-5 rounded-full grid place-items-center transition-all
                    ${giftSelected ? 'bg-[var(--s3-orange)]' : 'bg-white border-2 border-neutral-300'}`}>
                    {giftSelected && <IconCheck size={12} stroke="#fff" sw={3}/>}
                  </div>
                </div>
                <div className="text-[12.5px] text-neutral-600 mt-1 leading-snug">
                  3× PLA Basic Lite · 3× PETG Basic
                </div>
                <div className="flex items-center gap-1.5 mt-2 flex-wrap">
                  <div className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-[var(--s3-navy)]/5 border border-[var(--s3-navy)]/10 text-[11px] font-medium text-[var(--s3-navy)]">
                    Free
                  </div>
                  <div className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md bg-white border border-neutral-200 text-[11px] font-medium text-neutral-700">
                    <span className="w-3 h-3 rounded-full border border-black/10"
                      style={{ background: 'conic-gradient(from 0deg, #ef4444, #f59e0b, #eab308, #22c55e, #3b82f6, #8b5cf6, #ec4899, #ef4444)' }}/>
                    Random Color
                  </div>
                </div>
              </div>
            </button>
          </div>
        </Card>

        {/* Section 4 — Shipping */}
        <Card>
          <CardHeader title="Where do we ship it" subtitle="Malaysia addresses only."/>
          <div className="px-5 pb-5 space-y-3">
            <div>
              <Label htmlFor="name" required>Full name</Label>
              <Input id="name" placeholder="As on your IC / passport" value={name}
                onChange={e => setName(e.target.value)}/>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div>
                <Label htmlFor="email" required>Email</Label>
                <Input id="email" type="email" placeholder="you@example.com" value={email}
                  onChange={e => setEmail(e.target.value)}/>
              </div>
              <div>
                <Label htmlFor="phone" required>Contact</Label>
                <PhoneField id="phone" value={phone} onChange={setPhone}/>
              </div>
            </div>
            <div>
              <Label htmlFor="addr1" required>Address line 1</Label>
              <Input id="addr1" placeholder="Unit, building" value={addr1}
                onChange={e => setAddr1(e.target.value)}/>
            </div>
            <div>
              <Label htmlFor="addr2">Address line 2</Label>
              <Input id="addr2" placeholder="Street" value={addr2}
                onChange={e => setAddr2(e.target.value)}/>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label htmlFor="city" required>City</Label>
                <Input id="city" placeholder="e.g. Kuala Lumpur" value={city}
                  onChange={e => setCity(e.target.value)}/>
              </div>
              <div>
                <Label htmlFor="postcode" required>Postcode</Label>
                <Input id="postcode" placeholder="50000" mono
                  inputMode="numeric" pattern="[0-9]*" maxLength={5}
                  value={postcode}
                  onChange={e => setPostcode(e.target.value.replace(/\D/g,'').slice(0,5))}/>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label htmlFor="state" required>State</Label>
                <StateField id="state" value={state} onChange={setState} states={MY_STATES}/>
              </div>
              <div>
                <Label>Country</Label>
                <div className="h-11 px-3 rounded-lg bg-neutral-50 border border-neutral-200 flex items-center text-[14.5px] text-neutral-700">
                  🇲🇾 Malaysia
                </div>
              </div>
            </div>
            <label className="flex items-start gap-2.5 pt-2 cursor-pointer group">
              <input type="checkbox" checked={agreed} onChange={e => setAgreed(e.target.checked)} className="sr-only"/>
              <span className={`shrink-0 mt-0.5 w-[18px] h-[18px] rounded border-2 transition-colors grid place-items-center
                ${agreed ? 'bg-[var(--s3-orange)] border-[var(--s3-orange)]' : 'bg-white border-neutral-300 group-hover:border-neutral-400'}`}>
                {agreed && <IconCheck size={12} stroke="#fff" sw={3}/>}
              </span>
              <span className="text-[13px] text-neutral-700 leading-snug">
                I agree to the{' '}
                <button type="button" onClick={(e) => { e.preventDefault(); setTncOpen(true); }}
                  className="text-[var(--s3-orange)] underline underline-offset-2 font-medium">
                  campaign Terms & Conditions
                </button>.
              </span>
            </label>
          </div>
        </Card>

        <div className="text-center text-[11px] text-neutral-400 pt-2">
          Smith3D Sdn Bhd · we don't share your details outside this claim.
        </div>
      </div>

      {/* Sticky submit */}
      <div className="fixed inset-x-0 bottom-0 border-t border-neutral-200 bg-white/95 backdrop-blur px-4 py-3 pb-[max(1rem,env(safe-area-inset-bottom))]">
        <div className="max-w-[520px] mx-auto">
          {error && <div className="text-[12.5px] text-red-600 text-center mb-2">{error}</div>}
          {remaining && !error && (
            <div className="text-[11.5px] text-neutral-500 text-center mb-2">{remaining}</div>
          )}
          <Button variant="primary" size="xl" className="w-full"
            disabled={!allValid || submitting}
            onClick={handleSubmit}>
            {submitting ? (
              <>
                <svg className="animate-spin" width="18" height="18" viewBox="0 0 24 24" fill="none">
                  <circle cx="12" cy="12" r="10" stroke="currentColor" strokeOpacity="0.3" strokeWidth="3"/>
                  <path d="M12 2a10 10 0 0 1 10 10" stroke="currentColor" strokeWidth="3" strokeLinecap="round"/>
                </svg>
                Submitting…
              </>
            ) : disabledReason ? disabledReason : 'Submit claim'}
          </Button>
        </div>
      </div>

      <ScannerModal open={scannerOpen} onClose={() => setScannerOpen(false)} onDetect={(s) => setSn(s)}/>
      <BottomSheet open={tncOpen} onClose={() => setTncOpen(false)} title="Terms & Conditions">
        <TermsContent/>
      </BottomSheet>
      <SnStickerSample open={sampleOpen} onClose={() => setSampleOpen(false)}/>
      <InvoiceSample open={invoiceSampleOpen} onClose={() => setInvoiceSampleOpen(false)}/>
    </div>
  );
}

// Small (i) icon that reveals the distributor name on tap (mobile) or hover
// (desktop). Toggle on tap so fingers work; auto-dismiss on outside click.
function DistributorInfo() {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const off = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('click', off);
    return () => document.removeEventListener('click', off);
  }, [open]);
  return (
    <span ref={ref} className="relative inline-flex">
      <button type="button"
        onClick={(e) => { e.stopPropagation(); setOpen(v => !v); }}
        className="w-4 h-4 rounded-full bg-neutral-200 text-neutral-600 grid place-items-center hover:bg-neutral-300 active:scale-95"
        aria-label="Distributor details">
        <IconInfo size={10}/>
      </button>
      {open && (
        <span className="absolute top-full left-1/2 -translate-x-1/2 mt-1.5 whitespace-nowrap px-2.5 py-1.5 rounded-md bg-neutral-900 text-white text-[11.5px] leading-tight shadow-lg z-10"
          style={{ animation: 'fadeIn 140ms ease' }}>
          Pali Pali Trading Sdn Bhd
          <span className="absolute bottom-full left-1/2 -translate-x-1/2 w-0 h-0 border-l-[4px] border-l-transparent border-r-[4px] border-r-transparent border-b-[4px] border-b-neutral-900"/>
        </span>
      )}
    </span>
  );
}

// Sample-sticker reference popup. Shown when the user taps the photo
// thumbnail or "See sample" link — so they know exactly what must be
// visible when uploading their own photo (Product Serial No. + Product Type).
function SnStickerSample({ open, onClose }) {
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4"
      onClick={onClose}>
      <div className="absolute inset-0 bg-black/70" style={{ animation: 'fadeIn 180ms ease' }}/>
      <div onClick={e => e.stopPropagation()}
        className="relative bg-white rounded-2xl max-w-md w-full max-h-[90vh] flex flex-col shadow-2xl overflow-hidden"
        style={{ animation: 'slideUp 260ms cubic-bezier(0.22, 1, 0.36, 1)' }}>
        <div className="flex items-center justify-between px-4 py-3 border-b border-neutral-100">
          <div className="text-[15px] font-semibold">Sample SN sticker</div>
          <button onClick={onClose} className="w-8 h-8 rounded-full hover:bg-neutral-100 grid place-items-center" aria-label="Close">
            <IconX size={18}/>
          </button>
        </div>
        <div className="overflow-auto">
          <div className="px-5 pt-4 text-[13px] text-neutral-600 leading-relaxed">
            A <b className="text-neutral-900">product label</b> is a tag or piece of material attached to a product or its container that provides information to consumers. It can be found on the <b>back</b>, <b>side</b>, or <b>inside the box</b>, and contains the Product Serial Number (SN).
          </div>
          <div className="px-5 pt-3 text-[12.5px] text-[var(--s3-orange)] font-medium">
            ↓ This is the actual place you can find the SN:
          </div>
          <div className="p-4 bg-neutral-50 grid place-items-center mt-2">
            <img src="/assets/sn-sticker-sample.png" alt="SN sticker sample"
              className="max-w-full max-h-[50vh] rounded-md shadow border border-neutral-200"/>
          </div>
          <div className="px-5 py-4 text-[13.5px] text-neutral-700 leading-relaxed space-y-2">
            <div className="font-medium text-neutral-900">Your photo must clearly show both:</div>
            <ul className="space-y-1.5 pl-1">
              <li className="flex gap-2">
                <span className="w-5 h-5 rounded-full bg-red-100 text-red-700 grid place-items-center text-[11px] font-bold shrink-0 mt-0.5">1</span>
                <span><b>Product Serial No.</b> — e.g. <span className="font-mono">03919D580607841</span></span>
              </li>
              <li className="flex gap-2">
                <span className="w-5 h-5 rounded-full bg-red-100 text-red-700 grid place-items-center text-[11px] font-bold shrink-0 mt-0.5">2</span>
                <span><b>Product Type</b> — e.g. <span className="font-mono">A1-Combo</span></span>
              </li>
            </ul>
            <div className="text-[12.5px] text-neutral-500 pt-1">
              Both highlighted in red on the example above. Without both, we can't verify your claim.
            </div>
          </div>
        </div>
        <div className="px-4 py-3 border-t border-neutral-100">
          <button onClick={onClose}
            className="w-full h-11 rounded-full bg-[var(--s3-orange)] text-white text-[14px] font-semibold active:scale-95">
            Got it
          </button>
        </div>
      </div>
    </div>
  );
}

// Sample-invoice reference popup. Same pattern as SnStickerSample — shows
// what a valid purchase proof looks like so users upload something we can
// actually verify.
function InvoiceSample({ open, onClose }) {
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4"
      onClick={onClose}>
      <div className="absolute inset-0 bg-black/70" style={{ animation: 'fadeIn 180ms ease' }}/>
      <div onClick={e => e.stopPropagation()}
        className="relative bg-white rounded-2xl max-w-md w-full max-h-[90vh] flex flex-col shadow-2xl overflow-hidden"
        style={{ animation: 'slideUp 260ms cubic-bezier(0.22, 1, 0.36, 1)' }}>
        <div className="flex items-center justify-between px-4 py-3 border-b border-neutral-100">
          <div className="text-[15px] font-semibold">Sample invoice</div>
          <button onClick={onClose} className="w-8 h-8 rounded-full hover:bg-neutral-100 grid place-items-center" aria-label="Close">
            <IconX size={18}/>
          </button>
        </div>
        <div className="overflow-auto">
          <div className="px-5 pt-4 text-[13px] text-neutral-600 leading-relaxed">
            An <b className="text-neutral-900">invoice</b> is the receipt issued by the seller when you paid for the product. It records who sold it, what was sold, when, and for how much — enough for us to verify your purchase.
          </div>
          <div className="px-5 pt-3 text-[12.5px] text-[var(--s3-orange)] font-medium">
            ↓ This is what your Smith3D invoice should look like:
          </div>
          <div className="p-4 bg-neutral-50 grid place-items-center mt-2">
            <img src="/assets/invoice-sample.png" alt="Invoice sample"
              className="max-w-full max-h-[50vh] rounded-md shadow border border-neutral-200"/>
          </div>
          <div className="px-5 py-4 text-[13.5px] text-neutral-700 leading-relaxed space-y-2">
            <div className="font-medium text-neutral-900">Your photo must clearly show all of:</div>
            <ul className="space-y-1.5 pl-1">
              <li className="flex gap-2">
                <span className="w-5 h-5 rounded-full bg-red-100 text-red-700 grid place-items-center text-[11px] font-bold shrink-0 mt-0.5">1</span>
                <span><b>Seller Name</b> — Smith3D Sdn Bhd</span>
              </li>
              <li className="flex gap-2">
                <span className="w-5 h-5 rounded-full bg-red-100 text-red-700 grid place-items-center text-[11px] font-bold shrink-0 mt-0.5">2</span>
                <span><b>Invoice No.</b> — e.g. <span className="font-mono">2025-6430</span></span>
              </li>
              <li className="flex gap-2">
                <span className="w-5 h-5 rounded-full bg-red-100 text-red-700 grid place-items-center text-[11px] font-bold shrink-0 mt-0.5">3</span>
                <span><b>Purchase Date</b> — e.g. <span className="font-mono">23.10.2025</span></span>
              </li>
              <li className="flex gap-2">
                <span className="w-5 h-5 rounded-full bg-red-100 text-red-700 grid place-items-center text-[11px] font-bold shrink-0 mt-0.5">4</span>
                <span><b>Product Type &amp; Serial No.</b> — e.g. <span className="font-mono">Bambu Lab A1 Combo · SN: 03919D580608166</span></span>
              </li>
              <li className="flex gap-2">
                <span className="w-5 h-5 rounded-full bg-red-100 text-red-700 grid place-items-center text-[11px] font-bold shrink-0 mt-0.5">5</span>
                <span><b>Purchase Price</b> — e.g. <span className="font-mono">RM 1,999.00</span></span>
              </li>
            </ul>
            <div className="text-[12.5px] text-neutral-500 pt-1">
              All five highlighted in red on the example above. Missing fields will delay or block your claim.
            </div>
          </div>
        </div>
        <div className="px-4 py-3 border-t border-neutral-100">
          <button onClick={onClose}
            className="w-full h-11 rounded-full bg-[var(--s3-orange)] text-white text-[14px] font-semibold active:scale-95">
            Got it
          </button>
        </div>
      </div>
    </div>
  );
}

function SuccessCard({ onTrack, smith3dRef, upstreamRef }) {
  const [copied, setCopied] = React.useState(false);
  const copy = () => {
    navigator.clipboard?.writeText(smith3dRef);
    setCopied(true);
    setTimeout(() => setCopied(false), 1800);
  };
  return (
    <div className="min-h-full bg-neutral-50">
      <div className="min-h-full flex flex-col items-center justify-start px-5 pt-12 pb-12 max-w-[520px] mx-auto">
        <div className="w-20 h-20 rounded-full bg-green-50 border-2 border-green-100 grid place-items-center mb-5"
          style={{ animation: 'popIn 500ms cubic-bezier(0.34, 1.56, 0.64, 1)' }}>
          <div className="w-14 h-14 rounded-full bg-green-500 grid place-items-center">
            <IconCheck size={32} stroke="#fff" sw={3}/>
          </div>
        </div>
        <h2 className="text-[22px] font-bold tracking-tight text-neutral-900 text-center">
          Claim submitted
        </h2>
        <p className="text-[14px] text-neutral-600 text-center mt-1.5 max-w-xs leading-snug">
          We've received your claim for the X2D filament bundle. Keep this reference.
        </p>
        <div className="w-full mt-6 rounded-xl bg-white border border-neutral-200 p-4">
          <div className="text-[11px] font-medium text-neutral-500 uppercase tracking-wider">
            Smith3D tracking reference
          </div>
          <button onClick={copy} className="w-full mt-2 flex items-center justify-between gap-3 group">
            <span className="font-mono text-[22px] font-semibold text-neutral-900 tracking-wider">{smith3dRef}</span>
            <span className={`inline-flex items-center gap-1 text-[12px] font-medium transition-colors
              ${copied ? 'text-green-600' : 'text-neutral-500 group-hover:text-[var(--s3-orange)]'}`}>
              {copied ? <><IconCheck size={13} sw={2.5}/> Copied</> : <><IconCopy size={13}/> Copy</>}
            </span>
          </button>
          <div className="mt-3 pt-3 border-t border-neutral-100 text-[12.5px] text-neutral-600 leading-relaxed">
            {upstreamRef
              ? <>We've also forwarded your submission to the distributor <span className="font-mono text-[11.5px] text-neutral-500">(ref {upstreamRef})</span>. We'll email you when it's approved.</>
              : <>Your claim is queued with the distributor. We'll email you once it's forwarded and again when it's approved.</>}
          </div>
        </div>
        <Button variant="primary" size="lg" className="w-full mt-5" onClick={onTrack}>
          Track my claim
          <IconChevronRight size={18}/>
        </Button>
        <a href="/" className="mt-3 text-[13px] text-neutral-500 hover:text-neutral-800">
          Back to home
        </a>
        <div className="mt-8 text-[11.5px] text-neutral-400 text-center leading-relaxed">
          A confirmation has been sent to your email.<br/>
          Check spam if you don't see it within 5 minutes.
        </div>
      </div>
    </div>
  );
}

function TermsContent() {
  return (
    <div className="space-y-3">
      <p><strong>Campaign period.</strong> The X2D filament bundle claim is open from 1 Apr 2026 to 30 Jun 2026, or while stocks last.</p>
      <p><strong>Eligibility.</strong> Claims are limited to one per Bambu Lab X2D Combo unit purchased from Smith3D. You must submit the serial number and original invoice.</p>
      <p><strong>Shipping.</strong> We ship within Malaysia only, typically within 7–10 working days of distributor approval. East Malaysia addresses may take longer.</p>
      <p><strong>Approval.</strong> Rewards are handled by the official distributor, Pali Pali Trading Sdn Bhd. Final approval is at the distributor's discretion; Smith3D forwards your claim and handles fulfillment.</p>
      <p><strong>Privacy.</strong> Your details are used only to process this claim and are shared with the distributor and our courier partner (Pos Laju / J&T).</p>
      <p><strong>Questions.</strong> Get in touch with your S3D reference:</p>
      <ContactLinks/>
    </div>
  );
}

Object.assign(window, { ClaimScreen });
