const { Button, Badge, IconButton, Icon, Modal, Input } = window.PryzeDesignSystem_b2bad9;
const { REWARDS, USER, CATEGORIES, AMOUNT_PRESETS, PTS_PER_DOLLAR, POINTS_PER_SHIFT, BANNERS, PRYZER_QUOTES, GUIDE_STEPS } = window.PryzeData;

function CategoryPills({ active, onChange }) {
  return (
    <div className="pills-row">
      {CATEGORIES.map(c => (
        <button key={c} className={`pill ${active === c ? 'pill-active' : ''}`} onClick={() => onChange(c)}>{c}</button>
      ))}
    </div>
  );
}

function BannerShape({ shape }) {
  if (shape === 'wave') return <svg className="banner-shape" viewBox="0 0 200 200" preserveAspectRatio="none"><path d="M0,120 C50,60 90,180 140,110 C170,65 190,90 200,70 L200,200 L0,200 Z" fill="rgba(255,255,255,0.14)" /><path d="M20,150 C70,90 110,190 160,130 C185,95 195,110 200,95 L200,200 L0,200 Z" fill="rgba(255,255,255,0.08)" /></svg>;
  if (shape === 'blob') return <svg className="banner-shape" viewBox="0 0 200 200"><path d="M132 24c34 12 55 47 50 84-5 38-40 68-80 66-40-2-73-36-72-76 1-40 34-77 74-78 9 0 19 1 28 4z" fill="rgba(255,255,255,0.14)" /></svg>;
  return <div className="banner-shape banner-shape-grid" />;
}

function BannerCarousel() {
  const [i, setI] = React.useState(0);
  const railRef = React.useRef(null);
  const userTouch = React.useRef(false);
  const goTo = React.useCallback((idx, smooth) => {
    const rail = railRef.current;
    if (!rail) return;
    rail.scrollTo({ left: idx * rail.clientWidth, behavior: smooth === false ? 'auto' : 'smooth' });
  }, []);
  React.useEffect(() => {
    const t = setInterval(() => {
      if (userTouch.current) return;
      const rail = railRef.current;
      if (!rail) return;
      const next = (Math.round(rail.scrollLeft / rail.clientWidth) + 1) % BANNERS.length;
      goTo(next);
    }, 5000);
    return () => clearInterval(t);
  }, [goTo]);
  const onScroll = () => {
    const rail = railRef.current;
    if (!rail) return;
    const idx = Math.round(rail.scrollLeft / rail.clientWidth);
    setI(v => (v === idx ? v : idx));
  };
  const hold = () => { userTouch.current = true; };
  const release = () => { setTimeout(() => { userTouch.current = false; }, 3000); };
  const drag = React.useRef(null);
  const onPointerDown = e => {
    hold();
    if (e.pointerType === 'touch') return;
    drag.current = { x: e.clientX, left: railRef.current.scrollLeft };
    railRef.current.style.scrollSnapType = 'none';
  };
  const onPointerMove = e => {
    if (!drag.current) return;
    railRef.current.scrollLeft = drag.current.left - (e.clientX - drag.current.x);
  };
  const onPointerUp = e => {
    release();
    if (!drag.current) return;
    const rail = railRef.current;
    const moved = e.clientX - drag.current.x;
    drag.current = null;
    rail.style.scrollSnapType = '';
    const base = Math.round(rail.scrollLeft / rail.clientWidth);
    const idx = Math.abs(moved) > 40 ? Math.min(BANNERS.length - 1, Math.max(0, base)) : base;
    goTo(idx);
  };
  return (
    <div className="banner-carousel">
      <div className="banner-rail" ref={railRef} onScroll={onScroll}
        onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} onPointerLeave={onPointerUp} onPointerCancel={onPointerUp}
        onTouchStart={hold} onTouchEnd={release} onWheel={hold}>
        {BANNERS.map(b => (
          <div className={`banner banner-${b.tone}`} key={b.title}>
            <BannerShape shape={b.shape} />
            <div className="banner-content">
              <span className="banner-eyebrow">{b.eyebrow}</span>
              <p className="banner-title">{b.title}</p>
              <p className="banner-sub">{b.sub}</p>
            </div>
          </div>
        ))}
      </div>
      <div className="banner-dots">
        {BANNERS.map((_, idx) => <span key={idx} className={`dot ${idx === i ? 'dot-active' : ''}`} onClick={() => { hold(); goTo(idx); release(); }} />)}
      </div>
    </div>
  );
}

