/**
 * onboarding.mjs — First-run setup wizard
 * Shows a full-screen glassmorphic overlay guiding new users through initial configuration.
 * API key is optional — the app works out of the box via the hosted AI proxy.
 */

import store from '../store.mjs';
import api from '../api.mjs';

let overlay = null;
let currentStep = 0;
const state = {
  apiKey: '',
  provider: 'anthropic',
  personaName: 'AI-Do',
  avatarStyle: 'default',
  userName: ''
};

// ──────────────────────────────────────
// Public
// ──────────────────────────────────────

export function init() {
  const settings = store.getState().settings;
  if (settings.firstRun !== true) return;
  show();
}

/**
 * Show the onboarding wizard.
 * Can be called from settings to re-run the wizard.
 */
export function show() {
  if (overlay) return; // Already showing
  overlay = document.createElement('div');
  overlay.className = 'onboarding-overlay';
  overlay.setAttribute('role', 'dialog');
  overlay.setAttribute('aria-modal', 'true');
  overlay.setAttribute('aria-label', 'Setup Wizard');
  document.body.appendChild(overlay);
  renderStep(0);
}

// ──────────────────────────────────────
// Provider detection
// ──────────────────────────────────────

function detectProvider(key) {
  if (key.startsWith('sk-ant-')) return 'anthropic';
  if (key.startsWith('sk-')) return 'openai';
  if (key.startsWith('xai-')) return 'xai';
  return 'gemini';
}

const PROVIDER_LABELS = {
  anthropic: 'Anthropic Claude',
  openai: 'OpenAI GPT',
  xai: 'xAI Grok',
  gemini: 'Google Gemini'
};

// ──────────────────────────────────────
// Overlay lifecycle
// ──────────────────────────────────────

function dismiss() {
  if (!overlay) return;
  overlay.classList.add('onboarding-exit');
  setTimeout(() => {
    overlay?.remove();
    overlay = null;
  }, 400);
}

// ──────────────────────────────────────
// Step rendering
// ──────────────────────────────────────

function renderStep(step) {
  currentStep = step;
  overlay.innerHTML = '';

  const card = document.createElement('div');
  card.className = 'onboarding-card';

  // Step indicator dots
  const dots = document.createElement('div');
  dots.className = 'onboarding-dots';
  dots.setAttribute('aria-label', `Step ${step + 1} of 4`);
  for (let i = 0; i < 4; i++) {
    const dot = document.createElement('span');
    dot.className = 'onboarding-dot' + (i === step ? ' active' : '');
    dots.appendChild(dot);
  }

  const body = document.createElement('div');
  body.className = 'onboarding-body';

  if (step === 0) renderWelcome(body);
  else if (step === 1) renderApiKey(body);
  else if (step === 2) renderPersona(body);
  else if (step === 3) renderDone(body);

  card.appendChild(dots);
  card.appendChild(body);
  overlay.appendChild(card);

  // Trigger enter animation on next frame
  requestAnimationFrame(() => card.classList.add('onboarding-card-enter'));
}

// ── Step 1: Welcome ──

function renderWelcome(body) {
  body.innerHTML = `
    <div class="onboarding-avatar-hero" aria-hidden="true">
      <svg width="80" height="80" viewBox="0 0 100 100">
        <circle cx="50" cy="50" r="45" fill="var(--accent-primary)"/>
        <text x="50" y="64" font-size="42" text-anchor="middle" fill="white" font-family="system-ui" font-weight="600">A</text>
      </svg>
    </div>
    <h1 class="onboarding-title">Welcome to AI-Do!</h1>
    <p class="onboarding-desc">Your personal AI agent — always on, always learning.<br>Let's get you set up in under a minute.</p>
    <div class="onboarding-field">
      <label class="onboarding-label" for="ob-username">What should we call you?</label>
      <input class="onboarding-input" id="ob-username" type="text" placeholder="Your name" maxlength="60" autocomplete="name">
    </div>
    <button class="onboarding-btn-primary" id="ob-next">Get Started</button>
  `;
  const nameInput = body.querySelector('#ob-username');
  nameInput.value = state.userName;
  body.querySelector('#ob-next').addEventListener('click', () => {
    state.userName = nameInput.value.trim();
    renderStep(1);
  });
  nameInput.focus();
}

// ── Step 2: API Key (optional) ──

function renderApiKey(body) {
  body.innerHTML = `
    <h2 class="onboarding-title">Connect your AI</h2>
    <p class="onboarding-desc">AI-Do works right away with our hosted AI service.<br>
    For <strong>unlimited usage</strong>, paste your own API key below.</p>
    <div class="onboarding-field">
      <label class="onboarding-label" for="ob-apikey">API Key <span style="color: var(--text-tertiary); font-weight: normal;">(optional)</span></label>
      <input class="onboarding-input" id="ob-apikey" type="password"
        placeholder="sk-ant-…  /  sk-…  /  xai-…  /  AIza…"
        autocomplete="off" spellcheck="false">
      <span class="onboarding-hint" id="ob-provider-hint"></span>
    </div>
    <div class="onboarding-nav" style="display: flex; gap: var(--space-sm); justify-content: center; flex-wrap: wrap;">
      <button class="onboarding-btn-ghost" id="ob-back">Back</button>
      <button class="onboarding-btn-ghost" id="ob-skip" style="border: 1px solid var(--border-subtle);">Skip — use hosted AI</button>
      <button class="onboarding-btn-primary" id="ob-next">Continue</button>
    </div>
  `;

  const input = body.querySelector('#ob-apikey');
  const hint = body.querySelector('#ob-provider-hint');

  // Restore saved value
  input.value = state.apiKey;

  const updateHint = () => {
    const val = input.value.trim();
    if (!val) {
      hint.textContent = '';
      hint.className = 'onboarding-hint';
      return;
    }
    const p = detectProvider(val);
    hint.textContent = `Detected: ${PROVIDER_LABELS[p]}`;
    hint.className = 'onboarding-hint onboarding-hint-ok';
  };

  input.addEventListener('input', updateHint);
  updateHint();

  body.querySelector('#ob-back').addEventListener('click', () => renderStep(0));

  body.querySelector('#ob-skip').addEventListener('click', () => {
    state.apiKey = '';
    state.provider = 'anthropic';
    renderStep(2);
  });

  body.querySelector('#ob-next').addEventListener('click', () => {
    const val = input.value.trim();
    state.apiKey = val;
    state.provider = val ? detectProvider(val) : 'anthropic';
    renderStep(2);
  });

  input.focus();
}

