/* Penrose v2 — Campaign-pack repositioning. Atoms + Hero.
 * Loads after penrose-atoms.jsx (reuses PnTopNav, PnButton, PnOrb, PnFooter).
 */

const { useState: useStateV2, useEffect: useEffectV2 } = React;
const { PnButton: PnBtn2, PnOrb: PnOrb2 } = window;
const BOOKING_URL_V2 = window.PENROSE_BOOKING_URL || 'https://calendar.app.google/xFdbQsvUw5x5eVS48';

// V2 hero render card — reframed as "Campaign Pack" with multi-format variants.

const V2_PACKS = [
  {
    client: 'Mercer HVAC',
    pack: 'Pack 04 · Summer tune-up',
    brand: 'MH',
    bg: 'linear-gradient(160deg, #2a4a3a 0%, #4a6b58 38%, #c8a584 100%)',
    caption: <>Before the heat <em>wins.</em></>,
    cta: '$59 tune-up',
    formats: [
      { ratio: '9:16', label: 'Reels', video: 'uploads/6473926-uhd_2160_3840_25fps.mp4', bg: 'linear-gradient(160deg, #2a4a3a, #4a6b58 40%, #c8a584)' },
      { ratio: '1:1',  label: 'Feed',   video: 'uploads/cartoon-plumber-feed.mp4', bg: 'linear-gradient(170deg, #2a1c3a, #5a4a78 50%, #c8b8e0)' },
      { ratio: '16:9', label: 'YouTube', video: 'uploads/running-shoes-youtube.mp4', endAt: 4.5, bg: 'linear-gradient(150deg, #3a2a1c, #785a3a 50%, #f4c5a8)' },
      { ratio: ':06',  label: 'Bumper', video: 'uploads/diamond-ring-bumper.mp4', bg: 'linear-gradient(180deg, #1c2a3a, #4a5a78 50%, #a8c8e8)' },
    ],
  },
  {
    client: 'Hearthstone Roofing',
    pack: 'Pack 02 · Storm response',
    brand: 'HR',
    bg: 'linear-gradient(170deg, #3a2a4a 0%, #6b4a78 45%, #e8b8c4 100%)',
    caption: <>A roof that <em>outlives</em> the storm.</>,
    cta: 'Free inspection',
    formats: [
      { ratio: '9:16', label: 'TikTok',  bg: 'linear-gradient(170deg, #3a2a4a, #6b4a78 45%, #e8b8c4)' },
      { ratio: '1:1',  label: 'Meta',    bg: 'linear-gradient(160deg, #2a1c1c, #5a3a3a 50%, #e8b8a8)' },
      { ratio: '16:9', label: 'CTV',     bg: 'linear-gradient(180deg, #1c2a3a, #4a5a78 50%, #a8c8e8)' },
      { ratio: ':06',  label: 'Bumper',  bg: 'linear-gradient(150deg, #2a3a2a, #4a6b4a 50%, #a7e5b8)' },
    ],
  },
  {
    client: 'Mercy Valley Health',
    pack: 'Pack 07 · RN recruiting',
    brand: 'MV',
    bg: 'linear-gradient(180deg, #1c2a3a 0%, #4a5a78 50%, #a8c8e8 100%)',
    caption: <>Hiring 40 nurses <em>this</em> quarter.</>,
    cta: 'Apply now',
    formats: [
      { ratio: '9:16', label: 'Reels',    bg: 'linear-gradient(180deg, #1c2a3a, #4a5a78 50%, #a8c8e8)' },
      { ratio: '1:1',  label: 'LinkedIn', bg: 'linear-gradient(170deg, #2a2a3a, #4a4a6a 50%, #b8b8d8)' },
      { ratio: '16:9', label: 'YouTube',  bg: 'linear-gradient(150deg, #2a3a1c, #5a6b3a 50%, #b8c884)' },
      { ratio: ':06',  label: 'Bumper',   bg: 'linear-gradient(180deg, #1c3a2a, #3a6b58 50%, #a7e5d3)' },
    ],
  },
];

const syncVideoWindow = (video, format) => {
  const startAt = format.startAt || 0;
  const endAt = format.endAt;
  if (video.currentTime < startAt || (typeof endAt === 'number' && video.currentTime >= endAt)) {
    video.currentTime = startAt;
    const playPromise = video.play();
    if (playPromise?.catch) playPromise.catch(() => {});
  }
};

