<?php
require_once __DIR__ . '/config.php';
$themes = get_themes();
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <meta name="robots" content="noindex, nofollow">

  <title>AI Photo Booth</title>
  <style>
    :root{
      --bg:#0b0f19;
      --card:#121a2a;
      --muted:#9aa4b2;
      --text:#e6edf3;
      --accent:#7c5cff;
      --accent2:#22c55e;
      --danger:#ef4444;
      --border:rgba(255,255,255,.10);
    }
    *{box-sizing:border-box;font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif}
    body{margin:0;background:radial-gradient(1200px 600px at 20% 10%, rgba(124,92,255,.25), transparent 60%),
                 radial-gradient(800px 500px at 90% 30%, rgba(34,197,94,.18), transparent 60%),
                 var(--bg);
         color:var(--text); min-height:100vh}
    .wrap{max-width:1100px;margin:0 auto;padding:20px}
    .topbar{display:flex;align-items:center;gap:12px;padding:14px 16px;border:1px solid var(--border);
            border-radius:16px;background:rgba(18,26,42,.7);backdrop-filter: blur(10px)}
    .brand img{height:36px;width:auto;display:block}
    .brandTitle{font-weight:700;letter-spacing:.2px}
    .pill{margin-left:auto;font-size:12px;color:var(--muted);border:1px solid var(--border);padding:6px 10px;border-radius:999px}

    .screen{display:none;margin-top:18px}
    .screen.active{display:block}

    .card{border:1px solid var(--border);background:rgba(18,26,42,.7);border-radius:18px;padding:18px}
    h1,h2,h3{margin:0 0 10px}
    p{margin:0 0 14px;color:var(--muted);line-height:1.4}

    .btn{appearance:none;border:0;border-radius:14px;padding:12px 16px;cursor:pointer;font-weight:700}
    .btn-primary{background:linear-gradient(135deg, var(--accent), #4fd1c5);color:#0b0f19}
    .btn-ghost{background:transparent;border:1px solid var(--border);color:var(--text)}
    .btn-danger{background:rgba(239,68,68,.14);border:1px solid rgba(239,68,68,.35);color:#ffd0d0}
    .btn:disabled{opacity:.55;cursor:not-allowed}

    .grid{display:grid;gap:14px}
    /* Better for vertical kiosk screens */
.grid.themes{grid-template-columns:repeat(2, minmax(0, 1fr))}
.grid.avatars{grid-template-columns:repeat(2, minmax(0, 1fr))}
@media(min-width: 900px){
  .grid.themes{grid-template-columns:repeat(3, minmax(0, 1fr))}
  .grid.avatars{grid-template-columns:repeat(3, minmax(0, 1fr))}
}

    .tile{border:1px solid var(--border);border-radius:18px;overflow:hidden;background:rgba(255,255,255,.03);cursor:pointer}
    .tile:hover{border-color:rgba(124,92,255,.5);transform:translateY(-1px)}
    /* Square (1:1) tile images */
.tile img{
  width:100%;
  aspect-ratio: 1 / 1;   /* forces perfect square */
  height:auto;           /* let aspect-ratio control */
  object-fit: cover;
  display:block;
  background:#0a0f18;
}

    .tile .meta{padding:12px}
    .tile .name{font-weight:800}
    .tile .sub{font-size:12px;color:var(--muted);margin-top:6px}

    .row{display:flex;gap:10px;flex-wrap:wrap;align-items:center}
    .row.space{justify-content:space-between}
    .small{font-size:12px;color:var(--muted)}
    .divider{height:1px;background:var(--border);margin:14px 0}

    .cameraBox{display:grid;grid-template-columns:1.1fr .9fr;gap:14px}
    @media(max-width:900px){.cameraBox{grid-template-columns:1fr}}
    video,canvas{width:100%;border-radius:18px;border:1px solid var(--border);background:#000}
    .preview{border-radius:18px;border:1px solid var(--border);overflow:hidden}
    .preview img{width:100%;display:block}

    .status{padding:10px 12px;border-radius:12px;border:1px solid var(--border);color:var(--muted);font-size:13px}
    .status.ok{border-color:rgba(34,197,94,.35);color:#bff7cf;background:rgba(34,197,94,.08)}
    .status.err{border-color:rgba(239,68,68,.35);color:#ffd0d0;background:rgba(239,68,68,.08)}

    .qr{display:flex;justify-content:center;align-items:center;padding:12px;border:1px dashed var(--border);border-radius:16px}
    .qr img{max-width:220px;width:100%;height:auto}
    a{color:#b8c7ff}
    
    /* Welcome banner */
/* Welcome banner */
/* Banner: responsive + shows FULL image (no crop) */
.banner{
  width:100%;
  margin: 0 0 14px;
  border-radius:18px;
  overflow:hidden;
  border:1px solid var(--border);
  background: rgba(255,255,255,.03);
}

.banner img{
  width:100%;
  height:auto;          /* ✅ keeps full image */
  display:block;
  object-fit: contain;  /* optional, safe */
}

/* Mobile: make it full width of screen (not limited by wrap padding) */
@media (max-width: 768px){
  .banner{
    margin-left: calc(50% - 50vw);  /* ✅ full-bleed trick */
    margin-right: calc(50% - 50vw);
    width:100vw;
    border-radius: 0;
    border-left: 0;
    border-right: 0;
  }
}

  
    /* WhatsApp number input */
    input[type="tel"]{
      width:100%;
      padding:12px 12px;
      border-radius:14px;
      border:1px solid var(--border);
      background:rgba(255,255,255,.03);
      color:var(--text);
      outline:none;
    }
    input[type="tel"]::placeholder{color:rgba(154,164,178,.75)}
    input[type="tel"]:focus{
      border-color:rgba(124,92,255,.6);
      box-shadow:0 0 0 3px rgba(124,92,255,.15);
    }

  </style>
</head>
<body>
<div class="wrap">
  <div class="topbar">
    <div class="brand">
      <!-- Put your logo at: assets/logo.png -->
      <img src="assets/logo.png" alt="Brand" onerror="this.style.display='none'">
    </div>
    <div>
      <div class="brandTitle">AI Photo Booth</div>
      
    </div>
    
  </div>

  <!-- Screen 1: Welcome -->
  <div class="screen active" id="screen-welcome">
    <div class="card">
      <h1>Welcome 👋</h1>
      
      <!-- Big responsive banner -->
<div class="banner">
  <img src="assets/banner.jpg" alt="Banner" onerror="this.parentElement.style.display='none'">
</div>
      
      <p>Tap start, choose your theme & avatar, take a selfie, and get your AI photo instantly.</p>
      <div class="row">
        <button class="btn btn-primary" id="btnStart">Start AI Photo Booth</button>
      </div>
      <div class="divider"></div>
      <div class="small">
        Tip: For best results, use good lighting and keep face centered.
      </div>
    </div>
  </div>

  <!-- Screen 2: Themes -->
  <div class="screen" id="screen-themes">
    <div class="row space">
      <div>
        <h2>Select a Theme</h2>
        <p>Pick the vibe first.</p>
      </div>
      <div class="row">
        <button class="btn btn-ghost" onclick="goTo('welcome')">Back</button>
      </div>
    </div>

    <div class="grid themes" id="themesGrid"></div>
  </div>

  <!-- Screen 3: Avatars -->
  <div class="screen" id="screen-avatars">
    <div class="row space">
      <div>
        <h2 id="avatarTitle">Select an Avatar</h2>
        <p id="avatarSub">Pick your avatar style.</p>
      </div>
      <div class="row">
        <button class="btn btn-ghost" onclick="goTo('themes')">Back</button>
      </div>
    </div>

    <div class="grid avatars" id="avatarsGrid"></div>
  </div>

  <!-- Screen 4: Camera + Result -->
  <div class="screen" id="screen-camera">
    <div class="row space">
      <div>
        <h2>Take a Selfie</h2>
        <p id="selectionText"></p>
      </div>
      <div class="row">
        <button class="btn btn-ghost" onclick="goTo('avatars')">Back</button>
        <button class="btn btn-danger" id="btnResetAll">Start Over</button>
      </div>
    </div>

    <div class="cameraBox">
      <div class="card">
        <h3>Camera</h3>
        <p class="small">Allow camera permission. Then click “Capture”.</p>

        <video id="video" autoplay playsinline muted></video>

        <img id="selfiePreview" alt="Captured selfie"
     style="display:none;width:100%;border-radius:18px;border:1px solid var(--border);background:#000;" />
        <canvas id="canvas" style="display:none;"></canvas>

        <div class="divider"></div>
        <div class="row">
          <button class="btn btn-primary" id="btnCapture">Capture</button>
          <button class="btn btn-ghost" id="btnRetake" disabled>Retake</button>
          <button class="btn btn-primary" id="btnGenerate" disabled>Generate AI</button>
        </div>

        <div class="divider"></div>
        <div id="statusBox" class="status">Waiting for selfie…</div>
      </div>

      <div class="card">
        <h3>Result</h3>
        <p class="small">Your AI photo will appear here after processing.</p>

        <div class="preview" id="resultPreview" style="display:none;">
          <img id="resultImg" src="" alt="Generated">
        </div>

        <div class="divider"></div>

        <div class="row" id="waRow" style="display:none;align-items:flex-end;">
          <div style="flex:1;min-width:220px;">
            <div class="small" style="margin-bottom:6px;">Enter your WhatsApp number (with country code)</div>
            <input id="waNumber" type="tel" inputmode="numeric" autocomplete="tel" placeholder="91XXXXXXXXXX">
            <div class="small" style="margin-top:6px;">Example: 919876543210 (India). If you enter 10 digits, we’ll auto-add 91.</div>
          </div>
        </div>

<div class="divider"></div>

        <div class="row" id="resultActions" style="display:none;">
          <button class="btn btn-primary" id="btnWhatsapp">Share on WhatsApp</button>
          <a class="btn btn-ghost" id="btnDownload" href="#" download>Download</a>
        </div>

        <div class="divider"></div>

        <div class="qr" id="qrBox" style="display:none;">
          <div>
            <div class="small" style="text-align:center;margin-bottom:10px;">Scan to download</div>
            <img id="qrImg" src="" alt="QR">
          </div>
        </div>

        <div class="small" id="directLinkBox" style="margin-top:10px;display:none;">
          Direct link: <a id="directLink" href="#" target="_blank" rel="noreferrer">Open</a>
        </div>
      </div>
    </div>
  </div>

</div>

<script>
  // Themes data from PHP
  const THEMES = <?php echo json_encode($themes, JSON_UNESCAPED_SLASHES); ?>;

  // Simple state
  let selectedTheme = null;
  let selectedAvatar = null;
  let stream = null;
  let capturedBlob = null;

const crumb = document.getElementById('crumb');
function setCrumb(text){ if(crumb) crumb.textContent = text; }


  function goTo(screen){
    document.querySelectorAll('.screen').forEach(s => s.classList.remove('active'));
    document.getElementById('screen-' + screen).classList.add('active');

    if(screen === 'welcome') setCrumb('Welcome');
    if(screen === 'themes') setCrumb('Themes');
    if(screen === 'avatars') setCrumb('Avatars');
    if(screen === 'camera') setCrumb('Selfie');

    // Camera screen: start camera when entering
    if(screen === 'camera'){
      startCamera();
    } else {
      stopCamera();
    }
  }

  // Screen 1 button
  document.getElementById('btnStart').addEventListener('click', () => {
    renderThemes();
    goTo('themes');
  });

  // Themes rendering
  function renderThemes(){
    const grid = document.getElementById('themesGrid');
    grid.innerHTML = '';

    THEMES.forEach(t => {
      const div = document.createElement('div');
      div.className = 'tile';
      div.innerHTML = `
        <img src="${t.thumbnail}" alt="${t.name}" onerror="this.src='https://picsum.photos/400/240?random=1'">
        <div class="meta">
          <div class="name">${t.name}</div>
          <div class="sub">${t.avatars.length} avatar(s)</div>
        </div>
      `;
      div.addEventListener('click', () => {
        selectedTheme = t;
        renderAvatars();
        goTo('avatars');
      });
      grid.appendChild(div);
    });
  }

  // Avatars rendering
  function renderAvatars(){
    const grid = document.getElementById('avatarsGrid');
    const title = document.getElementById('avatarTitle');
    const sub = document.getElementById('avatarSub');

    title.textContent = `Select an Avatar — ${selectedTheme.name}`;
    sub.textContent = `Choose one avatar style to generate.`;

    grid.innerHTML = '';
    selectedTheme.avatars.forEach(a => {
      const div = document.createElement('div');
      div.className = 'tile';
      div.innerHTML = `
        <img src="${a.thumbnail}" alt="${a.name}" onerror="this.src='https://picsum.photos/400/240?random=2'">
        <div class="meta">
          <div class="name">${a.name}</div>
          <div class="sub">Tap to select</div>
        </div>
      `;
      div.addEventListener('click', () => {
        selectedAvatar = a;
        resetCameraUIOnly();
        document.getElementById('selectionText').textContent = `Theme: ${selectedTheme.name} • Avatar: ${selectedAvatar.name}`;
        goTo('camera');
      });
      grid.appendChild(div);
    });
  }

  // Camera logic
  const video = document.getElementById('video');
  const canvas = document.getElementById('canvas');
  const selfiePreview = document.getElementById('selfiePreview');

  const btnCapture = document.getElementById('btnCapture');
  const btnRetake = document.getElementById('btnRetake');
  const btnGenerate = document.getElementById('btnGenerate');
  const statusBox = document.getElementById('statusBox');

  const resultPreview = document.getElementById('resultPreview');
  const resultImg = document.getElementById('resultImg');
  const resultActions = document.getElementById('resultActions');
  const btnWhatsapp = document.getElementById('btnWhatsapp');
  const btnDownload = document.getElementById('btnDownload');
  const qrBox = document.getElementById('qrBox');
  const qrImg = document.getElementById('qrImg');
  const directLinkBox = document.getElementById('directLinkBox');
  const directLink = document.getElementById('directLink');

  const waRow = document.getElementById('waRow');
  const waNumber = document.getElementById('waNumber');

  function setStatus(text, type=''){
    statusBox.className = 'status ' + (type || '');
    statusBox.textContent = text;
  }

  async function startCamera(){
  if(stream) return;
  try{
    // iOS/Android reliable constraints
    stream = await navigator.mediaDevices.getUserMedia({
      video: { facingMode: "user" },
      audio: false
    });

    video.srcObject = stream;

    // iOS Safari reliability fixes
    video.muted = true;
    video.playsInline = true;

    const p = video.play();
    if (p && typeof p.then === "function") await p;

    setStatus('Camera ready. Capture a selfie.', 'ok');
  }catch(e){
    console.error(e);
    setStatus('Camera failed: ' + (e.name || '') + ' ' + (e.message || ''), 'err');
  }
}


  function stopCamera(){
    if(stream){
      stream.getTracks().forEach(t => t.stop());
      stream = null;
    }
  }

  function resetCameraUIOnly(){
    capturedBlob = null;
    btnRetake.disabled = true;
    btnGenerate.disabled = true;
    btnCapture.disabled = false;
    
     video.style.display = 'block';
     selfiePreview.style.display = 'none';
     selfiePreview.src = '';
    
    setStatus('Waiting for selfie…');

    // result UI reset
    resultPreview.style.display = 'none';
    resultActions.style.display = 'none';
    qrBox.style.display = 'none';
    directLinkBox.style.display = 'none';
    if(waRow){ waRow.style.display = 'none'; }
    if(waNumber){ waNumber.value = ''; }
    resultImg.src = '';
    btnDownload.href = '#';
    btnWhatsapp.onclick = null;
  }

  btnCapture.addEventListener('click', async () => {
    if(!stream){
      setStatus('Camera not started yet.', 'err');
      return;
    }
    const w = video.videoWidth;
    const h = video.videoHeight;
    if(!w || !h){
      setStatus('Camera not ready, try again.', 'err');
      return;
    }
    canvas.width = w;
    canvas.height = h;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0, w, h);

    // Convert to blob
    canvas.toBlob((blob) => {
  capturedBlob = blob;

  // Show captured selfie preview (freeze frame)
  selfiePreview.src = canvas.toDataURL('image/jpeg', 0.92);
  selfiePreview.style.display = 'block';
  video.style.display = 'none';

  // Optional: pause video stream so it doesn't keep moving in background
  // (even if hidden)
  // video.pause();

  btnRetake.disabled = false;
  btnGenerate.disabled = false;
  btnCapture.disabled = true;
  setStatus('Selfie captured. Click “Generate AI”.', 'ok');
}, 'image/jpeg', 0.92);

  });

  btnRetake.addEventListener('click', () => {
    resetCameraUIOnly();
  });

  document.getElementById('btnResetAll').addEventListener('click', () => {
    selectedTheme = null;
    selectedAvatar = null;
    resetCameraUIOnly();
    goTo('welcome');
  });

  // Generate AI (calls backend api/process.php - we'll build next)
  btnGenerate.addEventListener('click', async () => {
    if(!capturedBlob || !selectedTheme || !selectedAvatar){
      setStatus('Missing selfie or selection.', 'err');
      return;
    }

    setStatus('Uploading selfie & generating… please wait.', '');
    btnGenerate.disabled = true;
    btnRetake.disabled = true;

    try{
      const fd = new FormData();
      fd.append('themeId', selectedTheme.id);
      fd.append('avatarId', selectedAvatar.id);
      fd.append('selfie', capturedBlob, 'selfie.jpg');

      const res = await fetch('api/process.php', {
        method: 'POST',
        body: fd
      });

      const data = await res.json();

      if(!res.ok || !data.success){
        throw new Error(data.error || 'Unknown error');
      }

      // Show result
      const url = data.generatedUrl;
      resultImg.src = url;
      resultPreview.style.display = 'block';
      resultActions.style.display = 'flex';
      qrBox.style.display = 'flex';
      directLinkBox.style.display = 'block';
      directLink.href = url;

      btnDownload.href = url;

      // WhatsApp share (opens WhatsApp on THIS device to send the link)
      if(waRow){ waRow.style.display = 'flex'; }

      btnWhatsapp.onclick = () => {
        const raw = (waNumber && waNumber.value) ? waNumber.value.trim() : '';
        let digits = raw.replace(/[^0-9]/g, '');

        // If user enters 10 digits, assume India and add 91
        if(digits.length === 10) digits = '91' + digits;

        if(digits.length < 10){
          setStatus('❌ Please enter a valid WhatsApp number (with country code).', 'err');
          if(waNumber) waNumber.focus();
          return;
        }

        const msg = encodeURIComponent(`Here is your AI Photo Booth image:
${url}`);
        const waUrl = `https://wa.me/${digits}?text=${msg}`;
        window.open(waUrl, '_blank');
      };

      // QR code (use free QR image generator)
      qrImg.src = `https://api.qrserver.com/v1/create-qr-code/?size=260x260&data=${encodeURIComponent(url)}`;

      setStatus('✅ Generated successfully!', 'ok');
      btnRetake.disabled = false;

    }catch(err){
      console.error(err);
      setStatus('❌ ' + err.message, 'err');
      btnGenerate.disabled = false;
      btnRetake.disabled = false;
    }
  });

</script>
</body>
</html>
