// scenes/apps.jsx
// Hero-level showcase of Aldene's flagship internal applications.
// Each scene fills the full 1920×1080 stage and displays ONE app
// with its real screenshot (fully visible — objectFit: contain).
//
// Layouts:
//   - 'right'     : text panel left   ·  app frame right
//   - 'left'      : app frame left    ·  text panel right
//   - 'fullbleed' : header centred top, big app frame below

// ─────────────────────────────────────────────────────────────────────────
// AppShowcase — generic hero app scene
// ─────────────────────────────────────────────────────────────────────────
function AppShowcase({
  number,
  category, categoryColor,
  nameLines,           // array of strings, each a line in the title
  tagline,             // short value prop (yellow)
  description,         // body copy
  bullets = [],
  qrCode = null,       // { url, label, title, subtitle } — renders a QR panel in text column
  screenshot,          // /screenshots/foo.png
  url,                 // "portail.aldene.fr" — shown in app chrome
  layout = 'right',
  frameAccent,
  imageBg = '#FFFFFF', // letterbox color around contained image
  hideHeader = false,  // fullbleed: hide BIG title (compact caption only if tagline/description)
}) {
  const { localTime, duration } = useSprite();
  const t = localTime;
  const reveal = Math.max(0, Math.min(1, (t - 0.15) / 0.65));
  const exit   = Math.max(0, Math.min(1, (t - (duration - 0.5)) / 0.5));
  const exitOp = 1 - exit;
  const accent = frameAccent || categoryColor;

  // ──────────────────── FULLBLEED ────────────────────
  if (layout === 'fullbleed') {
    const hasCaption = hideHeader && (tagline || description);
    const showFullHeader = !hideHeader;

    const frameW = showFullHeader ? 1540 : 1700;
    const frameH = showFullHeader ? (description ? 760 : 820) : (hasCaption ? 880 : 920);
    const frameTop = showFullHeader ? (description ? 290 : 230) : (hasCaption ? 160 : 80);
    const frameLeft = (1920 - frameW) / 2;
    return (
      <div style={{ position: 'absolute', inset: 0, opacity: exitOp }}>
        <PageBackground>
          <div style={{ position: 'absolute', top: -50, right: -20, opacity: 0.35 }}>
            <SlashCluster appearAt={0} stagger={0.06} duration={0.45} scale={0.4} origin="tr"/>
          </div>
          <div style={{ position: 'absolute', bottom: -90, left: -60, opacity: 0.3 }}>
            <SlashCluster appearAt={0.1} stagger={0.06} duration={0.45} scale={0.35} origin="bl"/>
          </div>

          {/* Header — number, category, name, tagline (skipped when hideHeader) */}
          {showFullHeader && (
          <div style={{
            position: 'absolute',
            left: 0, right: 0, top: 78,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12,
            opacity: reveal,
            transform: `translateY(${(1 - reveal) * -10}px)`,
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 16,
            }}>
              <span style={{
                fontFamily: FONT_DISPLAY, fontWeight: 700, fontSize: 13,
                letterSpacing: '.24em', color: ALD.yellow,
              }}>
                A P P L I C A T I O N &nbsp;·&nbsp; {number}
              </span>
              <span style={{ color: 'rgba(255,255,255,.3)' }}>·</span>
              <ServiceChip color={categoryColor} label={category} size={14}
                style={{ textTransform: 'uppercase', letterSpacing: '.16em',
                         fontFamily: FONT_DISPLAY, fontWeight: 700, fontSize: 13 }}/>
            </div>
            <div style={{
              fontFamily: FONT_DISPLAY, fontWeight: 800, fontSize: 64,
              lineHeight: 0.98, letterSpacing: '-0.015em',
              textTransform: 'uppercase', color: ALD.white,
              textAlign: 'center',
            }}>
              {nameLines.join(' ')}<span style={{ color: ALD.yellow }}>.</span>
            </div>
            {tagline && (
              <div style={{
                fontFamily: FONT_DISPLAY, fontWeight: 600, fontSize: 22,
                color: ALD.yellow, letterSpacing: '-0.005em',
                maxWidth: 1300, textAlign: 'center',
                marginTop: 2,
              }}>
                {tagline}
              </div>
            )}
            {description && (
              <div style={{
                fontFamily: FONT_BODY, fontWeight: 400, fontSize: 17,
                color: '#C7CADD', lineHeight: 1.45,
                maxWidth: 1100, textAlign: 'center',
                marginTop: 6,
              }}>
                {description}
              </div>
            )}
          </div>
          )}

          {/* Compact caption — used when hideHeader is on but copy is provided */}
          {hasCaption && (
          <div style={{
            position: 'absolute',
            left: 0, right: 0, top: 50,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
            opacity: reveal,
            transform: `translateY(${(1 - reveal) * -8}px)`,
          }}>
            {tagline && (
              <div style={{
                fontFamily: FONT_DISPLAY, fontWeight: 700, fontSize: 26,
                color: ALD.white, letterSpacing: '-0.005em',
                textAlign: 'center', textTransform: 'uppercase',
              }}>
                {tagline} <span style={{ color: ALD.yellow }}>.</span>
              </div>
            )}
            {description && (
              <div style={{
                fontFamily: FONT_BODY, fontWeight: 400, fontSize: 17,
                color: '#C7CADD', lineHeight: 1.45,
                maxWidth: 1100, textAlign: 'center',
              }}>
                {description}
              </div>
            )}
          </div>
          )}

          {/* App frame */}
          <div style={{
            position: 'absolute',
            left: frameLeft,
            top: frameTop,
            width: frameW, height: frameH,
            opacity: reveal,
            transform: `translateY(${(1 - reveal) * 28}px)`,
          }}>
            <AppFrame title={url} width={frameW} height={frameH}
                      accent={accent} background={imageBg}>
              <ContainedImage src={screenshot} bg={imageBg}/>
            </AppFrame>
          </div>
        </PageBackground>
      </div>
    );
  }

  // ──────────────────── SPLIT (right or left) ────────────────────
  const imageOnRight = layout !== 'left';
  const frameW = 1080;
  const frameH = 660;
  const frameTop = (1080 - frameH) / 2;

  const textPanel = (
    <div style={{
      width: 540,
      opacity: reveal,
      transform: `translateX(${(1 - reveal) * (imageOnRight ? -30 : 30)}px)`,
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12,
        marginBottom: 24,
      }}>
        <span style={{
          fontFamily: FONT_DISPLAY, fontWeight: 700, fontSize: 12,
          letterSpacing: '.24em', color: ALD.yellow,
        }}>
          A P P &nbsp;·&nbsp; {number}
        </span>
        <span style={{ color: 'rgba(255,255,255,.25)' }}>·</span>
        <ServiceChip color={categoryColor} label={category} size={14}
          style={{ textTransform: 'uppercase', letterSpacing: '.14em',
                   fontFamily: FONT_DISPLAY, fontWeight: 700, fontSize: 12 }}/>
      </div>

      <div style={{
        fontFamily: FONT_DISPLAY, fontWeight: 800, fontSize: 80,
        lineHeight: 0.95, letterSpacing: '-0.015em',
        textTransform: 'uppercase', color: ALD.white,
        marginBottom: 22,
      }}>
        {nameLines.map((l, i) => (
          <div key={i}>
            {l}{i === nameLines.length - 1 && <span style={{ color: ALD.yellow }}>.</span>}
          </div>
        ))}
      </div>

      {tagline && (
        <div style={{
          fontFamily: FONT_DISPLAY, fontWeight: 700, fontSize: 28,
          lineHeight: 1.18, color: ALD.yellow,
          letterSpacing: '-0.005em', marginBottom: 28, maxWidth: 540,
        }}>
          {tagline}
        </div>
      )}

      {description && (
        <div style={{
          fontFamily: FONT_BODY, fontWeight: 400, fontSize: 19,
          lineHeight: 1.5, color: '#C7CADD',
          marginBottom: bullets.length ? 26 : 0, maxWidth: 540,
        }}>
          {description}
        </div>
      )}

      {bullets.length > 0 && (
        <ul style={{
          listStyle: 'none', padding: 0, margin: 0,
          display: 'flex', flexDirection: 'column', gap: 12,
        }}>
          {bullets.map((b, i) => (
            <li key={i} style={{
              fontFamily: FONT_BODY, fontWeight: 500, fontSize: 17,
              color: ALD.white, display: 'flex', alignItems: 'flex-start', gap: 14,
              lineHeight: 1.4,
            }}>
              <span style={{
                width: 7, height: 7, borderRadius: 4, background: ALD.yellow,
                display: 'inline-block', flexShrink: 0, marginTop: 9,
              }}/>
              {b}
            </li>
          ))}
        </ul>
      )}

      {/* Optional QR code panel */}
      {qrCode && (
        <div style={{
          marginTop: bullets.length ? 26 : 14,
          display: 'flex', alignItems: 'center', gap: 18,
          padding: '14px 22px 14px 14px',
          background: ALD.white,
          borderRadius: 14,
          width: 'fit-content',
          boxShadow: '0 14px 36px rgba(0,0,0,.35)',
        }}>
          <img
            src={`https://api.qrserver.com/v1/create-qr-code/?size=260x260&data=${encodeURIComponent(qrCode.url)}&color=1E2442&bgcolor=FFFFFF&qzone=1`}
            alt={`QR ${qrCode.url}`}
            style={{ width: 124, height: 124, borderRadius: 6, display: 'block' }}
          />
          <div style={{ color: ALD.navy, fontFamily: FONT_BODY }}>
            <div style={{
              fontFamily: FONT_DISPLAY, fontWeight: 700, fontSize: 11,
              letterSpacing: '.20em', textTransform: 'uppercase',
              color: '#8A90B0',
            }}>{qrCode.label || 'S C A N N E Z  \u2192'}</div>
            <div style={{
              fontFamily: FONT_DISPLAY, fontWeight: 800, fontSize: 22,
              letterSpacing: '-0.01em', marginTop: 4,
            }}>{qrCode.title || qrCode.url}</div>
            {qrCode.subtitle && (
              <div style={{
                fontFamily: FONT_BODY, fontSize: 12,
                color: '#4A5175', maxWidth: 220, marginTop: 6,
                lineHeight: 1.4,
              }}>{qrCode.subtitle}</div>
            )}
          </div>
        </div>
      )}
    </div>
  );

  const appFrame = (
    <div style={{
      width: frameW, height: frameH,
      opacity: reveal,
      transform: `translateX(${(1 - reveal) * (imageOnRight ? 40 : -40)}px)`,
    }}>
      <AppFrame title={url} width={frameW} height={frameH}
                accent={accent} background={imageBg}>
        <ContainedImage src={screenshot} bg={imageBg}/>
      </AppFrame>
    </div>
  );

  return (
    <div style={{ position: 'absolute', inset: 0, opacity: exitOp }}>
      <PageBackground>
        <div style={{ position: 'absolute', top: -50, right: -20, opacity: 0.4 }}>
          <SlashCluster appearAt={0} stagger={0.06} duration={0.45} scale={0.45} origin="tr"/>
        </div>

        {imageOnRight ? (
          <>
            <div style={{
              position: 'absolute',
              left: 110, top: '50%', transform: 'translateY(-50%)',
            }}>{textPanel}</div>
            <div style={{
              position: 'absolute',
              right: 80, top: frameTop,
            }}>{appFrame}</div>
          </>
        ) : (
          <>
            <div style={{
              position: 'absolute',
              left: 80, top: frameTop,
            }}>{appFrame}</div>
            <div style={{
              position: 'absolute',
              right: 110, top: '50%', transform: 'translateY(-50%)',
            }}>{textPanel}</div>
          </>
        )}
      </PageBackground>
    </div>
  );
}

