<?php
// public/website-spec.php — 7-Step Website Specification Generator
require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/layout.php';

$user = requireAuth();
$id   = (int)($_GET['id'] ?? 0);
$proj = getProject($id, $user['id']);
if (!$proj) { flash('error', 'Project not found.'); redirect(APP_URL . '/projects.php'); }

$step    = max(1, min(7, (int)($_GET['step'] ?? 1)));
$spec    = fetchOne("SELECT * FROM website_specs WHERE project_id = ? AND user_id = ?", [$id, $user['id']]);
$studio  = getStudioSettings($user['id']);

// ── Default font pairs ──────────────────────────────────────────────────────────
$fontPairs = [
    'Syne + DM Sans'           => ['heading' => 'Syne',           'body' => 'DM Sans'],
    'Playfair Display + Lato'  => ['heading' => 'Playfair Display','body' => 'Lato'],
    'Montserrat + Open Sans'   => ['heading' => 'Montserrat',      'body' => 'Open Sans'],
    'Bricolage Grotesque + Inter' => ['heading' => 'Bricolage Grotesque', 'body' => 'Inter'],
    'Raleway + Source Sans Pro'=> ['heading' => 'Raleway',         'body' => 'Source Sans Pro'],
    'Oswald + Roboto'          => ['heading' => 'Oswald',          'body' => 'Roboto'],
    'Custom'                   => ['heading' => '',                'body' => ''],
];

$brandStyles = ['Modern / Minimal','Bold & Creative','Corporate / Professional','Luxury / Premium','Playful & Friendly','Dark & Dramatic','Earthy & Organic','Tech / SaaS'];
$colorMoods  = ['Professional & Trustworthy','Energetic & Bold','Calm & Soothing','Elegant & Luxury','Fun & Playful','Natural & Earthy','Dark & Sophisticated','Fresh & Modern'];

// ── POST handlers ──────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = $_POST['action'] ?? '';

    // Save any step's data
    if ($action === 'save_step') {
        $postedStep = (int)($_POST['step'] ?? 1);
        $data       = [];

        switch ($postedStep) {
            case 1:
                $data = [
                    'business_name' => trim($_POST['business_name'] ?? ''),
                    'tagline'       => trim($_POST['tagline']       ?? ''),
                    'about'         => trim($_POST['about']         ?? ''),
                    'industry'      => trim($_POST['industry']      ?? ''),
                    'website_url'   => trim($_POST['website_url']   ?? ''),
                ];
                break;
            case 2:
                // Pages: array of name + description rows
                $pageNames = $_POST['page_name']  ?? [];
                $pageDescs = $_POST['page_desc']  ?? [];
                $pages = [];
                foreach ($pageNames as $i => $name) {
                    $name = trim($name);
                    if ($name) $pages[] = ['name' => $name, 'desc' => trim($pageDescs[$i] ?? '')];
                }
                $data = ['pages' => json_encode($pages)];
                break;
            case 3:
                // Services: name + description + price
                $svcNames   = $_POST['svc_name']  ?? [];
                $svcDescs   = $_POST['svc_desc']  ?? [];
                $svcPrices  = $_POST['svc_price'] ?? [];
                $services = [];
                foreach ($svcNames as $i => $name) {
                    $name = trim($name);
                    if ($name) $services[] = [
                        'name'  => $name,
                        'desc'  => trim($svcDescs[$i]  ?? ''),
                        'price' => trim($svcPrices[$i] ?? ''),
                    ];
                }
                $data = ['services' => json_encode($services)];
                break;
            case 4:
                $data = [
                    'target_audience' => trim($_POST['target_audience'] ?? ''),
                    'competitors'     => trim($_POST['competitors']     ?? ''),
                    'goals'           => trim($_POST['goals']           ?? ''),
                    'usp'             => trim($_POST['usp']             ?? ''),
                ];
                break;
            case 5:
                $data = [
                    'primary_color'   => $_POST['primary_color']   ?? '#000000',
                    'secondary_color' => $_POST['secondary_color'] ?? '#ffffff',
                    'accent_color'    => $_POST['accent_color']    ?? '#5b5ef4',
                    'color_mood'      => trim($_POST['color_mood'] ?? ''),
                    'color_notes'     => trim($_POST['color_notes'] ?? ''),
                ];
                break;
            case 6:
                $headingFont = trim($_POST['heading_font'] ?? '');
                $bodyFont    = trim($_POST['body_font']    ?? '');
                // If a font pair was selected, override custom input
                $pair = $_POST['font_pair'] ?? '';
                if ($pair && isset($fontPairs[$pair]) && $pair !== 'Custom') {
                    $headingFont = $fontPairs[$pair]['heading'];
                    $bodyFont    = $fontPairs[$pair]['body'];
                }
                $data = [
                    'logo_url'          => trim($_POST['logo_url']          ?? ''),
                    'heading_font'      => $headingFont,
                    'body_font'         => $bodyFont,
                    'brand_style'       => trim($_POST['brand_style']       ?? ''),
                    'brand_personality' => trim($_POST['brand_personality'] ?? ''),
                ];
                break;
        }

        if ($data) {
            if ($spec) {
                update('website_specs', $data, 'id = ?', [$spec['id']]);
            } else {
                $data['project_id'] = $id;
                $data['user_id']    = $user['id'];
                insert('website_specs', $data);
                $spec = fetchOne("SELECT * FROM website_specs WHERE project_id = ? AND user_id = ?", [$id, $user['id']]);
            }
        }

        // Navigate to next step or stay on 7
        $nextStep = min(7, $postedStep + 1);
        redirect(APP_URL . "/website-spec.php?id=$id&step=$nextStep");
    }

    if ($action === 'generate_spec') {
        if (!$spec) { flash('error', 'Complete the form steps first.'); redirect(APP_URL . "/website-spec.php?id=$id&step=1"); }
        $specData = $spec;
        // Fill intake fallbacks
        $intake = fetchOne("SELECT * FROM intake_forms WHERE project_id = ?", [$id]);
        if ($intake) {
            if (!$specData['target_audience']) $specData['target_audience'] = $intake['target_audience'] ?? '';
            if (!$specData['goals'])           $specData['goals']           = $intake['goals'] ?? '';
            if (!$specData['competitors'])     $specData['competitors']     = $intake['competitors'] ?? '';
        }
        $content = generateWebsiteSpecWithAI($specData, $user['id']);
        update('website_specs', ['ai_spec' => $content, 'generated_at' => date('Y-m-d H:i:s')], 'id = ?', [$spec['id']]);
        flash('success', 'Website specification generated!');
        redirect(APP_URL . "/website-spec.php?id=$id&step=7");
    }
}