// ── Step 3: Persona ──

function renderPersona(body) {
  const avatarStyles = ['default', 'friendly', 'professional', 'creative'];

  const avatarRadios = avatarStyles.map(s => `
    <label class="onboarding-avatar-option${s === state.avatarStyle ? ' selected' : ''}">
      <input type="radio" name="ob-avatar-style" value="${s}" ${s === state.avatarStyle ? 'checked' : ''}>
      <span>${s.charAt(0).toUpperCase() + s.slice(1)}</span>
    </label>
  `).join('');

  body.innerHTML = `
    <h2 class="onboarding-title">Customize your agent</h2>
    <p class="onboarding-desc">Give your agent a name and choose a personality style.</p>
    <div class="onboarding-field">
      <label class="onboarding-label" for="ob-name">Agent Name</label>
      <input class="onboarding-input" id="ob-name" type="text" placeholder="AI-Do" maxlength="40">
    </div>
    <div class="onboarding-field">
      <label class="onboarding-label">Avatar Style</label>
      <div class="onboarding-avatar-grid">${avatarRadios}</div>
    </div>
    <div class="onboarding-nav">
      <button class="onboarding-btn-ghost" id="ob-back">Back</button>
      <button class="onboarding-btn-primary" id="ob-next">Continue</button>
    </div>
  `;

  const nameInput = body.querySelector('#ob-name');
  nameInput.value = state.personaName;

  body.querySelectorAll('[name="ob-avatar-style"]').forEach(radio => {
    radio.addEventListener('change', () => {
      state.avatarStyle = radio.value;
      body.querySelectorAll('.onboarding-avatar-option').forEach(l => l.classList.remove('selected'));
      radio.closest('.onboarding-avatar-option').classList.add('selected');
    });
  });

  body.querySelector('#ob-back').addEventListener('click', () => renderStep(1));
  body.querySelector('#ob-next').addEventListener('click', () => {
    state.personaName = nameInput.value.trim() || 'AI-Do';
    renderStep(3);
  });

  nameInput.focus();
}

// ── Step 4: Done ──

function renderDone(body) {
  const modeText = state.apiKey
    ? `Using your ${PROVIDER_LABELS[state.provider]} API key.`
    : 'Using the hosted AI proxy. You can add your own API key in Settings anytime.';

  body.innerHTML = `
    <div class="onboarding-success-icon" aria-hidden="true">&#10003;</div>
    <h2 class="onboarding-title">You're all set!</h2>
    <p class="onboarding-desc" style="font-size: var(--font-size-sm); color: var(--text-secondary);">${modeText}</p>
    <p class="onboarding-desc">Here's what you can do with AI-Do:</p>
    <ul class="onboarding-tour">
      <li><span class="ob-icon">&#x1F4AC;</span><span><strong>Chat</strong> — send messages and get instant AI responses</span></li>
      <li><span class="ob-icon">&#x26A1;</span><span><strong>Skills</strong> — run automated tasks like research and writing</span></li>
      <li><span class="ob-icon">&#x1F9E0;</span><span><strong>Knowledge</strong> — ingest files and URLs into your agent's memory</span></li>
      <li><span class="ob-icon">&#x2699;&#xFE0F;</span><span><strong>Settings</strong> — fine-tune your agent at any time</span></li>
    </ul>
    <div class="onboarding-nav">
      <button class="onboarding-btn-ghost" id="ob-back">Back</button>
      <button class="onboarding-btn-primary" id="ob-finish">Start using AI-Do</button>
    </div>
  `;

  body.querySelector('#ob-back').addEventListener('click', () => renderStep(2));
  body.querySelector('#ob-finish').addEventListener('click', complete);
}

// ──────────────────────────────────────
// Completion
// ──────────────────────────────────────

async function complete() {
  const payload = {
    cli: 'gergy',
    persona: {
      name: state.personaName,
      avatarStyle: state.avatarStyle
    },
    firstRun: false
  };

  // Save user's name for personalization and usage tracking
  if (state.userName) {
    payload.userName = state.userName;
  }

  // Only set agentic config if user provided an API key
  if (state.apiKey) {
    payload.agentic = {
      provider: state.provider,
      apiKey: state.apiKey
    };
  }

  try {
    await api.updateConfig(payload);
    store.dispatch('SET_SETTINGS', { ...store.getState().settings, firstRun: false });
  } catch (err) {
    console.warn('[onboarding] Config save failed:', err.message);
  }

  dismiss();
}
