// CHUCO — Iridescent Glass implementation, with Tweaks support.
// Pairs with prism-pages.jsx.

const { PLANS, CONNECTIONS, FEATURES, CATEGORIES, CHANNELS, COUNTRIES, FAQ } = window.IPTV_DATA;

// ───────────────────────────────────────────────────────────────────────────
// PALETTES — curated iridescent gradients (stops only — glows derived).
// ───────────────────────────────────────────────────────────────────────────
const PALETTES = {
  aurora:  ['#63fff0', '#22d3ee', '#2dd4bf', '#a7f3d0'],
  sunset:  ['#ffb547', '#ff7a8a', '#d44dff', '#7c4dff'],
  ocean:   ['#5d8bff', '#3ddfff', '#7df9c5', '#92ffe7'],
  chrome:  ['#e6e6f0', '#9c9cb5', '#c0c0d0', '#f5f5ff'],
};

const BG_TONES = {
  navy:     '#070912',
  obsidian: '#050507',
  violet:   '#0a0617',
};

const COLORS = {
  panel: 'rgba(255,255,255,0.04)',
  panelHi: 'rgba(255,255,255,0.07)',
  border: 'rgba(255,255,255,0.08)',
  borderHot: 'rgba(255,255,255,0.18)',
  fg: '#f3f4ff',
  fgDim: 'rgba(243,244,255,0.62)',
  fgGhost: 'rgba(243,244,255,0.36)',
};

const FONT_DISPLAY = "'Space Grotesk', system-ui, sans-serif";
const FONT_BODY = "'Inter', system-ui, sans-serif";
const FONT_MONO = "'JetBrains Mono', ui-monospace, monospace";

// hex -> rgba with alpha
function rgba(hex, a) {
  const h = hex.replace('#', '');
  const n = h.length === 3 ? h.split('').map(c => c + c).join('') : h;
  const r = parseInt(n.slice(0, 2), 16);
  const g = parseInt(n.slice(2, 4), 16);
  const b = parseInt(n.slice(4, 6), 16);
  return `rgba(${r},${g},${b},${a})`;
}

function gradFrom(stops) {
  return `linear-gradient(110deg, ${stops[0]} 0%, ${stops[1]} 32%, ${stops[2]} 64%, ${stops[3]} 100%)`;
}
function gradSoft(stops) {
  return `linear-gradient(110deg, ${rgba(stops[0],0.6)}, ${rgba(stops[1],0.6)}, ${rgba(stops[2],0.6)}, ${rgba(stops[3],0.6)})`;
}

// ───────────────────────────────────────────────────────────────────────────
// Tweaks
// ───────────────────────────────────────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "paletteStops": ["#63fff0", "#22d3ee", "#2dd4bf", "#a7f3d0"],
  "bgTone": "violet",
  "showHeroPanel": true,
  "showGrain": true,
  "headlineText": "Television, refracted"
}/*EDITMODE-END*/;

// ───────────────────────────────────────────────────────────────────────────
// Shared UI primitives
// ───────────────────────────────────────────────────────────────────────────
function GlsCard({ children, style = {}, hi = false, onClick }) {
  return (
    <div onClick={onClick} style={{
      background: hi ? COLORS.panelHi : COLORS.panel,
      backdropFilter: 'blur(20px) saturate(140%)', WebkitBackdropFilter: 'blur(20px) saturate(140%)',
      border: `1px solid ${COLORS.border}`, borderRadius: 20,
      ...style,
    }}>{children}</div>
  );
}

function GlsLogo({ gradient }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{
        width: 34, height: 34, borderRadius: 10, background: gradient,
        position: 'relative', display: 'grid', placeItems: 'center',
        boxShadow: '0 6px 24px rgba(0,0,0,0.4), 0 0 24px rgba(255,255,255,0.15)',
      }}>
        <div style={{
          width: 14, height: 14, borderRadius: '50%', background: 'rgba(0,0,0,0.55)',
          border: '2px solid rgba(255,255,255,0.95)',
        }} />
      </div>
      <div style={{ fontFamily: FONT_DISPLAY, fontWeight: 700, fontSize: 19, letterSpacing: '-0.02em' }}>
        Prism<span style={{
          background: gradient, WebkitBackgroundClip: 'text',
          WebkitTextFillColor: 'transparent', backgroundClip: 'text',
        }}>Stream</span>
      </div>
    </div>
  );
}

