// Shared project-builder logic — steps, decision engine, localStorage helpers.
// No UI. Loaded before chrome.jsx on every page so the drawer has what it needs.

const PB_STEPS = [
  {
    key: 'stage', label: 'Stage',
    head: 'Where is your business right now?',
    sub: "Honest answer. We won't judge.",
    choices: [
      { v: 'starting', icon: 'Sparkle', name: 'Just starting',  desc: 'Pre-launch or first year. No site yet, or a placeholder.' },
      { v: 'small',    icon: 'Home',    name: '1–5 employees',   desc: 'Established, mostly word-of-mouth, ready to be more findable.' },
      { v: 'growing',  icon: 'Trend',   name: '5–25 employees',  desc: 'Already getting leads but operations feel duct-taped together.' },
      { v: 'mature',   icon: 'Cog',     name: 'Mature, scaling', desc: "$1M+ revenue, the bottleneck is now the owner's time." },
    ],
  },
  {
    key: 'goal', label: 'Goal',
    head: "What's the main thing you want this to fix?",
    sub: 'Pick the one that keeps you up at night the most.',
    choices: [
      { v: 'credible', icon: 'Eye',    name: 'A credible presence',    desc: "I just need a site that doesn't make me look unprofessional." },
      { v: 'leads',    icon: 'Target', name: 'More qualified leads',   desc: "My website needs to actually bring people in. Right now it doesn't." },
      { v: 'ops',      icon: 'Link',   name: 'Less operational chaos', desc: 'Too many tools. Leads die in inboxes. Quotes get lost.' },
      { v: 'time',     icon: 'Clock',  name: 'My time back',           desc: "I'm doing too many things that shouldn't need a human anymore." },
      { v: 'oneoff',   icon: 'Cube',   name: 'A one-off project',      desc: 'I have a specific build in mind, fixed scope and timeline.' },
    ],
  },
  {
    key: 'site', label: 'Current site',
    head: "What's your current website situation?",
    sub: "Be honest.. we've seen every flavor of bad website.",
    choices: [
      { v: 'none', icon: 'X',     name: "I don't have one",        desc: "Or it's a placeholder from a domain registrar." },
      { v: 'old',  icon: 'Clock', name: "I have one but it's old", desc: "Probably built 5+ years ago. Doesn't work on phones well." },
      { v: 'ok',   icon: 'Check', name: "It's okay, just not earning", desc: "Decent design but not bringing in calls or leads." },
      { v: 'good', icon: 'Star',  name: "It's good and I like it",  desc: "I just need the other layers.. CRM, automation, etc." },
    ],
  },
  {
    key: 'pace', label: 'Pace',
    head: 'How fast do you need to move?',
    sub: "Some packages take longer. We'll be honest about it.",
    choices: [
      { v: 'soon', icon: 'Bolt',     name: 'Within a month', desc: 'I have a hard reason to launch soon (event, season, deadline).' },
      { v: 'qtr',  icon: 'Calendar', name: 'Next quarter',   desc: "Standard pace. Foundation's 2-3 weeks; Growth's 6-8." },
      { v: 'flex', icon: 'Compass',  name: "I'm flexible",   desc: "Whatever's right for the project. I don't want to rush it." },
    ],
  },
  {
    key: 'extras', label: 'Extras',
    head: "Anything else that's relevant?",
    sub: "Pick all that apply. These shape what we'd recommend.",
    multi: true,
    choices: [
      { v: 'crm',   icon: 'Database', name: 'Want a CRM',        desc: "You're ready to track leads + customers in one place." },
      { v: 'blog',  icon: 'Pen',      name: 'Want a blog',        desc: 'Content + ongoing SEO are part of the plan.' },
      { v: 'ai',    icon: 'Bolt',     name: 'Want AI/automation', desc: 'Custom GPTs, agent workflows, automation builds.' },
      { v: 'dash',  icon: 'Chart',    name: 'Want a dashboard',   desc: 'Custom reporting with metrics that matter to you.' },
      { v: 'email', icon: 'Mail',     name: 'Need email setup',   desc: 'Google Workspace or Microsoft 365 for the team.' },
      { v: 'none',  icon: 'X',        name: 'None of the above',  desc: 'Just the website piece, thanks.' },
    ],
  },
];