// Reload spec after any saves
$spec = fetchOne("SELECT * FROM website_specs WHERE project_id = ? AND user_id = ?", [$id, $user['id']]);
$pages    = json_decode($spec['pages']    ?? '[]', true) ?: [];
$services = json_decode($spec['services'] ?? '[]', true) ?: [];

// ── Step completion check ──────────────────────────────────────────────────────
function stepDone(array $spec, int $s): bool {
    return match($s) {
        1 => !empty($spec['business_name']),
        2 => !empty($spec['pages']),
        3 => true, // optional
        4 => !empty($spec['target_audience']),
        5 => !empty($spec['primary_color']),
        6 => !empty($spec['brand_style']),
        7 => !empty($spec['ai_spec']),
        default => false,
    };
}

$stepLabels = ['Basic Info','Pages','Services','Business','Colors','Logo & Fonts','Review'];

renderHead('Website Spec — ' . $proj['title']);
renderNav($user);
renderFlash();
?>

<!-- Project crumb -->
<div style="display:flex;align-items:center;gap:8px;margin-bottom:20px;font-size:13px;color:var(--text2)">
  <a href="<?= APP_URL ?>/projects.php" style="color:var(--text2)">Projects</a>
  <span>›</span>
  <a href="<?= APP_URL ?>/project.php?id=<?= $id ?>" style="color:var(--text2)"><?= e($proj['title']) ?></a>
  <span>›</span>
  <span style="color:var(--text)">Website Spec</span>
</div>