const PnRenderCardV2 = ({ packIdx, formatIdx, onPickFormat }) => {
  const p = V2_PACKS[packIdx];
  const f = p.formats[formatIdx];
  return (
    <div className="pn-render-card">
      <div className="pn-render-card__head">
        <div className="pn-render-card__head-l">
          <div className="pn-render-card__brand">{p.brand}</div>
          <div className="pn-render-card__brief">
            <small>Campaign pack</small>
            {p.client}
          </div>
        </div>
        <div className="pn-render-card__status">
          <span className="dot" />
          Ready for review
        </div>
      </div>

      <div className="pn-render-card__frame" style={{ background: f.bg }}>
        {f.video && (
          <video
            className="pn-render-card__video"
            src={f.video}
            autoPlay
            muted
            loop
            playsInline
            preload="auto"
            onLoadedMetadata={(e) => syncVideoWindow(e.currentTarget, f)}
            onTimeUpdate={(e) => syncVideoWindow(e.currentTarget, f)}
          />
        )}
        <div className="pn-render-card__frame-tag">
          <span className="rec" />
          {f.label} · {f.ratio}
        </div>
        <div className="pn-render-card__frame-caption">{p.caption}</div>
        <div className="pn-render-card__frame-brand">
          <span className="mark">{p.brand}</span>
          {p.client}
        </div>
        <div className="pn-render-card__frame-cta">{p.cta} →</div>
        <div className="pn-render-card__progress" />
      </div>

      <div className="pn-render-card__variants">
        {p.formats.map((ff, i) => (
          <div
            key={i}
            className={`pn-variant ${i === formatIdx ? 'active' : ''}`}
            style={{ background: ff.bg }}
            onClick={() => onPickFormat(i)}
            title={`${ff.label} · ${ff.ratio}`}
          >
            {ff.video && (
              <video
                className="pn-variant__video"
                src={ff.video}
                autoPlay
                muted
                loop
                playsInline
                preload="metadata"
                onLoadedMetadata={(e) => syncVideoWindow(e.currentTarget, ff)}
                onTimeUpdate={(e) => syncVideoWindow(e.currentTarget, ff)}
              />
            )}
            <div className="pn-variant__label">{ff.ratio}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

const PnHeroV2 = ({ tweaks }) => {
  const packIdx = 0;
  const [formatIdx, setFormatIdx] = useStateV2(0);
  const palette = tweaks.palette || ['#f4c5a8', '#e8b8c4', '#c8b8e0'];
  const layout = tweaks.heroLayout || 'split';
  const headline = tweaks.heroHeadline || '3 ready-to-run video ads for your client|delivered in 5 business days.';
  const [a, b] = headline.split('|');

  // Rotate only the four hero formats; do not advance into the sample packs below.
  useEffectV2(() => {
    const id = setInterval(() => {
      setFormatIdx(fi => (fi + 1) % V2_PACKS[packIdx].formats.length);
    }, 4000);
    return () => clearInterval(id);
  }, []);

  return (
    <section className={`pn-hero ${layout === 'center' ? 'pn-hero--centered' : ''}`} data-screen-label="Hero">
      <PnOrb2 color={palette[0]} drift="drift-1" style={{ width: 720, height: 720, top: -140, left: -160, opacity: 0.55 }} />
      <PnOrb2 color={palette[1]} drift="drift-2" style={{ width: 600, height: 600, top: 40, right: -120, opacity: 0.5 }} />
      <PnOrb2 color={palette[2]} drift="drift-3" style={{ width: 480, height: 480, bottom: -200, left: '32%', opacity: 0.42 }} />

      <div className="pn-hero__container">
        <div className="pn-hero__grid">
          <div>
            <div className="pn-hero__eyebrow">
              <span className="dot" />
              White-label video ad production for agencies
            </div>
            <h1 className="pn-hero__title">
              {a}<br /><em>{b}</em>
            </h1>
            <p className="pn-hero__sub">
              We turn your brief into a polished paid-social video Campaign Pack using AI-assisted production and human creative review.
            </p>
            <div className="pn-hero__ctas">
              <PnBtn2 variant="primary" size="lg" href={BOOKING_URL_V2}>Get Started</PnBtn2>
              <PnBtn2 variant="outline" size="lg" href="#campaign-pack-preview">View sample campaign pack →</PnBtn2>
            </div>
          </div>
          <div className="pn-hero__side">
            <PnRenderCardV2 packIdx={packIdx} formatIdx={formatIdx} onPickFormat={setFormatIdx} />
          </div>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { PnHeroV2, PnRenderCardV2, V2_PACKS });