const PACKAGE_TIERS  = ['foundation', 'growth', 'operation', 'automation', 'custom'];
const PACKAGE_LABELS = { foundation: 'Foundation', growth: 'Growth', operation: 'Operation', automation: 'Automation', custom: 'Custom Build' };
const PACKAGE_PRICES = {
  foundation: 'A real custom site, built without templates. Mobile-ready and optimized from day one.',
  growth:     'Rank higher. Get found. More calls every month.',
  operation:  'Wire your site into your whole business.',
  automation: 'Get hours back. Automate what shouldn\'t need a human.',
  custom:     'Fixed scope. Fixed price. No surprises.',
};

const SOCIAL_PROOF = {
  foundation: 'Addison Excavations went from no web presence to their first qualified lead in 6 weeks.',
  growth:     'Clean Machines reached page-one local rankings in under 4 months.',
  operation:  'K&W Construction cut admin time by 40% after wiring in their CRM.',
  automation: 'One client recovered nine hours a week after their first automation build.',
  custom:     'Every custom build starts with a discovery call — no guesswork, no scope surprises.',
};

function getRecommendation(answers) {
  const { stage, goal, site, extras = [] } = answers;
  if (goal === 'oneoff') return {
    pkg: 'Custom Build', slug: 'custom',
    blurb: "Sounds like a fixed-scope project. We'd treat this as a Custom Build: discovery, design, development, launch.. at a fixed price with a clear timeline. Pricing depends on scope; we'd estimate after a 30-min discovery call.",
    next: ['Discovery call', 'Sitemap + scope', 'Fixed-price proposal'],
  };
  if (goal === 'time' || extras.includes('ai')) return {
    pkg: 'Automation', slug: 'automation',
    blurb: "You're talking about getting hours back, which is what the Automation tier is built for. We'd start with an operations audit (most clients enter Automation through Operation first), then build workflows that map to processes you already do manually.",
    next: ['Ops audit', 'Workflow map', 'First automation in 30 days'],
  };
  if (goal === 'ops' || extras.includes('crm') || extras.includes('email') || extras.includes('dash')) return {
    pkg: 'Operation', slug: 'operation',
    blurb: "CRM, dashboards, integrations.. Operation is where we wire the website into the rest of the business. If you don't already have a Growth site running, we'd recommend layering Growth + Operation together.",
    next: ['Tool audit', 'CRM recommendation', '90-day rollout'],
  };
  if (goal === 'leads' || site === 'ok' || stage === 'growing' || extras.includes('blog')) return {
    pkg: 'Growth', slug: 'growth',
    blurb: "You're ready for the website to actively earn its keep. Growth gives you multi-page custom build, dedicated service pages, full SEO, monthly content. Plus the year-one results guarantee in writing.",
    next: ['Keyword + competitor research', 'Multi-page custom design', 'SEO + content launch'],
  };
  return {
    pkg: 'Foundation', slug: 'foundation',
    blurb: "You don't need to overbuild. Foundation gives you a real custom one-page site, built without templates. Most clients stay here for years. About 30% step up to Growth when their business is ready for it.",
    next: ['Discovery call', 'Custom site in ~2 weeks', 'Month-to-month, cancel anytime'],
  };
}

// Best-guess recommendation from partial answers — drives the live panel
function getPartialRecommendation(answers) {
  const { goal, stage, site, extras = [] } = answers;
  if (!goal && !stage) return null;
  if (goal === 'oneoff') return 'custom';
  if (goal === 'time' || extras.includes('ai')) return 'automation';
  if (goal === 'ops' || extras.includes('crm') || extras.includes('email') || extras.includes('dash')) return 'operation';
  if (goal === 'leads' || site === 'ok' || stage === 'growing' || extras.includes('blog')) return 'growth';
  if (goal === 'credible' || stage === 'starting' || stage === 'small' || stage === 'mature') return 'foundation';
  return null;
}

const _LS_KEY = 'pda_builder_progress';
const _LS_TTL = 24 * 60 * 60 * 1000;

function loadProgress() {
  try {
    const raw = localStorage.getItem(_LS_KEY);
    if (!raw) return null;
    const d = JSON.parse(raw);
    if (Date.now() - d.ts > _LS_TTL) { localStorage.removeItem(_LS_KEY); return null; }
    return d;
  } catch (e) { return null; }
}

function saveProgress(answers, step) {
  try { localStorage.setItem(_LS_KEY, JSON.stringify({ answers, step, ts: Date.now() })); } catch (e) {}
}

function clearProgress() {
  try { localStorage.removeItem(_LS_KEY); } catch (e) {}
}

window.PDABuilderCore = {
  PB_STEPS, PACKAGE_TIERS, PACKAGE_LABELS, PACKAGE_PRICES, SOCIAL_PROOF,
  getRecommendation, getPartialRecommendation,
  loadProgress, saveProgress, clearProgress,
};