// ─── ContainedImage — full screenshot visible, no cropping ─────────────
function ContainedImage({ src, bg = '#FFFFFF' }) {
  return (
    <div style={{
      width: '100%', height: '100%',
      background: bg,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      overflow: 'hidden',
    }}>
      <img
        src={src}
        alt=""
        style={{
          maxWidth: '100%', maxHeight: '100%',
          width: 'auto', height: 'auto',
          objectFit: 'contain',
          display: 'block',
        }}
      />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// HERO scenes (10 apps × 8s each)
// ─────────────────────────────────────────────────────────────────────────

function SceneAppPortail() {
  return (
    <AppShowcase
      number="01" category="Infrastructure · SSO" categoryColor={ALD.svc.info}
      nameLines={['Portail', 'Aldene']}
      tagline="Tous nos outils, un seul endroit"
      description="Accès SSO Entra ID, reverse proxy Caddy, gestion d'accès par projet. Tout est hébergé en local chez nous — nos données ne sortent pas."
      screenshot="screenshots/portail.png"
      url="portail.aldene.fr"
      layout="fullbleed"
      hideHeader={true}
      imageBg={ALD.navy}
    />
  );
}

function SceneAppOpenWebUI() {
  return (
    <AppShowcase
      number="02" category="IA & Agents" categoryColor={ALD.svc.ia}
      nameLines={['ChatGPT', 'Interne']}
      tagline="L'IA souveraine, pour toutes nos équipes."
      description="Interface unifiée donnant accès à nos modèles Ollama locaux (gpt-oss:120b, llama, mistral) et aux APIs OpenAI / Claude — sans jamais exposer les données client."
      bullets={[
        'Modèles locaux et APIs cloud, au choix',
        'Authentification SSO + journalisation',
        'Données client jamais transmises au public',
      ]}
      screenshot="screenshots/openwebui.png"
      url="chat.aldene.fr"
      layout="right"
    />
  );
}

function SceneAppTriMail() {
  return (
    <AppShowcase
      number="03" category="Automatisation · IA" categoryColor={ALD.svc.ia}
      nameLines={['Tri Mail', 'IA']}
      tagline="Le tri du courrier, en automatique."
      description="Chaque email qui arrive sur votre boîte mail est analysé par une IA : priorité, tag métier, action suggérée. Vous attaquez directement ce qui compte vraiment."
      bullets={[
        'Classification 4 niveaux : urgent, à traiter, normal, low',
        'Tags métier auto : client, devis, RH, sécurité…',
        'Détection des mails sans réponse à relancer',
      ]}
      screenshot="screenshots/trimail.png"
      url="trimail.aldene.fr"
      layout="left"
    />
  );
}

function SceneApp3CX() {
  return (
    <AppShowcase
      number="04" category="IA Vocale · Téléphonie" categoryColor={ALD.svc.tel}
      nameLines={['3CX', 'Transcript']}
      tagline="Identifier les irritants client — et améliorer la qualité de service."
      description="Chaque appel est transcrit, résumé et noté par l'IA : ton client, qualité de la réponse, points de friction. Un radar pour repérer ce qui doit être corrigé — côté client comme côté équipe interne."
      bullets={[
        "Détection des incidents relationnels (confus, mécontent…)",
        "Suivi qualité par technicien et par client",
        "Boucle d'amélioration continue, sans écoute manuelle",
      ]}
      screenshot="screenshots/3cx-transcript.png"
      url="transcript.aldene.fr"
      layout="right"
    />
  );
}

function SceneAppDashboardSupport() {
  return (
    <AppShowcase
      number="05" category="Dashboards · TV mural" categoryColor={ALD.svc.print}
      nameLines={['Dashboard', 'Support']}
      tagline="Le pilotage temps réel de notre support, en open-space."
      description="Affiché sur grand écran 24/7 : 22 techniciens supervisés, files de tickets, appels 3CX, alertes SLA. Tout l'open-space sait où en est le support, à la seconde près."
      screenshot="screenshots/dashboard-support.png"
      url="dashboard.aldene.fr/support"
      layout="fullbleed"
      imageBg={ALD.navy}
    />
  );
}

function SceneAppTamponFacture() {
  return (
    <AppShowcase
      number="06" category="Comptabilité · Automatisation" categoryColor={ALD.svc.ged}
      nameLines={['Tampon', 'Facture']}
      tagline="Les factures fournisseurs, traitées toutes seules."
      description="Le service compta scanne. L'IA extrait, tamponne, déduplique et archive. Aujourd'hui : 88 % d'extraction automatique, doublons détectés et écartés sans saisie manuelle."
      bullets={[
        'Extraction IA · 88 % de confiance moyenne',
        'Dédoublonnage sur historique des factures',
        'Quarantaine pour les cas à risque',
      ]}
      screenshot="screenshots/tampon-facture.png"
      url="tampon.aldene.fr"
      layout="left"
    />
  );
}

function SceneAppS2F() {
  return (
    <AppShowcase
      number="07" category="Comptabilité · ERP" categoryColor={ALD.svc.ged}
      nameLines={['Suivi Factures', 'Fournisseurs']}
      tagline="Les volumes facturés sous contrôle."
      description="Comparaison automatique des factures fournisseurs avec les commandes ERP : licences totales, variations, alertes de rapprochement. Le service compta voit les écarts avant la clôture."
      bullets={[
        '30 000 licences suivies sur 16 fournisseurs',
        'Variations mensuelles détectées automatiquement',
        'Alertes de rapprochement · écarts facturé vs commandé',
      ]}
      screenshot="screenshots/s2f.png"
      url="s2f.aldene.fr"
      layout="right"
      imageBg={ALD.navy}
    />
  );
}

function SceneAppN8N() {
  return (
    <AppShowcase
      number="08" category="Infrastructure · Workflows" categoryColor={ALD.svc.cyber}
      nameLines={['n8n', 'Workflows']}
      tagline="L'infrastructure qui fait tourner tout le reste."
      description="Notre couche d'orchestration interne. Plus de 200 workflows automatisent ce qui prenait du temps : tri du courrier, génération de rapports, alertes métier, synchronisations."
      bullets={[
        '200+ workflows actifs en production',
        '65 423 exécutions · 99,8 % de succès',
        '27 heures économisées par semaine',
      ]}
      screenshot="screenshots/n8n.png"
      url="n8n.aldene.fr"
      layout="left"
      imageBg="#FAFAFA"
    />
  );
}

function SceneAppAldeneAI() {
  return (
    <AppShowcase
      number="09" category="Site public · Vitrine" categoryColor={ALD.svc.mob}
      nameLines={['Aldene', 'AI']}
      tagline="Notre vitrine IA — pour vous, qui nous regardez."
      description="Le site public de notre offre IA : services, secteurs, FAQ, prise de rendez-vous. Conçu et déployé en interne. www.aldeneai.fr"
      bullets={[
        'Vitrine de notre savoir-faire IA',
        'Diagnostic IA en ligne pour prospects',
        'Hébergé et opéré par nos équipes',
      ]}
      screenshot="screenshots/aldene-ai-site.png"
      url="www.aldeneai.fr"
      layout="fullbleed"
    />
  );
}

function SceneAppDiagnosticIA() {
  return (
    <AppShowcase
      number="10" category="Outil prospect · IA" categoryColor={ALD.svc.ia}
      nameLines={['Diagnostic', 'IA']}
      tagline="4 minutes pour mesurer le potentiel IA de votre entreprise."
      description="Un test gratuit en ligne : 4 minutes, 1 rapport personnalisé généré par l'IA. Idéal pour ouvrir le dialogue — chiffre les heures gagnables sur vos process actuels."
      qrCode={{
        url: 'https://diagnostic.aldene.ai',
        label: 'S C A N N E Z  P O U R  T E S T E R',
        title: 'diagnostic.aldene.ai',
        subtitle: 'Rapport personnalisé généré par l’IA en 4 minutes.',
      }}
      screenshot="screenshots/diagnostic-ia.png"
      url="diagnostic.aldene.ai"
      layout="left"
      imageBg={ALD.navy}
    />
  );
}

function SceneAppLiveCyber() {
  return (
    <AppShowcase
      number="11" category="Cybersécurité · Veille" categoryColor={ALD.svc.cyber}
      nameLines={['Live', 'Cyber']}
      tagline="La menace cyber expliquée simplement — et l'activité Aldene en direct."
      description="Veille temps réel ransomwares, CVE critiques, fuites de données et sanctions CNIL pour les PME françaises. Le site affiche aussi l'activité du support Aldene en direct : tickets ouverts, postes supervisés, alertes en cours."
      screenshot="screenshots/live-cyber.png"
      url="cyber.aldene.fr"
      layout="fullbleed"
    />
  );
}

Object.assign(window, {
  AppShowcase, ContainedImage,
  SceneAppPortail, SceneAppOpenWebUI, SceneAppTriMail, SceneApp3CX,
  SceneAppDashboardSupport, SceneAppTamponFacture, SceneAppS2F, SceneAppN8N,
  SceneAppAldeneAI, SceneAppDiagnosticIA, SceneAppLiveCyber,
});