<!-- ── STEP WIZARD HEADER ──────────────────────────────────────────────────── -->
<div class="card" style="padding:20px 24px;margin-bottom:24px;">
  <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
    <div>
      <h1 style="font-size:18px;font-weight:700;margin:0">Website Instruction Generator</h1>
      <p style="font-size:12px;color:var(--text2);margin:3px 0 0">Step <?= $step ?> of 7 — <?= $stepLabels[$step-1] ?></p>
    </div>
    <?php if ($step === 7 && $spec && $spec['ai_spec']): ?>
    <a href="<?= APP_URL ?>/website-spec-pdf.php?id=<?= $id ?>" target="_blank" class="btn btn-primary">
      <svg viewBox="0 0 24 24" style="width:16px;height:16px"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
      Download PDF
    </a>
    <?php endif; ?>
  </div>

  <!-- Step progress bar -->
  <div style="display:flex;gap:4px;align-items:center;">
    <?php foreach ($stepLabels as $i => $label):
      $num     = $i + 1;
      $isDone  = stepDone($spec ?? [], $num);
      $isCur   = $num === $step;
      $clr     = $isCur ? 'var(--accent)' : ($isDone ? 'var(--green)' : 'var(--border)');
      $txtClr  = $isCur ? '#fff' : ($isDone ? '#fff' : 'var(--text2)');
    ?>
    <a href="<?= APP_URL ?>/website-spec.php?id=<?= $id ?>&step=<?= $num ?>"
       style="display:flex;flex-direction:column;align-items:center;gap:4px;text-decoration:none;flex:1;min-width:0;">
      <div style="width:28px;height:28px;border-radius:50%;background:<?= $clr ?>;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;color:<?= $txtClr ?>;transition:.2s;flex-shrink:0;">
        <?= $isDone && !$isCur ? '✓' : $num ?>
      </div>
      <div style="font-size:9.5px;color:<?= $isCur ? 'var(--accent)' : 'var(--text2)' ?>;font-weight:<?= $isCur ? '600' : '400' ?>;text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:100%;"><?= $label ?></div>
    </a>
    <?php if ($i < 6): ?>
    <div style="flex:0 0 24px;height:2px;background:<?= $isDone ? 'var(--green)' : 'var(--border)' ?>;border-radius:2px;margin-bottom:18px;"></div>
    <?php endif; ?>
    <?php endforeach; ?>
  </div>
</div>

<!-- ══════════════════════════════════════════════════════════════════════════
     STEP 1 — Basic Info
══════════════════════════════════════════════════════════════════════════ -->
<?php if ($step === 1): ?>
<div class="card">
  <h2 class="card-title">Basic Business Information</h2>
  <p style="font-size:13px;color:var(--text2);margin-bottom:24px;">Tell us about the client's business.</p>
  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="save_step">
    <input type="hidden" name="step" value="1">

    <div class="form-row">
      <div class="form-group">
        <label>Business Name *</label>
        <input type="text" name="business_name" value="<?= e($spec['business_name'] ?? $proj['client_name'] ?? '') ?>" required placeholder="e.g. Acme Design Studio">
      </div>
      <div class="form-group">
        <label>Industry</label>
        <input type="text" name="industry" value="<?= e($spec['industry'] ?? '') ?>" placeholder="e.g. Fitness, Real Estate, SaaS">
      </div>
    </div>
    <div class="form-group">
      <label>Tagline / Slogan</label>
      <input type="text" name="tagline" value="<?= e($spec['tagline'] ?? '') ?>" placeholder="e.g. Building the web, one pixel at a time">
    </div>
    <div class="form-group">
      <label>About the Business</label>
      <textarea name="about" rows="4" placeholder="Describe what the business does, its history, and what makes it unique."><?= e($spec['about'] ?? '') ?></textarea>
    </div>
    <div class="form-group">
      <label>Current Website URL <small style="font-weight:400;color:var(--text2)">(if any)</small></label>
      <input type="url" name="website_url" value="<?= e($spec['website_url'] ?? '') ?>" placeholder="https://...">
    </div>
    <div style="display:flex;gap:10px;margin-top:8px;">
      <a href="<?= APP_URL ?>/project.php?id=<?= $id ?>" class="btn btn-ghost">← Back to Project</a>
      <button class="btn btn-primary" type="submit">Save & Continue →</button>
    </div>
  </form>
</div>

<!-- ══════════════════════════════════════════════════════════════════════════
     STEP 2 — Pages
══════════════════════════════════════════════════════════════════════════ -->
<?php elseif ($step === 2): ?>
<div class="card">
  <h2 class="card-title">Website Pages</h2>
  <p style="font-size:13px;color:var(--text2);margin-bottom:20px;">List all pages the website needs. Each page can have a short description of its purpose.</p>
  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="save_step">
    <input type="hidden" name="step" value="2">

    <div id="pages-container">
      <?php
      // Show saved pages or default starter set
      $defaultPages = $pages ?: [
        ['name' => 'Home',       'desc' => 'Hero, services overview, testimonials, CTA'],
        ['name' => 'About',      'desc' => 'Story, team, mission and values'],
        ['name' => 'Services',   'desc' => 'Detailed service listings with pricing'],
        ['name' => 'Portfolio',  'desc' => 'Case studies and project showcase'],
        ['name' => 'Contact',    'desc' => 'Contact form, map, phone and email'],
      ];
      foreach ($defaultPages as $i => $page):
      ?>
      <div class="page-row" style="display:grid;grid-template-columns:180px 1fr auto;gap:10px;margin-bottom:10px;align-items:center;">
        <input type="text" name="page_name[]" value="<?= e($page['name']) ?>" placeholder="Page name" style="font-weight:600;">
        <input type="text" name="page_desc[]" value="<?= e($page['desc']) ?>" placeholder="Purpose / key content (optional)">
        <button type="button" class="btn btn-ghost btn-sm" onclick="this.closest('.page-row').remove()" style="padding:8px;color:var(--red)">✕</button>
      </div>
      <?php endforeach; ?>
    </div>

    <button type="button" class="btn btn-ghost btn-sm" style="margin-top:4px;margin-bottom:24px;" onclick="addPageRow()">+ Add Page</button>

    <div style="display:flex;gap:10px;">
      <a href="?id=<?= $id ?>&step=1" class="btn btn-ghost">← Back</a>
      <button class="btn btn-primary" type="submit">Save & Continue →</button>
    </div>
  </form>