function AdRewardsScreen({ banner, onOpenReward, onBack }) {
  const list = REWARDS.filter(r => banner.rewardIds.includes(r.id));
  return (
    <div className="screen-body">
      <button className="ad-back" onClick={onBack}><Icon name="arrow-left" size={19} color="var(--fg-primary)" /></button>
      <div>
        <p className="section-title">Featured in this ad</p>
        <h2 className="ad-list-title">{banner.title}</h2>
      </div>
      <div className="brand-grid">
        {list.map(r => (
          <div key={r.id} className="brand-item" onClick={() => onOpenReward(r)}>
            <BrandLogo brand={r} />
            <span className="brand-name">{r.title}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function BrandLogo({ brand, size }) {
  if (brand.logo) return <div className="brand-logo brand-logo-img" style={{ width: size, height: size }}><img src={brand.logo} alt={brand.title} /></div>;
  return <div className="brand-logo" style={{ background: brand.bg, width: size, height: size, fontSize: size ? size * 0.22 : 14 }}>{brand.initials}</div>;
}

function BalancePill() {
  return (
    <div className="balance-pill">
      <span className="coin"><Icon name="sparkle" size={13} weight="fill" color="var(--neutral-950)" /></span>
      {USER.points.toLocaleString()}
    </div>
  );
}

function WalletHomeScreen({ onOpenReward, align }) {
  const [cat, setCat] = React.useState('All');
  const [q, setQ] = React.useState('');
  const needle = q.trim().toLowerCase();
  const base = cat === 'All' ? REWARDS : REWARDS.filter(r => r.cat === cat);
  const filtered = needle ? base.filter(r => r.title.toLowerCase().includes(needle)) : base;
  const groups = cat === 'All'
    ? CATEGORIES.slice(1).map(c => ({ cat: c, items: filtered.filter(r => r.cat === c) })).filter(g => g.items.length)
    : [{ cat, items: filtered }];
  return (
    <div className="screen-body">
      <div className="rewards-header">
        <h1 className="rewards-title">Rewards</h1>
        <BalancePill />
      </div>
      <div className="rewards-search">
        <Icon name="magnifying-glass" size={18} color="var(--fg-muted)" />
        <input className="rewards-search-input" placeholder="Search brands" value={q} onChange={e => setQ(e.target.value)} />
      </div>
      <BannerCarousel />
      <CategoryPills active={cat} onChange={setCat} />
      {needle && groups.length === 0 && <p className="rewards-empty">No brands match “{q}”.</p>}
      {groups.map(g => (
        <div key={g.cat} className="catalog-section">
          <p className="section-title">{g.cat}</p>
          <div className={`brand-grid ${align === 'left' ? 'align-left' : ''}`}>
            {g.items.map(r => (
              <div key={r.id} className="brand-item" onClick={() => onOpenReward(r)}>
                <BrandLogo brand={r} />
                <span className="brand-name">{r.title}</span>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function MoneyCard({ value, pct, active, onClick }) {
  const r = 22, c = 2 * Math.PI * r;
  const off = c - Math.min(1, pct) * c;
  return (
    <button className={`money-card ${active ? 'money-card-active' : ''}`} onClick={onClick}>
      <svg width="54" height="54" viewBox="0 0 54 54" className="money-ring">
        <circle cx="27" cy="27" r={r} fill="none" stroke="var(--border-default)" strokeWidth="3" />
        <circle cx="27" cy="27" r={r} fill="none" stroke={active ? 'var(--color-primary)' : 'var(--color-primary)'} strokeWidth="3" className="money-ring-active-stroke"
          strokeDasharray={c} strokeDashoffset={off} strokeLinecap="round" transform="rotate(-90 27 27)" />
        <text x="27" y="31" textAnchor="middle" className="money-ring-label">${value}</text>
      </svg>
      <span className="money-card-pct">{(value * PTS_PER_DOLLAR).toLocaleString()} pts</span>
    </button>
  );
}

const CAT_DESC = {
  Food: 'brand serving up quick, craveable meals — a solid pick for refueling between shifts.',
  Retail: 'go-to spot for everyday essentials and gear, from basics to statement pieces.',
  Auto: 'keeps you road-ready with reliable parts, service, and fuel for the daily grind.',
  Tech: 'your source for gadgets, gear, and everything that keeps you plugged in.',
  Hotel: 'a place to rest up and recharge, whether it\'s a quick stay or a proper getaway.',
};

function BrandInfoCard({ reward }) {
  return (
    <div className="brand-info-card">
      <BrandLogo brand={reward} size={40} />
      <div>
        <p className="brand-info-title">About {reward.title}</p>
        <p className="brand-info-body">{reward.title} is a {reward.cat.toLowerCase()} {CAT_DESC[reward.cat] || 'brand our Pryzers redeem often.'}</p>
      </div>
    </div>
  );
}

function PinConfirmSheet({ visible, pinned, reward, amount, onPickAmount, onConfirm, onClose }) {
  if (!visible) return null;
  return (
    <div className={`sheet-backdrop ${visible ? 'sheet-open' : ''}`} onClick={onClose}>
      <div className="sheet-panel" onClick={e => e.stopPropagation()}>
        <div className="sheet-handle" />
        <div className="sheet-icon"><Icon name="push-pin" size={22} weight="fill" color="var(--color-primary)" /></div>
        <p className="sheet-title">{pinned ? 'Unpin this reward?' : 'Pin this reward?'}</p>
        <p className="sheet-body">{pinned ? `Remove ${reward ? reward.title : ''} from your pinned list.` : `Pin ${reward ? reward.title : ''} to your home screen at this amount, so you always know what you're saving for.`}</p>
        {!pinned && (
          <div className="sheet-amt-row">
            {AMOUNT_PRESETS.map(v => (
              <button key={v} className={`sheet-amt-chip ${amount === v ? 'is-active' : ''}`} onClick={() => onPickAmount(v)}>${v}</button>
            ))}
          </div>
        )}
        <div className="sheet-actions">
          <Button label="Cancel" variant="outline" style={{ borderColor: 'var(--border-default)' }} onPress={onClose} />
          <Button label={pinned ? 'Unpin' : `Pin at $${amount}`} variant="primary" onPress={onConfirm} />
        </div>
      </div>
    </div>
  );
}

const CAT_TAG = {
  Food: { bg: 'rgba(255,138,61,.16)', fg: '#FFB27A', bgLight: 'rgba(230,110,20,.12)', fgLight: '#B45309' },
  Retail: { bg: 'rgba(154,140,255,.16)', fg: '#BCB0FF', bgLight: 'rgba(107,90,255,.12)', fgLight: '#5B3FD6' },
  Auto: { bg: 'rgba(255,255,255,.1)', fg: '#D8D8DC', bgLight: 'rgba(0,0,0,.06)', fgLight: '#4B4B50' },
  Tech: { bg: 'rgba(90,209,255,.16)', fg: '#8FDEFF', bgLight: 'rgba(10,140,190,.12)', fgLight: '#0A6E93' },
  Hotel: { bg: 'rgba(124,255,178,.16)', fg: '#9CFFC2', bgLight: 'rgba(20,140,80,.12)', fgLight: '#177245' },
};

function RewardDetailScreen({ reward, pinned, onTogglePin, onRedeem, onBack }) {
  const [amount, setAmount] = React.useState(10);
  const [focused, setFocused] = React.useState(false);
  const [sheetOpen, setSheetOpen] = React.useState(false);
  const scrollRef = React.useRef(null);
  const chosen = amount;
  const cost = chosen * PTS_PER_DOLLAR;
  const afford = USER.points >= cost && chosen > 0;
  const remaining = Math.max(0, cost - USER.points);
  const shiftsAway = remaining === 0 ? 0 : Math.ceil(remaining / POINTS_PER_SHIFT);

  function handleFocus(e) {
    setFocused(true);
    const el = e.target, container = scrollRef.current;
    if (!container) return;
    requestAnimationFrame(() => {
      const delta = el.getBoundingClientRect().top - container.getBoundingClientRect().top - 90;
      container.scrollTop += delta;
    });
  }

  return (
    <div className="detail-screen">
      <div className="detail-scroll" ref={scrollRef}>
        <div className="detail-hero" style={{ background: `radial-gradient(120% 100% at 50% -10%, ${reward.bg} 0%, ${reward.bg}55 38%, var(--bg-app) 78%)` }} data-hero-theme="dark-tint">
          <button className="detail-back" onClick={onBack}><Icon name="arrow-left" size={20} color="var(--hero-fg,#fff)" /></button>
          <div className="detail-hero-actions">
            <BalancePill />
            <button className={`detail-pin ${pinned ? 'detail-pin-active' : ''}`} onClick={() => setSheetOpen(true)}>
              <Icon name="push-pin" size={19} weight={pinned ? 'fill' : 'regular'} color={pinned ? 'var(--color-primary)' : 'var(--hero-fg,#fff)'} />
            </button>
          </div>
          <div className="detail-hero-logo-wrap">
            <BrandLogo brand={reward} size={84} />
          </div>
          <p className="detail-hero-title">{reward.title}</p>
          <span className="cat-tag" style={{ '--cat-bg': CAT_TAG[reward.cat].bg, '--cat-fg': CAT_TAG[reward.cat].fg, '--cat-bg-light': CAT_TAG[reward.cat].bgLight, '--cat-fg-light': CAT_TAG[reward.cat].fgLight }}>{reward.cat}</span>

          <div className="insight-strip">
            <div className="insight-chip">
              <Icon name="push-pin" size={14} weight="fill" color="var(--color-primary)" />
              <span>{(reward.pinned + (pinned ? 1 : 0)).toLocaleString()} redeemed</span>
            </div>
            <div className="insight-chip">
              <Icon name="coins" size={14} weight="fill" color="var(--pantone-sun-glare)" />
              <span>{remaining.toLocaleString()} pts to go</span>
            </div>
            <div className="insight-chip">
              <Icon name="briefcase" size={14} weight="fill" color="var(--violet-300)" />
              <span>{shiftsAway === 0 ? 'You can redeem now' : `${shiftsAway} more shift${shiftsAway > 1 ? 's' : ''} to unlock`}</span>
            </div>
          </div>
        </div>
        <div className="detail-body">
          <p className="section-title">Choose an amount</p>
          <div className="money-grid">
            {AMOUNT_PRESETS.map(v => (
              <MoneyCard key={v} value={v} pct={(USER.points) / (v * PTS_PER_DOLLAR)} active={amount === v}
                onClick={() => setAmount(v)} />
            ))}
          </div>

          <div className="brand-info-card">
            <div>
              <p className="brand-info-title">About {reward.title}</p>
              <p className="brand-info-body">{reward.title} is a {reward.cat.toLowerCase()} {CAT_DESC[reward.cat] || 'brand our Pryzers redeem often.'}</p>
            </div>
          </div>

          <div className="guide-card">
            <p className="section-title">How redemption works</p>
            <div className="guide-list">
              {GUIDE_STEPS.map((s, idx) => (
                <div key={s.step} className="guide-row">
                  <Icon name={['cursor-click', 'check-circle', 'envelope-simple-open'][idx] || 'check'} size={18} weight="regular" color="var(--fg-secondary)" />
                  <div>
                    <p className="guide-title">{s.title}</p>
                    <p className="guide-body">{s.body}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
          {focused && <div style={{ height: 220 }} />}
        </div>
      </div>
      <div className="detail-footer">
        <Button label={afford ? `Redeem for $${chosen}` : chosen > 0 ? 'Not enough points' : 'Enter an amount'} variant="primary" disabled={!afford} onPress={() => onRedeem(chosen, cost)} />
      </div>
      <PinConfirmSheet visible={sheetOpen} pinned={pinned} reward={reward} amount={amount} onPickAmount={setAmount} onClose={() => setSheetOpen(false)} onConfirm={() => { onTogglePin(amount); setSheetOpen(false); }} />
    </div>
  );
}

function RedeemConfirmSheet({ reward, amount, cost, visible, onConfirm, onClose }) {
  if (!reward) return null;
  return (
    <div className={`sheet-backdrop ${visible ? 'sheet-open' : ''}`} onClick={onClose}>
      <div className="sheet-panel" onClick={e => e.stopPropagation()}>
        <div className="sheet-handle" />
        <div className="sheet-icon"><Icon name="receipt" size={22} weight="regular" color="var(--fg-primary)" /></div>
        <p className="sheet-title">Confirm redemption</p>
        <p className="sheet-body">You're about to redeem a <strong>${amount} {reward.title}</strong> reward for <strong>{cost.toLocaleString()} points</strong>. This can't be undone.</p>
        <div className="sheet-actions">
          <Button label="Cancel" variant="outline" style={{ borderColor: 'var(--border-default)' }} onPress={onClose} />
          <Button label="Confirm" variant="primary" onPress={onConfirm} />
        </div>
      </div>
    </div>
  );
}

function Sprinkles() {
  const colors = ['#7CFFB2','#5AD1FF','#B98CFF','#fff','#FFD84D','var(--color-primary)'];
  const pieces = React.useMemo(() => Array.from({ length: 140 }, (_, i) => ({
    left: Math.random() * 100, delay: Math.random() * 0.5, dur: 1.6 + Math.random() * 2,
    color: colors[i % colors.length], rot: Math.random() * 360, size: 6 + Math.random() * 10,
    drift: (Math.random() - 0.5) * 200, shape: i % 3 === 0 ? '50%' : '2px',
  })), []);
  return (
    <div className="sprinkle-wrap">
      {pieces.map((p, i) => (
        <span key={i} className="sprinkle" style={{ left: `${p.left}%`, animationDelay: `${p.delay}s`, animationDuration: `${p.dur}s`, background: p.color, width: p.size, height: p.size * (p.shape === '50%' ? 1 : 0.45), borderRadius: p.shape, transform: `rotate(${p.rot}deg)`, '--drift': `${p.drift}px` }} />
      ))}
    </div>
  );
}

function RedeemSuccessSheet({ visible, reward, amount, onDone }) {
  React.useEffect(() => {
    const audio = new Audio('uploads/sound-effects-library-cash-register-sound.mp3');
    audio.volume = 0.7;
    audio.play().catch(() => {});
    const t = setTimeout(onDone, 4200);
    return () => { clearTimeout(t); audio.pause(); };
  }, []);
  if (!reward) return null;
  return (
    <div className={`success-overlay ${visible ? 'success-open' : ''}`} onClick={onDone}>
      <button className="success-close" onClick={onDone}><Icon name="x" size={18} weight="bold" color="#fff" /></button>
      <div className="success-glow" />
      <BurstRays />
      <div className="success-card" onClick={e => e.stopPropagation()}>
        <Sprinkles />
        <span className="success-stamp">CASHED OUT</span>
        <div className="success-logo-spacer" />
        <BrandLogo brand={reward} size={64} />
        <span className="success-amount">${amount}</span>
        <span className="success-won">STRAIGHT TO YOUR WALLET</span>
      </div>
      <p className="success-headline">Let's go! 🎉</p>
      <p className="success-sub">Your {reward.title} card just landed — code's in your email.</p>
      <div className="success-timer-track"><div className="success-timer-fill" /></div>
    </div>
  );
}

function BurstRays() {
  const rays = React.useMemo(() => Array.from({ length: 16 }, (_, i) => i * (360 / 16)), []);
  return (
    <svg className="burst-rays" viewBox="0 0 300 300">
      {rays.map((deg, i) => (
        <line key={i} x1="150" y1="150" x2={150 + 140 * Math.cos(deg * Math.PI / 180)} y2={150 + 140 * Math.sin(deg * Math.PI / 180)}
          stroke={i % 2 === 0 ? 'var(--color-primary)' : 'var(--lime-500)'} strokeWidth="4" strokeLinecap="round" opacity="0.5" />
      ))}
    </svg>
  );
}

function ComingSoonScreen({ label, emoji }) {
  return (
    <div className="placeholder">
      <div className="big">{emoji}</div>
      <p className="section-title" style={{fontSize:15,textTransform:'none',letterSpacing:0,color:'var(--fg-primary)',fontWeight:700}}>{label}</p>
      <p style={{fontSize:13}}>This flow is coming in a later phase.</p>
    </div>
  );
}

window.PryzeScreens = { WalletHomeScreen, AdRewardsScreen, RewardDetailScreen, RedeemConfirmSheet, RedeemSuccessSheet, ComingSoonScreen };