function GlsButton({ children, variant = 'primary', size = 'md', gradient, onClick, style = {} }) {
  const pad = size === 'lg' ? '15px 26px' : size === 'sm' ? '8px 14px' : '11px 20px';
  const fz = size === 'lg' ? 15 : size === 'sm' ? 12 : 14;
  if (variant === 'primary') {
    return (
      <button onClick={onClick} style={{
        background: gradient, color: '#0a0c18', border: 'none',
        padding: pad, borderRadius: 999, fontSize: fz, fontFamily: FONT_BODY,
        fontWeight: 700, cursor: 'pointer',
        boxShadow: '0 12px 32px rgba(0,0,0,0.35), 0 0 24px rgba(255,255,255,0.08)',
        transition: 'transform .12s, box-shadow .12s',
        ...style,
      }} onMouseDown={e => e.currentTarget.style.transform = 'scale(0.97)'}
         onMouseUp={e => e.currentTarget.style.transform = ''}
         onMouseLeave={e => e.currentTarget.style.transform = ''}>
        {children}
      </button>
    );
  }
  return (
    <button onClick={onClick} style={{
      background: COLORS.panel, backdropFilter: 'blur(20px)',
      color: COLORS.fg, border: `1px solid ${COLORS.borderHot}`,
      padding: pad, borderRadius: 999, fontSize: fz, fontWeight: 500, cursor: 'pointer',
      fontFamily: FONT_BODY,
      ...style,
    }}>{children}</button>
  );
}