</div>
<script>
function addPageRow() {
  var c = document.getElementById('pages-container');
  var d = document.createElement('div');
  d.className = 'page-row';
  d.style.cssText = 'display:grid;grid-template-columns:180px 1fr auto;gap:10px;margin-bottom:10px;align-items:center;';
  d.innerHTML = '<input type="text" name="page_name[]" placeholder="Page name" style="font-weight:600;">'
              + '<input type="text" name="page_desc[]" placeholder="Purpose / key content (optional)">'
              + '<button type="button" class="btn btn-ghost btn-sm" onclick="this.closest(\'.page-row\').remove()" style="padding:8px;color:var(--red)">✕</button>';
  c.appendChild(d);
  d.querySelector('input').focus();
}
</script>

<!-- ══════════════════════════════════════════════════════════════════════════
     STEP 3 — Services
══════════════════════════════════════════════════════════════════════════ -->
<?php elseif ($step === 3): ?>
<div class="card">
  <h2 class="card-title">Services / Offerings</h2>
  <p style="font-size:13px;color:var(--text2);margin-bottom:20px;">What does the client sell or offer? Add each service with a description and optional price. You can skip this step if not applicable.</p>
  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="save_step">
    <input type="hidden" name="step" value="3">

    <!-- Column headers -->
    <div style="display:grid;grid-template-columns:200px 1fr 120px auto;gap:10px;margin-bottom:6px;padding:0 2px;">
      <div style="font-size:11px;font-weight:600;color:var(--text2)">Service Name</div>
      <div style="font-size:11px;font-weight:600;color:var(--text2)">Description</div>
      <div style="font-size:11px;font-weight:600;color:var(--text2)">Price (optional)</div>
      <div></div>
    </div>

    <div id="services-container">
      <?php
      $defaultSvcs = $services ?: [['name'=>'','desc'=>'','price'=>'']];
      foreach ($defaultSvcs as $i => $svc):
      ?>
      <div class="svc-row" style="display:grid;grid-template-columns:200px 1fr 120px auto;gap:10px;margin-bottom:10px;align-items:center;">
        <input type="text" name="svc_name[]"  value="<?= e($svc['name'])  ?>" placeholder="e.g. Website Design">
        <input type="text" name="svc_desc[]"  value="<?= e($svc['desc'])  ?>" placeholder="Brief description">
        <input type="text" name="svc_price[]" value="<?= e($svc['price']) ?>" placeholder="e.g. $1,500">
        <button type="button" class="btn btn-ghost btn-sm" onclick="this.closest('.svc-row').remove()" style="padding:8px;color:var(--red)">✕</button>
      </div>
      <?php endforeach; ?>
    </div>

    <button type="button" class="btn btn-ghost btn-sm" style="margin-top:4px;margin-bottom:24px;" onclick="addSvcRow()">+ Add Service</button>

    <div style="display:flex;gap:10px;">
      <a href="?id=<?= $id ?>&step=2" class="btn btn-ghost">← Back</a>
      <button class="btn btn-primary" type="submit">Save & Continue →</button>
      <a href="?id=<?= $id ?>&step=4" class="btn btn-ghost" style="color:var(--text2)">Skip →</a>
    </div>
  </form>
</div>
<script>
function addSvcRow() {
  var c = document.getElementById('services-container');
  var d = document.createElement('div');
  d.className = 'svc-row';
  d.style.cssText = 'display:grid;grid-template-columns:200px 1fr 120px auto;gap:10px;margin-bottom:10px;align-items:center;';
  d.innerHTML = '<input type="text" name="svc_name[]" placeholder="e.g. Website Design">'
              + '<input type="text" name="svc_desc[]" placeholder="Brief description">'
              + '<input type="text" name="svc_price[]" placeholder="e.g. $1,500">'
              + '<button type="button" class="btn btn-ghost btn-sm" onclick="this.closest(\'.svc-row\').remove()" style="padding:8px;color:var(--red)">✕</button>';
  c.appendChild(d);
  d.querySelector('input').focus();
}
</script>

