// Image placeholder + Gemini prompt slot.
// Each marked region in the design becomes an <ImageSlot> with:
//  - a unique slot id (e.g. "hero-bg", "values-collab")
//  - a Gemini prompt string
//  - a suggested aspect ratio + crop hints
// Until a real image is dropped in (assets/slots/<id>.jpg), it renders as a
// labelled placeholder so the user can see exactly what goes where.

window.ImageSlot = function ImageSlot({
  id, prompt, ratio = 'landscape',
  caption = '', src = null,
  fill = true, dim = 0.4, accent = '#E63028',
}) {
  const [showPrompt, setShowPrompt] = React.useState(false);
  const [copied, setCopied] = React.useState(false);
  // Auto-probe assets/slots/<id>.{png,jpg,webp} so the user can just drop a file in.
  // We try png → jpg → webp in order; placeholder shows only if all fail.
  const candidates = src
    ? [src]
    : [`assets/img/${id}.jpg`, `assets/img/${id}.png`, `assets/img/${id}.jpeg`, `assets/img/${id}.webp`];
  const [probeIdx, setProbeIdx] = React.useState(0);
  const [probeOk, setProbeOk] = React.useState(false);
  const [probeDone, setProbeDone] = React.useState(false);
  React.useEffect(() => {
    let cancelled = false;
    setProbeIdx(0); setProbeOk(false); setProbeDone(false);
    const tryNext = (i) => {
      if (cancelled) return;
      if (i >= candidates.length) { setProbeDone(true); return; }
      const img = new Image();
      img.onload = () => { if (!cancelled) { setProbeIdx(i); setProbeOk(true); setProbeDone(true); } };
      img.onerror = () => tryNext(i + 1);
      img.src = candidates[i];
    };
    tryNext(0);
    return () => { cancelled = true; };
  }, [id, src]);

  // Real image found → render it.
  if (probeOk) {
    return (
      <div style={{
        position: fill ? 'absolute' : 'relative', inset: fill ? 0 : 'auto',
        width: '100%', height: '100%',
        backgroundImage: `url(${candidates[probeIdx]})`, backgroundSize: 'cover', backgroundPosition: 'center',
      }} />
    );
  }
  // Still probing — render nothing transparent (avoids placeholder flash).
  if (!probeDone) {
    return <div style={{ position: fill ? 'absolute' : 'relative', inset: fill ? 0 : 'auto', width: '100%', height: '100%' }} />;
  }

  const copyPrompt = (e) => {
    e.stopPropagation();
    try {
      navigator.clipboard.writeText(prompt);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch (err) {}
  };

  return (
    <div
      onClick={() => setShowPrompt(v => !v)}
      style={{
        position: fill ? 'absolute' : 'relative',
        inset: fill ? 0 : 'auto',
        width: '100%', height: '100%',
        background: `repeating-linear-gradient(45deg, #1a0f0c 0 14px, #110806 14px 28px)`,
        border: `1px dashed ${accent}66`,
        cursor: 'pointer',
        overflow: 'hidden',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: '#EDE6DD',
        fontFamily: 'ui-monospace, "JetBrains Mono", monospace',
      }}>
      {/* dim overlay */}
      <div style={{ position: 'absolute', inset: 0, background: `rgba(10,8,7,${dim})`, pointerEvents: 'none' }} />

      {/* slot label */}
      <div style={{
        position: 'absolute', top: 12, left: 12, zIndex: 2,
        fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase',
        color: accent, background: 'rgba(10,8,7,0.85)',
        padding: '5px 9px', border: `1px solid ${accent}55`,
      }}>
        ◐ IMAGE · {id}
      </div>

      {/* aspect badge */}
      <div style={{
        position: 'absolute', top: 12, right: 12, zIndex: 2,
        fontSize: 9, letterSpacing: '0.16em', textTransform: 'uppercase',
        color: '#8a7e72', background: 'rgba(10,8,7,0.7)',
        padding: '5px 9px',
      }}>{ratio}</div>

      {/* center plus + caption */}
      <div style={{ textAlign: 'center', zIndex: 2, padding: '0 24px', pointerEvents: 'none' }}>
        <div style={{
          width: 44, height: 44, border: `2px solid ${accent}88`, borderRadius: '50%',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          margin: '0 auto 14px', color: accent, fontSize: 22, fontWeight: 700,
        }}>＋</div>
        <div style={{ fontSize: 11, letterSpacing: '0.18em', color: '#EDE6DD', textTransform: 'uppercase', fontWeight: 700 }}>
          {caption || id}
        </div>
        <div style={{ fontSize: 9, letterSpacing: '0.14em', color: '#8a7e72', marginTop: 6 }}>
          CLICK TO SEE GEMINI PROMPT
        </div>
      </div>

      {/* expanded prompt */}
      {showPrompt && (
        <div onClick={(e) => e.stopPropagation()} style={{
          position: 'absolute', inset: 12, zIndex: 3,
          background: 'rgba(6,4,3,0.96)', border: `1px solid ${accent}`,
          padding: 16, overflow: 'auto',
          fontFamily: 'ui-monospace, monospace',
          display: 'flex', flexDirection: 'column', gap: 10,
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ fontSize: 10, color: accent, letterSpacing: '0.18em', textTransform: 'uppercase', fontWeight: 700 }}>
              GEMINI PROMPT · {id}
            </div>
            <button onClick={() => setShowPrompt(false)} style={{
              background: 'transparent', border: 'none', color: '#8a7e72', cursor: 'pointer',
              fontSize: 16, padding: 4,
            }}>✕</button>
          </div>
          <div style={{
            fontSize: 12, color: '#EDE6DD', lineHeight: 1.5,
            whiteSpace: 'pre-wrap', wordBreak: 'break-word',
            flex: 1, fontFamily: 'ui-monospace, monospace',
          }}>{prompt}</div>
          <button onClick={copyPrompt} style={{
            background: copied ? '#4ADE80' : accent, border: 'none', color: '#fff',
            padding: '8px 12px', cursor: 'pointer',
            fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', fontWeight: 700,
            fontFamily: 'inherit', alignSelf: 'flex-start',
          }}>{copied ? '✓ Copied' : 'Copy prompt'}</button>
          <div style={{ fontSize: 9, color: '#8a7e72', letterSpacing: '0.12em' }}>
            Drop into <code>assets/slots/{id}.jpg</code> when ready.
          </div>
        </div>
      )}
    </div>
  );
};

// Centralized list of all image slots used on the page,
// with Gemini prompts. Edit prompts here in one place.
window.OXIDE_IMAGE_SLOTS = {
  'hero-bg': {
    ratio: '21:9 cinematic',
    caption: 'Hero — full-bleed background',
    prompt: 'Cinematic ultra-wide hero shot for a survival game called OXIDE. A lone armored survivor in a tattered hoodie and improvised metal armor stands on a rusted shipping-container rooftop at golden-hour, silhouetted against a smoldering post-industrial wasteland: oil refineries on fire in the far distance, thick orange smoke, embers floating through the air. Volumetric god-rays cut through the smoke. Color palette: deep oxide-red, rust orange, charcoal black, dirty bone white. Shallow DOF, anamorphic lens flare, photorealistic, gritty film grain, 35mm. Composition: wide negative space on the left for headline text, the survivor framed in the right third. NO logos, NO text, NO UI.',
  },
  'value-1': {
    ratio: '1:1',
    caption: 'Value 01 — Vibe Over Views',
    prompt: 'Tight over-the-shoulder shot of a Twitch streamer creator wearing a black hoodie, their RGB-lit gaming setup glowing in a dark room, faces of their viewers reflected as small thumbnails on a second monitor. The chat box on screen is full of lively messages and emotes. Warm rust-orange and cool teal contrast lighting, photorealistic, shallow depth of field, gritty cinematic. Mood: alive, electric, real community. NO visible text or UI labels.',
  },
  'value-2': {
    ratio: '1:1',
    caption: 'Value 02 — Level Up Together',
    prompt: 'Two armored Rust/OXIDE survivors fist-bumping at sunrise on a rooftop made of rusted scrap metal sheets, an entire base-building complex sprawling behind them. Smoky orange sky, lens flare, embers. Photorealistic game-cinematic style, gritty film grain. Color palette: rust, charcoal, gold light. NO text, NO HUD.',
  },
  'value-3': {
    ratio: '1:1',
    caption: 'Value 03 — Direct Dev Access',
    prompt: 'Top-down shot of a rugged industrial workbench: a backlit gaming keyboard, a Discord chat printed onto a torn piece of paper pinned with a knife, schematic blueprints with red-pen developer notes, a coffee mug, scattered ammo casings used as paperweights. Warm tungsten lighting, deep shadows, photorealistic still-life, oxide-red highlights. NO readable text — keep typography blurred/illegible.',
  },
  'tier-legend': {
    ratio: '3:4 portrait',
    caption: 'Tier 4 — Legend hero portrait',
    prompt: 'Heroic 3/4 portrait of an elite OXIDE survivor in custom black-and-rust-red armor with a glowing red visor, posed against a smoke-filled sunset. Their armor has unique etched markings (their gamer-tag stylized as a sigil). Backlit dramatically, embers swirling. Photorealistic, cinematic, painterly. Mood: legendary, untouchable, iconic. NO logos, NO text.',
  },
  'creators-collab': {
    ratio: '16:9',
    caption: 'Squad — collab/co-stream wide',
    prompt: 'Wide cinematic shot of five hooded survivors standing shoulder-to-shoulder at the edge of a rusted bridge overlooking a smoldering post-apocalyptic city. Each one slightly different silhouette and weapon. Heavy backlighting, warm orange smoke behind them, cool blue rim-light from the front. Photorealistic, dramatic, gritty 35mm film. Mood: united squad, ready for battle. NO text, NO visible faces.',
  },
  'faq-bg': {
    ratio: '16:9',
    caption: 'FAQ — atmospheric background',
    prompt: 'Quiet moody atmospheric shot: a single rusted metal door slightly ajar, warm orange light spilling out into a dark concrete corridor. Embers floating in the light beam. Heavy fog, photorealistic, very dark, cinematic. Color: deep oxide red and warm amber, against near-black. NO subjects, just architecture and light. Used as a darkened background for FAQ section.',
  },
  'final-cta': {
    ratio: '21:9 cinematic',
    caption: 'Final CTA — call-to-action backdrop',
    prompt: 'Epic wide shot from behind, of a single armored survivor walking away from camera toward a massive burning sunrise over a rusted industrial wasteland. Hot orange sky, deep silhouettes, volumetric haze. Photorealistic, cinematic, painterly. Strong central perspective, vanishing point in the sun. Color: rust-red, orange, deep brown, black silhouettes. NO text, NO HUD. Mood: invitation, beginning, promise.',
  },
};
