/* ===========================================================================
   iRaven App Store Studio — canvas: backgrounds, device frames, templates.
   Everything here renders at REAL export pixels (panel = device.canvas.w/h),
   then the app scales the wrapper down with CSS transform for display.
   =========================================================================== */

const DISPLAY = "'Space Grotesk', system-ui, sans-serif";
const BODY = "'Inter', system-ui, sans-serif";

/* ---------- backgrounds ---------- */
function BackgroundLayer({ bg, dims }) {
  const fill = { position: 'absolute', inset: 0 };
  if (bg === 'pitch') {
    const stripe = Math.round(dims.w * 0.085);
    return (
      <div style={fill}>
        <div style={{ ...fill, background: 'linear-gradient(180deg,#0d1c12,#06100a)' }} />
        <div style={{ ...fill, background:
          `repeating-linear-gradient(180deg, rgba(255,255,255,0.045) 0 ${stripe}px, rgba(0,0,0,0) ${stripe}px ${stripe*2}px)` }} />
        <div style={{ ...fill, background:
          'radial-gradient(120% 80% at 50% 0%, rgba(31,157,85,0.30), transparent 55%)' }} />
        <div style={{ ...fill, background:
          'radial-gradient(120% 90% at 50% 100%, rgba(0,0,0,0.55), transparent 60%)' }} />
      </div>
    );
  }
  const layers = window.BG_DEFS[bg] || window.BG_DEFS.stadium;
  return (
    <div style={fill}>
      {layers.map((b, i) => <div key={i} style={{ ...fill, background: b }} />)}
    </div>
  );
}

/* faint vignette + grain shared on top of every bg for depth */
function Atmosphere({ dims }) {
  return (
    <div style={{ position: 'absolute', inset: 0,
      background: 'radial-gradient(130% 100% at 50% 50%, transparent 58%, rgba(0,0,0,0.45) 100%)' }} />
  );
}

/* ---------- device frame ---------- */
function DeviceFrame({ device, width, image, label, transparentScreen, emptyScreen }) {
  if (window.useMediaWarm) window.useMediaWarm([image]);
  const resolved = window.mediaSrcOf ? window.mediaSrcOf(image) : (typeof image === 'string' ? resolveAsset(image) : null);
  const f = device.frame;
  const bezel = width * f.bezelRatio;
  const radius = width * f.radiusRatio;
  const screenW = width - bezel * 2;
  const screenH = screenW / device.screenAspect;
  const height = screenH + bezel * 2;
  const innerR = radius - bezel;

  const screen = emptyScreen
    ? <div style={{ width: '100%', height: '100%', background: '#000' }} />
    : transparentScreen
    ? <div style={{ width: '100%', height: '100%' }} />
    : resolved
    ? <img src={resolved} crossOrigin="anonymous" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
    : (
      <div style={{ width: '100%', height: '100%', position: 'relative',
        background: `repeating-linear-gradient(135deg, #0e1830 0 ${width*0.03}px, #0a1326 ${width*0.03}px ${width*0.06}px)` }}>
        <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexDirection: 'column', gap: width*0.02 }}>
          <div style={{ width: width*0.16, height: width*0.16, borderRadius: width*0.04,
            border: `${Math.max(2,width*0.006)}px dashed rgba(255,255,255,0.28)` }} />
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: width*0.045,
            letterSpacing: '0.08em', color: 'rgba(255,255,255,0.42)', textTransform: 'uppercase' }}>
            drop screenshot
          </div>
        </div>
      </div>
    );

  return (
    <div style={{ position: 'relative', width, height,
      borderRadius: radius, background: 'linear-gradient(155deg,#23262e,#0c0d12)',
      padding: bezel, boxSizing: 'border-box',
      boxShadow: `0 ${width*0.05}px ${width*0.12}px rgba(0,0,0,0.55), inset 0 0 ${width*0.01}px rgba(255,255,255,0.18)` }}>
      {f.watch ? (
        <>
          <div style={{ position: 'absolute', right: -width * 0.035, top: height * 0.22,
            width: width * 0.05, height: height * 0.16, borderRadius: width * 0.02,
            background: 'linear-gradient(90deg,#2a2d35,#15161b)' }} />
          <div style={{ position: 'absolute', right: -width * 0.022, top: height * 0.46,
            width: width * 0.032, height: height * 0.20, borderRadius: width * 0.016,
            background: 'linear-gradient(90deg,#26292f,#121317)' }} />
        </>
      ) : null}
      <div style={{ position: 'relative', width: '100%', height: '100%', borderRadius: innerR, overflow: 'hidden',
        background: transparentScreen ? 'transparent' : '#000',
        boxShadow: transparentScreen ? 'none' : `inset 0 0 ${width*0.012}px rgba(0,0,0,0.9)` }}>
        {screen}
        {f.island && (
          <div style={{ position: 'absolute', top: screenH * 0.018, left: '50%', transform: 'translateX(-50%)',
            width: screenW * 0.34, height: screenW * 0.092, background: '#000', borderRadius: 999, zIndex: 3 }} />
        )}
      </div>
    </div>
  );
}