// ───────────────────────────────────────────────────────────────────────────
// Top navigation (sticky w/ scroll bg state)
// ───────────────────────────────────────────────────────────────────────────
function TopBar({ page, setPage, gradient, scrollRef }) {
  const [solid, setSolid] = React.useState(false);
  React.useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const onScroll = () => setSolid(el.scrollTop > 8);
    el.addEventListener('scroll', onScroll);
    return () => el.removeEventListener('scroll', onScroll);
  }, [scrollRef]);

  const navItems = [
    { id: 'home',     label: 'Home' },
    { id: 'plans',    label: 'Plans' },
    { id: 'channels', label: 'Channels' },
    { id: 'devices',  label: 'Devices' },
  ];
  return (
    <div style={{
      padding: '16px 40px', display: 'flex', alignItems: 'center', gap: 32,
      position: 'sticky', top: 0, zIndex: 30,
      background: solid ? 'rgba(7,9,18,0.78)' : 'rgba(7,9,18,0.2)',
      backdropFilter: 'blur(20px) saturate(140%)', WebkitBackdropFilter: 'blur(20px) saturate(140%)',
      borderBottom: `1px solid ${solid ? COLORS.border : 'transparent'}`,
      transition: 'background .2s, border-color .2s',
    }}>
      <div onClick={() => setPage('home')} style={{ cursor: 'pointer' }}>
        <GlsLogo gradient={gradient} />
      </div>
      <div style={{ display: 'flex', gap: 4, marginLeft: 8 }}>
        {navItems.map(n => (
          <button key={n.id} onClick={() => setPage(n.id)} style={{
            background: page === n.id ? COLORS.panelHi : 'transparent',
            color: page === n.id ? COLORS.fg : COLORS.fgDim,
            border: 'none', padding: '8px 14px', fontFamily: FONT_BODY, fontSize: 13,
            fontWeight: 500, cursor: 'pointer', borderRadius: 999,
          }}>{n.label}</button>
        ))}
      </div>
      <div style={{ marginLeft: 'auto', display: 'flex', gap: 12, alignItems: 'center' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: COLORS.fgDim }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#a0ffd6', boxShadow: '0 0 8px #a0ffd6' }} />
          All systems nominal
        </div>
        <GlsButton variant="ghost" size="sm">Sign in</GlsButton>
        <GlsButton variant="primary" size="sm" gradient={gradient} onClick={() => setPage('plans')}>Get started →</GlsButton>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────────────────
// Background ambient layer
// ───────────────────────────────────────────────────────────────────────────
function AmbientBackground({ stops, showGrain }) {
  return (
    <>
      <div style={{
        position: 'fixed', top: -80, left: -120, width: 520, height: 520, borderRadius: '50%',
        background: `radial-gradient(circle, ${rgba(stops[0], 0.35)}, transparent 60%)`,
        filter: 'blur(70px)', pointerEvents: 'none', zIndex: 0,
      }} />
      <div style={{
        position: 'fixed', top: 240, right: -140, width: 560, height: 560, borderRadius: '50%',
        background: `radial-gradient(circle, ${rgba(stops[1], 0.28)}, transparent 60%)`,
        filter: 'blur(70px)', pointerEvents: 'none', zIndex: 0,
      }} />
      <div style={{
        position: 'fixed', bottom: -200, left: '38%', width: 520, height: 520, borderRadius: '50%',
        background: `radial-gradient(circle, ${rgba(stops[3], 0.25)}, transparent 60%)`,
        filter: 'blur(70px)', pointerEvents: 'none', zIndex: 0,
      }} />
      {showGrain && (
        <div style={{
          position: 'fixed', inset: 0, pointerEvents: 'none', zIndex: 1, opacity: 0.05,
          backgroundImage: 'url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'180\' height=\'180\'><filter id=\'n\'><feTurbulence type=\'fractalNoise\' baseFrequency=\'0.85\' numOctaves=\'2\'/></filter><rect width=\'100%25\' height=\'100%25\' filter=\'url(%23n)\' opacity=\'0.5\'/></svg>")',
        }} />
      )}
    </>
  );
}

// ───────────────────────────────────────────────────────────────────────────
// Footer
// ───────────────────────────────────────────────────────────────────────────
function Footer({ gradient, setPage }) {
  return (
    <footer style={{
      marginTop: 100, padding: '56px 56px 36px',
      borderTop: `1px solid ${COLORS.border}`,
      background: 'rgba(7,9,18,0.5)', backdropFilter: 'blur(16px)',
      position: 'relative', zIndex: 2,
    }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr 1fr', gap: 36 }}>
        <div>
          <GlsLogo gradient={gradient} />
          <p style={{ color: COLORS.fgDim, fontSize: 13, lineHeight: 1.6, marginTop: 16, maxWidth: 280 }}>
            Reseller-grade IPTV on a global anti-buffer CDN. 22,000+ channels, 80,000+ on demand,
            instant activation, cancel any time.
          </p>
          <div style={{ display: 'flex', gap: 8, marginTop: 20 }}>
            {['𝕏', 'in', '✱', 'tg'].map(s => (
              <div key={s} style={{
                width: 34, height: 34, borderRadius: '50%',
                border: `1px solid ${COLORS.border}`, background: COLORS.panel,
                display: 'grid', placeItems: 'center', color: COLORS.fgDim, cursor: 'pointer',
                fontSize: 14, fontWeight: 600,
              }}>{s}</div>
            ))}
          </div>
        </div>
        {[
          { h: 'Product', items: [['Plans', 'plans'], ['Channels', 'channels'], ['Devices', 'devices'], ['Free trial', 'plans']] },
          { h: 'Support', items: [['Setup guides', null], ['Status', null], ['Contact', null], ['Refund policy', null]] },
          { h: 'Company', items: [['Affiliate', null], ['Reseller panel', null], ['Press kit', null], ['Privacy', null]] },
          { h: 'Reach',   items: [['Telegram chat', null], ['Discord', null], ['Email', null], ['Live agent', null]] },
        ].map(col => (
          <div key={col.h}>
            <div style={{ fontSize: 11, letterSpacing: '0.18em', color: COLORS.fgGhost, marginBottom: 14 }}>{col.h.toUpperCase()}</div>
            {col.items.map(([label, page]) => (
              <div key={label} onClick={() => page && setPage(page)} style={{
                fontSize: 13, color: COLORS.fgDim, padding: '5px 0', cursor: page ? 'pointer' : 'default',
              }}>{label}</div>
            ))}
          </div>
        ))}
      </div>
      <div style={{
        marginTop: 40, paddingTop: 22, borderTop: `1px solid ${COLORS.border}`,
        display: 'flex', justifyContent: 'space-between', fontSize: 12, color: COLORS.fgGhost,
      }}>
        <span>© 2026 CHUCO TV. A reseller of premium IPTV lines.</span>
        <span style={{ fontFamily: FONT_MONO }}>cdn-eu-west-3 · 99.93% uptime · v3.4.1</span>
      </div>
    </footer>
  );
}

// ───────────────────────────────────────────────────────────────────────────
// Main App
// ───────────────────────────────────────────────────────────────────────────
function PrismApp() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const stops = Array.isArray(tweaks.paletteStops) && tweaks.paletteStops.length === 4
    ? tweaks.paletteStops : PALETTES.aurora;
  const bg = BG_TONES[tweaks.bgTone] || BG_TONES.navy;
  const gradient = gradFrom(stops);
  const gradientSoft = gradSoft(stops);

  const [page, setPage] = React.useState('home');
  const [cart, setCart] = React.useState({ planId: '6m', connId: 2 });
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTo({ top: 0, behavior: 'instant' });
  }, [page]);

  const plan = PLANS.find(p => p.id === cart.planId);
  const conn = CONNECTIONS.find(c => c.id === cart.connId);
  const total = (plan ? plan.price : 0) + (conn ? conn.add : 0);

  const ctx = { gradient, gradientSoft, stops, headlineText: tweaks.headlineText, showHeroPanel: tweaks.showHeroPanel };

  return (
    <div ref={scrollRef} style={{
      width: '100%', height: '100vh', overflow: 'auto',
      background: bg, color: COLORS.fg, fontFamily: FONT_BODY,
      position: 'relative',
    }}>
      <AmbientBackground stops={stops} showGrain={tweaks.showGrain} />
      <TopBar page={page} setPage={setPage} gradient={gradient} scrollRef={scrollRef} />
      <div style={{ position: 'relative', zIndex: 2 }}>
        {page === 'home'     && <PrismHome     ctx={ctx} setPage={setPage} />}
        {page === 'plans'    && <PrismPlans    ctx={ctx} cart={cart} setCart={setCart} setPage={setPage} />}
        {page === 'channels' && <PrismChannels ctx={ctx} />}
        {page === 'devices'  && <PrismDevices  ctx={ctx} setPage={setPage} />}
        {page === 'checkout' && <PrismCheckout ctx={ctx} plan={plan} conn={conn} total={total} setPage={setPage} />}
        {page === 'success'  && <PrismSuccess  ctx={ctx} setPage={setPage} />}
      </div>
      <Footer gradient={gradient} setPage={setPage} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Palette">
          <TweakColor label="Iridescent palette"
            value={stops}
            options={[PALETTES.aurora, PALETTES.sunset, PALETTES.ocean, PALETTES.chrome]}
            onChange={v => setTweak('paletteStops', v)} />
          <TweakRadio label="Background"
            value={tweaks.bgTone}
            options={[{value: 'navy', label: 'Navy'}, {value: 'obsidian', label: 'Black'}, {value: 'violet', label: 'Violet'}]}
            onChange={v => setTweak('bgTone', v)} />
        </TweakSection>
        <TweakSection label="Layout">
          <TweakToggle label="Hero now-playing panel" value={tweaks.showHeroPanel} onChange={v => setTweak('showHeroPanel', v)} />
          <TweakToggle label="Film grain" value={tweaks.showGrain} onChange={v => setTweak('showGrain', v)} />
        </TweakSection>
        <TweakSection label="Copy">
          <TweakText label="Hero headline" value={tweaks.headlineText} onChange={v => setTweak('headlineText', v)} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

// Expose shared pieces to prism-pages.jsx (separate script scope).
Object.assign(window, {
  PRISM: { COLORS, FONT_DISPLAY, FONT_BODY, FONT_MONO, GlsCard, GlsButton, GlsLogo, gradFrom, gradSoft, rgba },
  PrismApp,
});
