function DemoPlatformLogo({ platform, compact = false }) {
  const typeClass = compact ? 'is-compact' : 'is-hero';

  return (
    <span className={`demo-platform-logo ${typeClass} is-${platform.id}`}>
      {platform.id === 'shopify' ? <span className="demo-platform-logo-bag">S</span> : null}
      {platform.id === 'url' ? <span className="demo-platform-logo-link" aria-hidden="true" /> : null}
      <span className="demo-platform-logo-word">{platform.label}</span>
    </span>
  );
}

function DemoOutputCard({ output, className }) {
  if (!output) return null;

  return (
    <figure className={`demo-flow-card ${className || ''}`}>
      <div className="demo-card-head">
        <span>{output.label}</span>
        <span className="demo-card-plus">+</span>
      </div>
      <div className="demo-card-media">
        {output.src ? (
          <video
            src={output.src}
            poster={output.poster}
            aria-label={output.alt}
            muted
            playsInline
            autoPlay
            loop
          />
        ) : (
          <img src={output.image} alt={output.alt || output.label} />
        )}
      </div>
    </figure>
  );
}

function StudioHero({ copy, sectionId, sectionKey }) {
  const packs = window.ATELA_HERO_DEMO_PACKS || [];
  const defaultPackId = window.ATELA_HERO_DEMO_DEFAULT_PACK_ID || packs[0]?.id || '';
  const [activePackId, setActivePackId] = React.useState(defaultPackId);
  const activePack = packs.find((pack) => pack.id === activePackId) || packs[0];
  const sourcePacks = packs.slice(0, 4);
  const platforms = activePack?.platforms || [];
  const currentLocale = window.atelaGetCurrentLocale ? window.atelaGetCurrentLocale() : 'en';
  const buildPageSectionUrl = window.atelaBuildPageSectionUrl;
  const ctaHref = buildPageSectionUrl
    ? buildPageSectionUrl('studio', 'portfolio', currentLocale)
    : '#portfolio';
  const openStartFlow = window.atelaOpenStartFlow;
  const trackCtaClick = window.atelaTrackCtaClick;
  const isStartFlowComplete = Boolean(window.ATELA_AUTH?.isSignedIn?.());
  const authCopy = window.atelaGetCopySection('auth');
  const ctaLabel = isStartFlowComplete ? (authCopy?.completedCta || copy.cta) : copy.cta;
  const completedIcon = isStartFlowComplete ? (
    <span className="atela-cta-complete-check" aria-hidden="true">
      <svg viewBox="0 0 16 16" focusable="false">
        <path d="M3.5 8.5 6.5 11.5 12.5 4.5" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    </span>
  ) : null;

  const handleCtaClick = (event) => {
    if (trackCtaClick) {
      trackCtaClick({
        sectionId: sectionKey,
        ctaId: 'studio_hero_cta',
        ctaLabel,
        destination: ctaHref,
        is_start_flow_complete: isStartFlowComplete,
      });
    }

    if (openStartFlow) {
      event.preventDefault();
      if (isStartFlowComplete) return;
      openStartFlow({ source: 'studio_hero' });
      return;
    }

    const target = document.getElementById('portfolio');
    if (target) {
      event.preventDefault();
      target.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

  const handlePackClick = (pack) => {
    setActivePackId(pack.id);

    if (window.atelaTrackUiInteraction) {
      window.atelaTrackUiInteraction({
        sectionId: sectionKey,
        interactionId: `studio_hero_pack_${pack.id}`,
        interactionType: 'select',
        interactionLabel: pack.name,
      });
    }
  };

  return (
    <section id={sectionId} className="demo-hero">
      <div className="demo-hero-copy">
        <h1 className="demo-hero-title">
          {copy.titleLead}
          <br />
          {copy.titlePrefix} <span className="atela-mark demo-title-highlight">{copy.titleHighlight}</span>
        </h1>
        <p className="demo-hero-subtitle">
          {(copy.subtitleLines || []).map((line, index) => (
            <React.Fragment key={`${line}-${index}`}>
              {index > 0 ? <br /> : null}
              {line}
            </React.Fragment>
          ))}
        </p>
        <a className="demo-hero-button" href={ctaHref} onClick={handleCtaClick}>
          {ctaLabel}
          {completedIcon || <span className="demo-hero-button-arrow">↗</span>}
        </a>
      </div>

      {activePack ? (
        <div className="demo-flow-stage demo-flow-stage-wire" aria-label="Workflow preview">
          <div className="demo-flow-stage-inner">
            <div className="demo-flow-inputs" aria-hidden="true">
              {platforms.map((platform) => (
                <span key={platform.id} className={`demo-input-node is-${platform.id}`}>
                  <DemoPlatformLogo platform={platform} />
                </span>
              ))}
            </div>

            <div className="demo-source-card is-focused">
              <div className="demo-source-head">
                <span className="demo-source-title">Assets</span>
                <span className="demo-card-plus">+</span>
              </div>
              <div className="demo-source-list">
                {sourcePacks.map((pack) => (
                  <button
                    key={pack.id}
                    type="button"
                    className={`demo-source-item${pack.id === activePack.id ? ' is-active' : ''}`}
                    aria-label={`${copy.packAriaPrefix || 'View result'}: ${pack.name}`}
                    onClick={() => handlePackClick(pack)}
                  >
                    <img className="demo-source-thumb" src={pack.source.image} alt={pack.source.alt || pack.name} />
                    <span>{pack.name}</span>
                  </button>
                ))}
              </div>
            </div>

            <DemoOutputCard output={activePack.outputs?.studio} className="is-shadows" />
            <div className="demo-compact-output-grid">
              <DemoOutputCard output={activePack.outputs?.angle} className="is-angle" />
              <DemoOutputCard output={activePack.outputs?.variation} className="is-variation" />
              <DemoOutputCard output={activePack.outputs?.lifestyle} className="is-lifestyle" />
            </div>
            <DemoOutputCard output={activePack.outputs?.video} className="is-video" />
          </div>
        </div>
      ) : null}
    </section>
  );
}

function Hero(props = {}) {
  const sectionKey = props.sectionKey || 'hero';
  const sectionId = props.sectionId || 'hero';
  const copy = window.atelaGetCopySection(sectionKey);
  const trackCtaClick = window.atelaTrackCtaClick;

  if (copy?.titleLead) {
    return <StudioHero copy={copy} sectionId={sectionId} sectionKey={sectionKey} />;
  }

  const scrollToSection = (event, sectionId) => {
    const el = document.getElementById(sectionId);
    if (el) {
      event.preventDefault();
      el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

  const handlePrimaryClick = (event) => {
    if (trackCtaClick) {
      trackCtaClick({ sectionId, ctaId: 'hero_cta', ctaLabel: copy.cta, destination: '#contact' });
    }
    scrollToSection(event, 'contact');
  };

  const handleSecondaryClick = (event) => {
    if (trackCtaClick) {
      trackCtaClick({ sectionId, ctaId: 'hero_secondary', ctaLabel: copy.secondaryCta, destination: '#how-it-works' });
    }
    scrollToSection(event, 'how-it-works');
  };

  const visual = copy.visual || {};

  return (
    <section id={sectionId} className="landing-hero">
      <div className="landing-hero-inner">
        <div className="landing-hero-copy">
          {copy.eyebrow ? <span className="landing-hero-eyebrow">{copy.eyebrow}</span> : null}
          <h1 className="landing-hero-headline">{copy.headline}</h1>
          <p className="landing-hero-sub">{copy.sub}</p>
          {copy.proof ? (
            <p className="landing-hero-proof">{copy.proof}</p>
          ) : null}
          <div className="landing-hero-actions">
            <a
              href="#contact"
              className="atela-btn-primary"
              onClick={handlePrimaryClick}
            >
              {copy.cta}
            </a>
            <a
              href="#how-it-works"
              className="landing-hero-secondary"
              onClick={handleSecondaryClick}
            >
              {copy.secondaryCta}
            </a>
          </div>
        </div>

        <div className="landing-hero-visual" aria-label="Brand asset production preview">
          <div className="landing-hero-input-card">
            <span>{visual.inputLabel}</span>
            {(visual.inputItems || []).map((item) => <b key={item}>{item}</b>)}
          </div>

          <div className="landing-hero-proof-grid">
            <figure className="landing-hero-proof-card is-before">
              <span className="landing-hero-proof-badge">{visual.beforeLabel}</span>
              <div className="landing-hero-proof-image landing-hero-placeholder">
                <div className="landing-hero-pack">
                  <i />
                  <strong>BRAND</strong>
                  <small>label text drift</small>
                </div>
              </div>
              <figcaption>{visual.beforeCaption}</figcaption>
            </figure>

            <figure className="landing-hero-proof-card is-after">
              <span className="landing-hero-proof-badge">{visual.afterLabel}</span>
              <div className="landing-hero-proof-image">
                <img src="/assets/comparisons/2/atela.avif" alt="ATELA generated beauty product campaign asset" />
              </div>
              <figcaption>{visual.afterCaption}</figcaption>
            </figure>
          </div>

          <div className="landing-hero-output-card">
            <span>{visual.outputLabel}</span>
            {(visual.outputItems || []).map((item) => <b key={item}>{item}</b>)}
          </div>
        </div>
      </div>
    </section>
  );
}

window.Hero = Hero;