/* ---------- headline block ---------- */
function Headline({ slide, dims, accentColor, align = 'center', maxWidth = 0.86, baseRatio = 0.082 }) {
  const sz = (window.TITLE_SIZES.find(t => t.id === slide.titleSize) || { scale: 1 }).scale;
  const fs = dims.w * baseRatio * sz;
  const lines = (slide.headline || '').split('\n');
  return (
    <div style={{ maxWidth: dims.w * maxWidth, textAlign: align,
      display: 'flex', flexDirection: 'column', gap: dims.w * 0.018,
      alignItems: align === 'left' ? 'flex-start' : 'center' }}>
      <div style={{ width: dims.w * 0.07, height: dims.w * 0.008, borderRadius: 999, background: accentColor }} />
      <h1 style={{ margin: 0, fontFamily: DISPLAY, fontWeight: 700, color: '#fff',
        fontSize: fs, lineHeight: 1.02, letterSpacing: '-0.02em', textWrap: 'balance' }}>
        {lines.map((l, i) => <div key={i}>{l || '\u00A0'}</div>)}
      </h1>
      {slide.subtitle ? (
        <p style={{ margin: 0, fontFamily: BODY, fontWeight: 400, color: 'rgba(255,255,255,0.70)',
          fontSize: dims.w * 0.032, lineHeight: 1.35, maxWidth: dims.w * 0.74, textWrap: 'pretty' }}>
          {slide.subtitle}
        </p>
      ) : null}
    </div>
  );
}

function CalloutChip({ text, dims, accentColor, side }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: dims.w * 0.02,
      flexDirection: side === 'right' ? 'row-reverse' : 'row' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: dims.w * 0.018,
        padding: `${dims.w*0.018}px ${dims.w*0.028}px`, borderRadius: dims.w * 0.5,
        background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.14)',
        boxShadow: '0 8px 30px rgba(0,0,0,0.35)', whiteSpace: 'nowrap' }}>
        <span style={{ width: dims.w * 0.022, height: dims.w * 0.022, borderRadius: 999, background: accentColor,
          boxShadow: `0 0 ${dims.w*0.03}px ${accentColor}` }} />
        <span style={{ fontFamily: BODY, fontWeight: 600, color: '#fff', fontSize: dims.w * 0.03 }}>{text}</span>
      </div>
      <div style={{ width: dims.w * 0.06, height: 2, background: 'rgba(255,255,255,0.25)' }} />
    </div>
  );
}