<!-- ══════════════════════════════════════════════════════════════════════════
     STEP 4 — Business
══════════════════════════════════════════════════════════════════════════ -->
<?php elseif ($step === 4): ?>
<div class="card">
  <h2 class="card-title">Business & Audience</h2>
  <p style="font-size:13px;color:var(--text2);margin-bottom:24px;">This helps the AI write a strategy-focused specification document.</p>
  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="save_step">
    <input type="hidden" name="step" value="4">

    <?php $intake = fetchOne("SELECT * FROM intake_forms WHERE project_id = ?", [$id]); ?>
    <div class="form-group">
      <label>Target Audience *</label>
      <textarea name="target_audience" rows="3" placeholder="Who are the ideal customers? Age, profession, pain points, goals..."><?= e($spec['target_audience'] ?? $intake['target_audience'] ?? '') ?></textarea>
    </div>
    <div class="form-group">
      <label>Unique Selling Proposition (USP)</label>
      <textarea name="usp" rows="2" placeholder="What makes this business stand out from competitors?"><?= e($spec['usp'] ?? '') ?></textarea>
    </div>
    <div class="form-group">
      <label>Website Goals</label>
      <textarea name="goals" rows="3" placeholder="What should the website achieve? Generate leads, sell products, build authority..."><?= e($spec['goals'] ?? $intake['goals'] ?? '') ?></textarea>
    </div>
    <div class="form-group">
      <label>Competitors / Inspiration Sites</label>
      <textarea name="competitors" rows="2" placeholder="URLs or names of competitor or inspiration websites..."><?= e($spec['competitors'] ?? $intake['competitors'] ?? '') ?></textarea>
    </div>
    <div style="display:flex;gap:10px;">
      <a href="?id=<?= $id ?>&step=3" class="btn btn-ghost">← Back</a>
      <button class="btn btn-primary" type="submit">Save & Continue →</button>
    </div>
  </form>
</div>

<!-- ══════════════════════════════════════════════════════════════════════════
     STEP 5 — Colors
══════════════════════════════════════════════════════════════════════════ -->
<?php elseif ($step === 5): ?>
<div class="card">
  <h2 class="card-title">Brand Colors</h2>
  <p style="font-size:13px;color:var(--text2);margin-bottom:24px;">Choose the brand color palette for the website.</p>
  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="save_step">
    <input type="hidden" name="step" value="5">

    <!-- Live color preview swatch -->
    <div id="color-preview" style="display:flex;gap:0;border-radius:var(--radius-lg);overflow:hidden;height:64px;margin-bottom:24px;border:1px solid var(--border);">
      <div id="swatch-primary"   style="flex:1;background:<?= e($spec['primary_color']   ?? '#1a1a2e') ?>;" title="Primary"></div>
      <div id="swatch-secondary" style="flex:1;background:<?= e($spec['secondary_color'] ?? '#ffffff') ?>;" title="Secondary"></div>
      <div id="swatch-accent"    style="flex:1;background:<?= e($spec['accent_color']    ?? '#5b5ef4') ?>;" title="Accent"></div>
    </div>

    <div class="form-row cols-3">
      <div class="form-group">
        <label>Primary Color</label>
        <div style="display:flex;gap:8px;align-items:center;">
          <input type="color" name="primary_color" id="pc" value="<?= e($spec['primary_color'] ?? '#1a1a2e') ?>"
                 style="width:42px;height:36px;border:1px solid var(--border);border-radius:8px;background:var(--bg3);padding:2px;cursor:pointer;"
                 oninput="document.getElementById('swatch-primary').style.background=this.value">
          <input type="text" id="pc-hex" value="<?= e($spec['primary_color'] ?? '#1a1a2e') ?>" style="flex:1;"
                 oninput="document.getElementById('pc').value=this.value;document.getElementById('swatch-primary').style.background=this.value">
        </div>
        <small style="color:var(--text2);font-size:11px">Main background / text color</small>
      </div>
      <div class="form-group">
        <label>Secondary Color</label>
        <div style="display:flex;gap:8px;align-items:center;">
          <input type="color" name="secondary_color" id="sc" value="<?= e($spec['secondary_color'] ?? '#f5f5f5') ?>"
                 style="width:42px;height:36px;border:1px solid var(--border);border-radius:8px;background:var(--bg3);padding:2px;cursor:pointer;"
                 oninput="document.getElementById('swatch-secondary').style.background=this.value">
          <input type="text" id="sc-hex" value="<?= e($spec['secondary_color'] ?? '#f5f5f5') ?>" style="flex:1;"
                 oninput="document.getElementById('sc').value=this.value;document.getElementById('swatch-secondary').style.background=this.value">
        </div>
        <small style="color:var(--text2);font-size:11px">Background / surface color</small>
      </div>
      <div class="form-group">
        <label>Accent / CTA Color</label>
        <div style="display:flex;gap:8px;align-items:center;">
          <input type="color" name="accent_color" id="ac" value="<?= e($spec['accent_color'] ?? '#5b5ef4') ?>"
                 style="width:42px;height:36px;border:1px solid var(--border);border-radius:8px;background:var(--bg3);padding:2px;cursor:pointer;"
                 oninput="document.getElementById('swatch-accent').style.background=this.value">
          <input type="text" id="ac-hex" value="<?= e($spec['accent_color'] ?? '#5b5ef4') ?>" style="flex:1;"
                 oninput="document.getElementById('ac').value=this.value;document.getElementById('swatch-accent').style.background=this.value">
        </div>
        <small style="color:var(--text2);font-size:11px">Buttons, links, highlights</small>
      </div>
    </div>

    <div class="form-row">
      <div class="form-group">
        <label>Color Mood / Feel</label>
        <select name="color_mood">
          <option value="">— Select —</option>
          <?php foreach ($colorMoods as $m): ?>
          <option value="<?= $m ?>" <?= ($spec['color_mood'] ?? '') === $m ? 'selected' : '' ?>><?= $m ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label>Color Notes</label>
        <input type="text" name="color_notes" value="<?= e($spec['color_notes'] ?? '') ?>" placeholder="e.g. avoid red, client loves earth tones">
      </div>
    </div>

    <div style="display:flex;gap:10px;">
      <a href="?id=<?= $id ?>&step=4" class="btn btn-ghost">← Back</a>
      <button class="btn btn-primary" type="submit">Save & Continue →</button>
    </div>
  </form>
