// 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 [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">
            <IconInfo size={12} className="text-neutral-400"/>
            Rewards are handled by the official distributor.
          </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">
              <div className="shrink-0 w-12 h-12 rounded-md bg-white border border-neutral-200 grid place-items-center">
                <svg width="40" height="30" viewBox="0 0 40 30">
                  <rect x="2" y="4" width="36" height="22" rx="2" fill="#fff" stroke="#999"/>
                  <g fill="#222">
                    <rect x="6" y="8" width="1" height="14"/>
                    <rect x="8" y="8" width="2" height="14"/>
                    <rect x="11" y="8" width="1" height="14"/>
                    <rect x="13" y="8" width="3" height="14"/>
                    <rect x="17" y="8" width="1" height="14"/>
                    <rect x="19" y="8" width="2" height="14"/>
                    <rect x="22" y="8" width="1" height="14"/>
                    <rect x="24" y="8" width="3" height="14"/>
                    <rect x="28" y="8" width="1" height="14"/>
                    <rect x="30" y="8" width="2" height="14"/>
                    <rect x="33" y="8" width="1" height="14"/>
                  </g>
                </svg>
              </div>
              <div className="text-[12.5px] text-neutral-600 leading-snug pt-0.5">
                Printed on the silver sticker at the back of your X2D, just above the power socket.
              </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>
              <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-gradient-to-br from-orange-100 to-orange-50 grid place-items-center border border-orange-100">
                <FilamentIllustration/>
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-start justify-between gap-2">
                  <div className="text-[14.5px] font-semibold text-neutral-900 leading-snug">Bambu Filament Bundle</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-0.5 leading-snug">
                  3× PLA Basic Lite · 3× PETG Basic
                </div>
                <div className="flex items-center gap-2 mt-2">
                  <div className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-white border border-neutral-200 text-[11px] font-medium text-neutral-700">
                    Worth RM 354
                  </div>
                  <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>
              </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>
    </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 });