/* ---------- the panel (export node) ---------- */
function Panel({ slide }) {
  if (window.useMediaWarm) window.useMediaWarm([slide.image, slide.image2]);
  const posterSrc = window.mediaSrcOf ? window.mediaSrcOf(slide.image) : resolveAsset(slide.image);
  const device = window.DEVICES[slide.device] || window.DEVICES.iphone;
  const dims = device.canvas;
  const accentColor = window.resolveAccent(slide.accent);
  /* finishing controls */
  const eff = {
    ds: (window.DEV_SIZES.find(d => d.id === slide.devSize) || { scale: 1 }).scale,
    tilt: slide.tilt || 0,
    glow: slide.glow === undefined ? 0.5 : slide.glow,
  };
  const glowLayer = (eff.glow > 0 && slide.template !== 'poster' && slide.template !== 'full-bleed') ? (
    <div style={{ position: 'absolute', left: '50%', top: '62%', transform: 'translate(-50%,-50%)',
      width: dims.w * 1.25, height: dims.w * 1.25, borderRadius: '50%',
      background: `radial-gradient(closest-side, ${accentColor}${eff.glow === 1 ? '59' : '30'}, transparent 70%)` }} />
  ) : null;
  const root = { position: 'relative', width: dims.w, height: dims.h, overflow: 'hidden', color: '#fff' };

  let content = null;

  if (slide.template === 'angled') {
    content = (
      <>
        <div style={{ position: 'absolute', top: dims.h * 0.075, left: dims.w * 0.085, right: dims.w * 0.085 }}>
          <Headline slide={slide} dims={dims} accentColor={accentColor} align="left" baseRatio={0.088} maxWidth={0.9} />
        </div>
        <div style={{ position: 'absolute', left: '50%', bottom: -dims.h * 0.06,
          transform: `translateX(-50%) rotate(${-8 + eff.tilt}deg)` }}>
          <div style={{ position: 'absolute', inset: '-12%', borderRadius: '50%',
            background: `radial-gradient(closest-side, ${accentColor}40, transparent 72%)` }} />
          <DeviceFrame device={device} width={dims.w * 0.86 * eff.ds} image={slide.image} />
        </div>
      </>
    );
  } else if (slide.template === 'split') {
    content = (
      <>
        <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: dims.h * 0.30,
          background: `linear-gradient(135deg, ${accentColor}2e, transparent 75%)`,
          borderBottom: `1px solid ${accentColor}40` }} />
        <div style={{ position: 'absolute', top: dims.h * 0.065, left: dims.w * 0.08, right: dims.w * 0.08 }}>
          <Headline slide={slide} dims={dims} accentColor={accentColor} align="left" baseRatio={0.082} maxWidth={0.92} />
        </div>
        <div style={{ position: 'absolute', left: '50%', top: dims.h * 0.345,
          transform: `translateX(-50%) rotate(${eff.tilt}deg)` }}>
          <DeviceFrame device={device} width={dims.w * 0.78 * eff.ds} image={slide.image} />
        </div>
      </>
    );
  } else if (slide.template === 'fan') {
    content = (
      <>
        <div style={{ position: 'absolute', top: dims.h * 0.055, left: 0, right: 0, display: 'flex', justifyContent: 'center' }}>
          <Headline slide={slide} dims={dims} accentColor={accentColor} align="center" baseRatio={0.07} />
        </div>
        <div style={{ position: 'absolute', left: dims.w * 0.30, top: dims.h * 0.36,
          transform: `rotate(${7 + eff.tilt}deg)` }}>
          <DeviceFrame device={device} width={dims.w * 0.62 * eff.ds} image={slide.image2} />
        </div>
        <div style={{ position: 'absolute', left: dims.w * 0.05, top: dims.h * 0.31,
          transform: `rotate(${-7 + eff.tilt}deg)` }}>
          <DeviceFrame device={device} width={dims.w * 0.62 * eff.ds} image={slide.image} />
        </div>
      </>
    );
  } else if (slide.template === 'callouts') {
    const items = (slide.callouts || '').split('\n').map(s => s.trim()).filter(Boolean).slice(0, 4);
    const left = items.filter((_, i) => i % 2 === 0);
    const right = items.filter((_, i) => i % 2 === 1);
    content = (
      <>
        <div style={{ position: 'absolute', top: dims.h * 0.07, left: 0, right: 0, display: 'flex', justifyContent: 'center' }}>
          <Headline slide={slide} dims={dims} accentColor={accentColor} align="center" baseRatio={0.07} />
        </div>
        <div style={{ position: 'absolute', left: '50%', top: '54%', transform: 'translate(-50%,-50%)' }}>
          <DeviceFrame device={device} width={dims.w * 0.6} image={slide.image} />
        </div>
        <div style={{ position: 'absolute', left: dims.w * 0.045, top: '42%', transform: 'translateY(-50%)',
          display: 'flex', flexDirection: 'column', gap: dims.w * 0.04 }}>
          {left.map((t, i) => <CalloutChip key={i} text={t} dims={dims} accentColor={accentColor} side="left" />)}
        </div>
        <div style={{ position: 'absolute', right: dims.w * 0.045, top: '60%', transform: 'translateY(-50%)',
          display: 'flex', flexDirection: 'column', gap: dims.w * 0.04, alignItems: 'flex-end' }}>
          {right.map((t, i) => <CalloutChip key={i} text={t} dims={dims} accentColor={accentColor} side="right" />)}
        </div>
      </>
    );
  } else if (slide.template === 'full-bleed') {
    content = (
      <>
        <div style={{ position: 'absolute', left: '50%', top: '53%', transform: 'translate(-50%,-50%)' }}>
          <DeviceFrame device={device} width={dims.w * 0.9} image={slide.image} />
        </div>
        <div style={{ position: 'absolute', inset: 0,
          background: 'linear-gradient(180deg, rgba(3,5,14,0.92) 0%, rgba(3,5,14,0.55) 22%, transparent 42%)' }} />
        <div style={{ position: 'absolute', top: dims.h * 0.07, left: 0, right: 0, display: 'flex', justifyContent: 'center' }}>
          <Headline slide={slide} dims={dims} accentColor={accentColor} align="center" baseRatio={0.078} />
        </div>
      </>
    );
  } else if (slide.template === 'big-stat') {
    content = (
      <>
        <div style={{ position: 'absolute', top: dims.h * 0.085, left: dims.w * 0.08, right: dims.w * 0.08 }}>
          <Headline slide={slide} dims={dims} accentColor={accentColor} align="left" baseRatio={0.12} maxWidth={0.96} />
        </div>
        <div style={{ position: 'absolute', left: '50%', bottom: -dims.h * 0.05, transform: 'translateX(-50%)' }}>
          <DeviceFrame device={device} width={dims.w * 0.7} image={slide.image} />
        </div>
      </>
    );
  } else if (slide.template === 'headline-bottom') {
    content = (
      <>
        <div style={{ position: 'absolute', left: '50%', top: -dims.h * 0.07, transform: 'translateX(-50%)' }}>
          <DeviceFrame device={device} width={dims.w * 0.76} image={slide.image} />
        </div>
        <div style={{ position: 'absolute', bottom: dims.h * 0.06, left: 0, right: 0, display: 'flex', justifyContent: 'center' }}>
          <Headline slide={slide} dims={dims} accentColor={accentColor} align="center" baseRatio={0.075} />
        </div>
      </>
    );
  } else if (slide.template === 'duo') {
    content = (
      <>
        <div style={{ position: 'absolute', top: dims.h * 0.055, left: 0, right: 0, display: 'flex', justifyContent: 'center' }}>
          <Headline slide={slide} dims={dims} accentColor={accentColor} align="center" baseRatio={0.068} />
        </div>
        <div style={{ position: 'absolute', left: dims.w * 0.015, top: dims.h * 0.37, transform: 'rotate(-6deg)' }}>
          <DeviceFrame device={device} width={dims.w * 0.56} image={slide.image} />
        </div>
        <div style={{ position: 'absolute', right: dims.w * 0.015, top: dims.h * 0.31, transform: 'rotate(5deg)' }}>
          <DeviceFrame device={device} width={dims.w * 0.56} image={slide.image2} />
        </div>
      </>
    );
  } else if (slide.template === 'companion') {
    const watchSpec = window.DEVICES.watch;
    const mainSpec = device.id === 'watch' ? window.DEVICES.iphone : device;
    content = (
      <>
        <div style={{ position: 'absolute', top: dims.h * 0.05, left: 0, right: 0, display: 'flex', justifyContent: 'center' }}>
          <Headline slide={slide} dims={dims} accentColor={accentColor} align="center" baseRatio={0.068} />
        </div>
        <div style={{ position: 'absolute', left: dims.w * 0.06, top: dims.h * 0.33, transform: 'rotate(-3deg)' }}>
          <DeviceFrame device={mainSpec} width={dims.w * 0.56} image={slide.image} />
        </div>
        <div style={{ position: 'absolute', right: dims.w * 0.05, top: dims.h * 0.50, transform: 'rotate(6deg)' }}>
          <DeviceFrame device={watchSpec} width={dims.w * 0.38} image={slide.image2} />
        </div>
      </>
    );
  } else if (slide.template === 'poster') {
    content = (
      <>
        {posterSrc ? (
          <img src={posterSrc} crossOrigin="anonymous" style={{ position: 'absolute', inset: 0,
            width: '100%', height: '100%', objectFit: 'cover' }} />
        ) : (
          <div style={{ position: 'absolute', inset: 0,
            background: `repeating-linear-gradient(135deg, #0e1830 0 ${dims.w*0.03}px, #0a1326 ${dims.w*0.03}px ${dims.w*0.06}px)` }}>
            <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: "'JetBrains Mono', monospace", fontSize: dims.w * 0.04, letterSpacing: '0.08em',
              color: 'rgba(255,255,255,0.42)', textTransform: 'uppercase' }}>drop screenshot</div>
          </div>
        )}
        <div style={{ position: 'absolute', inset: 0,
          background: 'linear-gradient(180deg, rgba(3,5,14,0.15) 38%, rgba(3,5,14,0.94) 80%)' }} />
        <div style={{ position: 'absolute', left: dims.w * 0.08, right: dims.w * 0.08, bottom: dims.h * 0.065 }}>
          <Headline slide={slide} dims={dims} accentColor={accentColor} align="left" baseRatio={0.085} maxWidth={0.9} />
        </div>
      </>
    );
  } else {
    // headline-top (default)
    content = (
      <>
        <div style={{ position: 'absolute', top: dims.h * 0.072, left: 0, right: 0, display: 'flex', justifyContent: 'center' }}>
          <Headline slide={slide} dims={dims} accentColor={accentColor} align="center" />
        </div>
        <div style={{ position: 'absolute', left: '50%', bottom: -dims.h * 0.07,
          transform: `translateX(-50%) rotate(${eff.tilt}deg)` }}>
          <DeviceFrame device={device} width={dims.w * 0.76 * eff.ds} image={slide.image} />
        </div>
      </>
    );
  }

  return (
    <div style={root}>
      <BackgroundLayer bg={slide.bg} dims={dims} />
      <Atmosphere dims={dims} />
      {glowLayer}
      {content}
    </div>
  );
}

Object.assign(window, { Panel, DeviceFrame, BackgroundLayer });