</div>

<!-- ══════════════════════════════════════════════════════════════════════════
     STEP 6 — Logo & Fonts
══════════════════════════════════════════════════════════════════════════ -->
<?php elseif ($step === 6): ?>
<div class="card">
  <h2 class="card-title">Logo, Fonts & Brand Style</h2>
  <p style="font-size:13px;color:var(--text2);margin-bottom:24px;">Define the visual identity beyond color.</p>
  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="save_step">
    <input type="hidden" name="step" value="6">

    <!-- Logo -->
    <div class="form-group">
      <label>Logo URL <small style="font-weight:400;color:var(--text2)">(PNG, SVG or WebP recommended)</small></label>
      <div style="display:flex;gap:12px;align-items:center;">
        <img id="logo-prev" src="<?= e($spec['logo_url'] ?? '') ?>" style="height:44px;max-width:120px;object-fit:contain;<?= ($spec['logo_url'] ?? '') ? '' : 'display:none;' ?>"
             onerror="this.style.display='none'">
        <input type="url" name="logo_url" value="<?= e($spec['logo_url'] ?? '') ?>"
               placeholder="https://yoursite.com/logo.png" style="flex:1;"
               oninput="var img=document.getElementById('logo-prev');img.src=this.value;img.style.display=this.value?'':'none'">
      </div>
    </div>

    <!-- Brand Style -->
    <div class="form-group">
      <label>Brand Style</label>
      <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:4px;">
        <?php foreach ($brandStyles as $bs): ?>
        <label style="display:flex;align-items:center;gap:6px;padding:8px 14px;border:1.5px solid <?= ($spec['brand_style'] ?? '') === $bs ? 'var(--accent)' : 'var(--border)' ?>;border-radius:var(--radius);cursor:pointer;font-size:12px;transition:.15s;"
               onclick="document.querySelectorAll('.bs-opt').forEach(el=>{el.style.borderColor='var(--border)';el.style.color='var(--text2)'});this.style.borderColor='var(--accent)';this.style.color='var(--accent)'">
          <input type="radio" name="brand_style" value="<?= $bs ?>" <?= ($spec['brand_style'] ?? '') === $bs ? 'checked' : '' ?> style="display:none;">
          <?= $bs ?>
        </label>
        <?php endforeach; ?>
      </div>
    </div>

    <!-- Font Pairs -->
    <div class="form-group">
      <label>Typography Pair</label>
      <?php $currentPair = ''; foreach ($fontPairs as $pairName => $p) { if ($p['heading'] === ($spec['heading_font'] ?? '') && $p['body'] === ($spec['body_font'] ?? '')) { $currentPair = $pairName; break; } } ?>
      <select name="font_pair" id="font-pair-select" onchange="onFontPairChange(this.value)" style="margin-bottom:10px;">
        <?php foreach ($fontPairs as $pairName => $p): ?>
        <option value="<?= $pairName ?>" <?= $currentPair === $pairName ? 'selected' : '' ?>>
          <?= $pairName ?><?= $p['heading'] ? ' — ' . $p['heading'] . ' + ' . $p['body'] : '' ?>
        </option>
        <?php endforeach; ?>
      </select>
      <div id="custom-fonts" style="display:<?= (!$currentPair || $currentPair === 'Custom') ? 'grid' : 'none' ?>;grid-template-columns:1fr 1fr;gap:12px;">
        <div class="form-group" style="margin:0">
          <label>Heading Font</label>
          <input type="text" name="heading_font" id="heading-font" value="<?= e($spec['heading_font'] ?? '') ?>" placeholder="e.g. Syne">
        </div>
        <div class="form-group" style="margin:0">
          <label>Body Font</label>
          <input type="text" name="body_font" id="body-font" value="<?= e($spec['body_font'] ?? '') ?>" placeholder="e.g. DM Sans">
        </div>
      </div>
    </div>

    <!-- Brand Personality -->
    <div class="form-group">
      <label>Brand Personality / Tone of Voice</label>
      <textarea name="brand_personality" rows="3" placeholder="e.g. Professional yet approachable. Confident but never arrogant. Uses plain language..."><?= e($spec['brand_personality'] ?? '') ?></textarea>
    </div>

    <div style="display:flex;gap:10px;">
      <a href="?id=<?= $id ?>&step=5" class="btn btn-ghost">← Back</a>
      <button class="btn btn-primary" type="submit">Save & Continue →</button>
    </div>
  </form>
</div>
<script>
<?php echo "var fontPairs = " . json_encode($fontPairs) . ";\n"; ?>
function onFontPairChange(val) {
  var cf = document.getElementById('custom-fonts');
  var hf = document.getElementById('heading-font');
  var bf = document.getElementById('body-font');
  if (val === 'Custom' || !fontPairs[val] || !fontPairs[val].heading) {
    cf.style.display = 'grid';
    hf.value = ''; bf.value = '';
  } else {
    cf.style.display = 'none';
    hf.value = fontPairs[val].heading;
    bf.value = fontPairs[val].body;
  }
}
</script>

<!-- ══════════════════════════════════════════════════════════════════════════
     STEP 7 — Review & Generate
══════════════════════════════════════════════════════════════════════════ -->
<?php elseif ($step === 7):
  $clientRow  = fetchOne("SELECT * FROM clients WHERE id = ?", [$proj['client_id']]);
  $aiProvider = $studio['ai_provider'] ?? 'deepseek';
  $hasKey     = $aiProvider === 'deepseek'
      ? !empty($studio['deepseek_api_key'])
      : !empty(ANTHROPIC_API_KEY);
?>

<!-- Two-column: summary left, AI result right -->
<div style="display:grid;grid-template-columns:320px 1fr;gap:24px;align-items:start;">

  <!-- Left: Summary card -->
  <div style="display:flex;flex-direction:column;gap:16px;">
    <div class="card">
      <h2 class="card-title" style="font-size:14px;">Spec Summary</h2>

      <?php if ($spec['logo_url'] ?? ''): ?>
      <img src="<?= e($spec['logo_url']) ?>" style="height:36px;max-width:120px;object-fit:contain;margin-bottom:12px;" onerror="this.style.display='none'">
      <?php endif; ?>

      <div style="font-weight:700;font-size:15px;margin-bottom:2px;"><?= e($spec['business_name'] ?? '—') ?></div>
      <?php if ($spec['tagline'] ?? ''): ?>
      <div style="font-size:11px;color:var(--text2);font-style:italic;margin-bottom:10px;">"<?= e($spec['tagline']) ?>"</div>
      <?php endif; ?>

      <?php
      $summaryRows = [
        'Industry'   => $spec['industry']      ?? '',
        'Pages'      => count($pages) . ' pages',
        'Services'   => count($services) . ' services',
        'Style'      => $spec['brand_style']   ?? '',
        'Fonts'      => ($spec['heading_font'] ?? '') . ($spec['body_font'] ? ' + ' . $spec['body_font'] : ''),
      ];
      foreach ($summaryRows as $lbl => $val): if (!trim($val)) continue; ?>
      <div style="display:flex;justify-content:space-between;padding:5px 0;border-bottom:1px solid var(--border);font-size:12px;">
        <span style="color:var(--text2)"><?= $lbl ?></span>
        <span style="font-weight:500;text-align:right;"><?= e($val) ?></span>
      </div>
      <?php endforeach; ?>

      <!-- Color swatches -->
      <?php if ($spec['primary_color'] ?? ''): ?>
      <div style="margin-top:12px;margin-bottom:4px;font-size:11px;color:var(--text2);font-weight:600;text-transform:uppercase;letter-spacing:1px;">Colors</div>
      <div style="display:flex;gap:6px;">
        <?php foreach (['primary_color','secondary_color','accent_color'] as $col): ?>
        <div title="<?= e($spec[$col] ?? '') ?>"
             style="width:28px;height:28px;border-radius:50%;background:<?= e($spec[$col] ?? '#ccc') ?>;border:1px solid var(--border);"></div>
        <?php endforeach; ?>
        <div style="font-size:11px;color:var(--text2);align-self:center;margin-left:4px;"><?= e($spec['color_mood'] ?? '') ?></div>
      </div>
      <?php endif; ?>
    </div>

    <!-- Generate button -->
    <div class="card">
      <h2 class="card-title" style="font-size:14px;">Generate Specification</h2>
      <?php if (!$hasKey): ?>
      <div class="flash flash-error" style="font-size:12px;">
        No <?= $aiProvider === 'deepseek' ? 'DeepSeek' : 'Anthropic' ?> API key set.
        <a href="<?= APP_URL ?>/admin.php?tab=ai" style="color:var(--accent2)">Add one in AI Settings →</a>
      </div>
      <?php else: ?>
      <p style="font-size:12px;color:var(--text2);margin-bottom:14px;">
        AI Provider: <strong><?= $aiProvider === 'deepseek' ? '🟢 DeepSeek (free)' : '🔵 Anthropic Claude' ?></strong><br>
        This will generate a ~1,500 word professional specification document.
        <?= $spec['ai_spec'] ? 'A previous version exists — click to regenerate.' : '' ?>
      </p>
      <form method="POST">
        <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
        <input type="hidden" name="action" value="generate_spec">
        <button class="btn btn-ai" type="submit" id="gen-spec-btn" onclick="showSpecSpinner()">
          <svg viewBox="0 0 24 24" style="width:16px;height:16px"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/></svg>
          <?= $spec['ai_spec'] ? 'Regenerate Spec' : 'Generate with AI' ?>
        </button>
      </form>
      <div class="ai-spinner" id="spec-spinner" style="margin-top:12px;">
        <div class="spinner"></div> Generating — this takes ~20 seconds…
      </div>
      <?php endif; ?>
    </div>

    <!-- PDF download -->
    <?php if ($spec['ai_spec'] ?? ''): ?>
    <div class="card">
      <h2 class="card-title" style="font-size:14px;">Export</h2>
      <a href="<?= APP_URL ?>/website-spec-pdf.php?id=<?= $id ?>" target="_blank" class="btn btn-primary" style="width:100%;justify-content:center;">
        ⬇ Download Branded PDF
      </a>
      <div style="font-size:11px;color:var(--text2);margin-top:8px;text-align:center;">
        Generated <?= $spec['generated_at'] ? formatDate($spec['generated_at']) : '' ?>
      </div>
    </div>
    <?php endif; ?>

    <a href="?id=<?= $id ?>&step=6" class="btn btn-ghost" style="text-align:center;">← Back to Step 6</a>
  </div>

  <!-- Right: AI spec content -->
  <div>
    <?php if ($spec['ai_spec'] ?? ''): ?>
    <div class="card">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
        <h2 class="card-title" style="margin:0">Generated Specification</h2>
        <span style="font-size:11px;color:var(--text2);">Powered by <?= $aiProvider === 'deepseek' ? 'DeepSeek' : 'Claude' ?></span>
      </div>
      <div class="brief-content"><?= markdownToHtml($spec['ai_spec']) ?></div>
    </div>
    <?php else: ?>
    <div class="empty-state" style="min-height:300px;">
      <div class="big-icon">📄</div>
      <h3>No specification yet</h3>
      <p>Complete all steps and click <strong>Generate with AI</strong> to create your branded website specification document.</p>
    </div>
    <?php endif; ?>
  </div>
</div>

<script>
function showSpecSpinner() {
  document.getElementById('spec-spinner').classList.add('visible');
  document.getElementById('gen-spec-btn').disabled = true;
}
</script>
<?php endif; ?>

<?php renderFooter(); ?>
