// frontend/src/components/onboarding/OnboardingWizard.jsx
// Apare automat după prima înregistrare.
// Ghidează clientul prin: profil brand → API keys (dacă BYOK) → nișă → primul run

import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext.jsx';
import { api } from '../../context/AuthContext.jsx';
import { useT } from '../../i18n/translations.js';
import {
  Sparkles, ChevronRight, ChevronLeft, Check,
  Target, Users, Zap, Key, ArrowRight, X
} from 'lucide-react';
import { clsx } from 'clsx';
import toast from 'react-hot-toast';

const TONES = [
  'Casual and conversational',
  'Professional and authoritative',
  'Educational and step-by-step',
  'Energetic and motivational',
  'Direct and no-nonsense',
  'Humorous and entertaining',
];

const PROVIDERS = [
  { id: 'claude',  name: 'Anthropic Claude',  models: ['claude-sonnet-4-5', 'claude-haiku-4-5-20251001', 'claude-opus-4-5'], placeholder: 'sk-ant-api03-...' },
  { id: 'openai',  name: 'OpenAI GPT',         models: ['gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo'], placeholder: 'sk-...' },
  { id: 'gemini',  name: 'Google Gemini',       models: ['gemini-1.5-pro', 'gemini-1.5-flash'], placeholder: 'AIzaSy...' },
];

export default function OnboardingWizard({ onComplete }) {
  const { user, refreshUser } = useAuth();
  const navigate = useNavigate();
  const t = useT(user?.locale);

  const isByok = user?.plan?.byok;
  const steps = isByok
    ? ['welcome', 'brand', 'apikeys', 'niche', 'done']
    : ['welcome', 'brand', 'niche', 'done'];

  const [step, setStep] = useState(0);
  const [saving, setSaving] = useState(false);
  const [skipped, setSkipped] = useState(false);

  const [brand, setBrand] = useState({
    niche: '', brandName: '', targetAudience: '',
    tone: '', writingStyle: '', avoidWords: '', cta: '',
  });

  const [apiKey, setApiKey] = useState({ provider: 'claude', key: '', model: 'claude-sonnet-4-5' });
  const [keyTested, setKeyTested] = useState(null);
  const [testing, setTesting] = useState(false);

  const currentStep = steps[step];
  const isLast = step === steps.length - 1;
  const isFirst = step === 0;
  const progress = Math.round((step / (steps.length - 1)) * 100);

  const next = () => setStep(s => Math.min(s + 1, steps.length - 1));
  const prev = () => setStep(s => Math.max(s - 1, 0));

  const saveBrand = async () => {
    if (!brand.niche.trim()) { toast.error('Please enter your niche'); return false; }
    setSaving(true);
    try {
      await api.put('/profile', {
        niche: brand.niche,
        brandName: brand.brandName,
        targetAudience: brand.targetAudience,
        tone: brand.tone,
        writingStyle: brand.writingStyle,
        avoidWords: brand.avoidWords.split(',').map(w => w.trim()).filter(Boolean),
        cta: brand.cta,
      });
      return true;
    } catch { toast.error('Save failed. Try again.'); return false; }
    finally { setSaving(false); }
  };

  const testAndSaveKey = async () => {
    if (!apiKey.key.trim()) { toast.error('Enter your API key'); return; }
    setTesting(true);
    setKeyTested(null);
    try {
      const { data } = await api.put(`/profile/api-keys/${apiKey.provider}`, {
        apiKey: apiKey.key,
        model: apiKey.model,
      });
      setKeyTested(data.valid ? 'valid' : 'invalid');
      if (data.valid) toast.success('Key saved and verified ✓');
      else toast.error(`Key saved but test failed: ${data.error}`);
    } catch { toast.error('Failed to save key'); setKeyTested('invalid'); }
    finally { setTesting(false); }
  };

  const handleNext = async () => {
    if (currentStep === 'brand') {
      const ok = await saveBrand();
      if (!ok) return;
    }
    if (isLast) {
      await refreshUser();
      onComplete();
      navigate('/dashboard/niche');
      return;
    }
    next();
  };

  const handleSkip = async () => {
    // Mark onboarding as done even if skipped
    await refreshUser();
    onComplete();
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 9999,
      background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '16px',
    }}>
      <div style={{
        background: 'var(--color-background-primary)',
        borderRadius: '20px',
        border: '0.5px solid var(--color-border-tertiary)',
        width: '100%', maxWidth: '520px',
        overflow: 'hidden',
        position: 'relative',
      }}>
        {/* Progress bar */}
        <div style={{ height: '3px', background: 'var(--color-background-secondary)' }}>
          <div style={{
            height: '100%',
            width: `${progress}%`,
            background: 'var(--color-text-info)',
            transition: 'width 0.4s ease',
          }} />
        </div>

        {/* Header */}
        <div style={{ padding: '28px 32px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
            <div style={{
              width: '32px', height: '32px',
              background: 'var(--color-background-info)',
              borderRadius: '8px',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Sparkles size={15} color="var(--color-text-info)" />
            </div>
            <span style={{ fontWeight: '500', fontSize: '15px', color: 'var(--color-text-primary)' }}>
              Content Machine
            </span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
            <span style={{ fontSize: '12px', color: 'var(--color-text-tertiary)', fontFamily: 'var(--font-mono)' }}>
              {step + 1} / {steps.length}
            </span>
            <button
              onClick={handleSkip}
              style={{ color: 'var(--color-text-tertiary)', fontSize: '13px', padding: '4px 8px', borderRadius: '6px' }}
            >
              Skip setup
            </button>
          </div>
        </div>

        {/* Step dots */}
        <div style={{ display: 'flex', gap: '6px', padding: '16px 32px 0' }}>
          {steps.map((_, i) => (
            <div key={i} style={{
              height: '3px', flex: 1, borderRadius: '2px',
              background: i <= step ? 'var(--color-text-info)' : 'var(--color-background-secondary)',
              transition: 'background 0.3s',
            }} />
          ))}
        </div>

        {/* Content */}
        <div style={{ padding: '28px 32px 32px' }}>
          {currentStep === 'welcome' && <StepWelcome user={user} isByok={isByok} />}
          {currentStep === 'brand'   && <StepBrand brand={brand} setBrand={setBrand} tones={TONES} />}
          {currentStep === 'apikeys' && (
            <StepApiKeys
              apiKey={apiKey}
              setApiKey={setApiKey}
              providers={PROVIDERS}
              onTest={testAndSaveKey}
              testing={testing}
              keyTested={keyTested}
            />
          )}
          {currentStep === 'niche'   && <StepNicheIntro />}
          {currentStep === 'done'    && <StepDone user={user} />}

          {/* Navigation */}
          <div style={{ display: 'flex', gap: '10px', marginTop: '28px', justifyContent: 'space-between' }}>
            {!isFirst ? (
              <button
                onClick={prev}
                style={{
                  padding: '10px 18px', borderRadius: '10px',
                  border: '0.5px solid var(--color-border-secondary)',
                  fontSize: '14px', fontWeight: '500',
                  color: 'var(--color-text-secondary)',
                  display: 'flex', alignItems: 'center', gap: '6px',
                }}
              >
                <ChevronLeft size={15} /> Back
              </button>
            ) : <div />}

            <button
              onClick={handleNext}
              disabled={saving}
              style={{
                padding: '12px 24px', borderRadius: '10px',
                background: 'var(--color-text-info)',
                color: 'white', fontSize: '15px', fontWeight: '500',
                display: 'flex', alignItems: 'center', gap: '8px',
                opacity: saving ? 0.6 : 1,
              }}
            >
              {saving ? 'Saving…' : isLast ? (
                <><Check size={16} /> Start creating</>
              ) : (
                <>Continue <ChevronRight size={16} /></>
              )}
            </button>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes fadeIn { from { opacity:0; transform:translateY(12px); } to { opacity:1; transform:translateY(0); } }
        .onboard-step { animation: fadeIn 0.35s cubic-bezier(0.16,1,0.3,1); }
        .onboard-input {
          width: 100%; padding: 10px 14px; font-size: 15px; font-family: inherit;
          border: 0.5px solid var(--color-border-secondary); border-radius: 10px;
          background: var(--color-background-secondary); color: var(--color-text-primary);
          outline: none; box-sizing: border-box;
        }
        .onboard-input:focus { border-color: var(--color-border-info); box-shadow: 0 0 0 3px rgba(25,118,210,0.08); }
        .onboard-label { font-size: 13px; font-weight: 500; color: var(--color-text-secondary); margin-bottom: 6px; display: block; }
        .onboard-field { margin-bottom: 16px; }
        .tone-btn {
          padding: 8px 14px; border-radius: 8px; font-size: 13px; font-family: inherit;
          border: 0.5px solid var(--color-border-tertiary); cursor: pointer;
          background: var(--color-background-primary); color: var(--color-text-secondary);
          transition: all 0.15s;
        }
        .tone-btn.active {
          border-color: var(--color-border-info); background: var(--color-background-info);
          color: var(--color-text-info); font-weight: 500;
        }
      `}</style>
    </div>
  );
}

// ─── STEP: Welcome ─────────────────────────────────────────────────────────
function StepWelcome({ user, isByok }) {
  return (
    <div className="onboard-step">
      <div style={{ fontSize: '40px', marginBottom: '16px' }}>👋</div>
      <h2 style={{ fontSize: '22px', fontWeight: '500', marginBottom: '10px', color: 'var(--color-text-primary)' }}>
        Welcome, {user?.fullName?.split(' ')[0]}!
      </h2>
      <p style={{ fontSize: '15px', color: 'var(--color-text-secondary)', lineHeight: '1.6', marginBottom: '20px' }}>
        Your 14-day trial has started. Let's set up your content pipeline in the next 3 minutes.
      </p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
        {[
          { icon: '🎯', text: 'Tell us about your brand & audience' },
          ...(isByok ? [{ icon: '🔑', text: 'Connect your AI API key' }] : []),
          { icon: '📍', text: 'Define your content niche precisely' },
          { icon: '🚀', text: 'Run your first pipeline in 8 minutes' },
        ].map((item, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: '12px',
            padding: '12px 16px', borderRadius: '10px',
            background: 'var(--color-background-secondary)',
            border: '0.5px solid var(--color-border-tertiary)',
          }}>
            <span style={{ fontSize: '18px' }}>{item.icon}</span>
            <span style={{ fontSize: '14px', color: 'var(--color-text-primary)' }}>{item.text}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── STEP: Brand Profile ────────────────────────────────────────────────────
function StepBrand({ brand, setBrand, tones }) {
  const set = (k) => (e) => setBrand(b => ({ ...b, [k]: e.target.value }));
  return (
    <div className="onboard-step">
      <h2 style={{ fontSize: '20px', fontWeight: '500', marginBottom: '6px', color: 'var(--color-text-primary)' }}>
        Your brand voice
      </h2>
      <p style={{ fontSize: '14px', color: 'var(--color-text-secondary)', marginBottom: '20px', lineHeight: '1.5' }}>
        This is how the AI learns to write in <em>your</em> style.
      </p>

      <div className="onboard-field">
        <label className="onboard-label">Your niche <span style={{ color: 'var(--color-text-danger)' }}>*</span></label>
        <input className="onboard-input" value={brand.niche} onChange={set('niche')}
          placeholder="e.g. fitness coaching for busy moms over 35" />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
        <div className="onboard-field">
          <label className="onboard-label">Brand / channel name</label>
          <input className="onboard-input" value={brand.brandName} onChange={set('brandName')}
            placeholder="e.g. Strong Mom" />
        </div>
        <div className="onboard-field">
          <label className="onboard-label">Call to action</label>
          <input className="onboard-input" value={brand.cta} onChange={set('cta')}
            placeholder="e.g. Subscribe for weekly tips" />
        </div>
      </div>

      <div className="onboard-field">
        <label className="onboard-label">Target audience</label>
        <input className="onboard-input" value={brand.targetAudience} onChange={set('targetAudience')}
          placeholder="e.g. women aged 30-45 who want to lose weight while raising kids" />
      </div>

      <div className="onboard-field">
        <label className="onboard-label">Content tone</label>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', marginTop: '6px' }}>
          {tones.map(tone => (
            <button key={tone} className={clsx('tone-btn', brand.tone === tone && 'active')}
              onClick={() => setBrand(b => ({ ...b, tone }))}>
              {tone}
            </button>
          ))}
        </div>
      </div>

      <div className="onboard-field">
        <label className="onboard-label">Words / phrases to avoid <span style={{ fontSize: '12px', fontWeight: 400 }}>(comma-separated)</span></label>
        <input className="onboard-input" value={brand.avoidWords} onChange={set('avoidWords')}
          placeholder="e.g. leverage, synergy, game-changer, hustle" />
      </div>
    </div>
  );
}

// ─── STEP: API Keys (BYOK only) ─────────────────────────────────────────────
function StepApiKeys({ apiKey, setApiKey, providers, onTest, testing, keyTested }) {
  const selected = providers.find(p => p.id === apiKey.provider);
  return (
    <div className="onboard-step">
      <h2 style={{ fontSize: '20px', fontWeight: '500', marginBottom: '6px', color: 'var(--color-text-primary)' }}>
        Connect your AI
      </h2>
      <p style={{ fontSize: '14px', color: 'var(--color-text-secondary)', marginBottom: '20px', lineHeight: '1.5' }}>
        Your Pro plan uses your own API key. Keys are encrypted with AES-256 and never shared.
      </p>

      {/* Provider selector */}
      <div className="onboard-field">
        <label className="onboard-label">AI Provider</label>
        <div style={{ display: 'flex', gap: '8px' }}>
          {providers.map(p => (
            <button key={p.id}
              onClick={() => setApiKey(k => ({ ...k, provider: p.id, key: '', model: p.models[0] }))}
              style={{
                flex: 1, padding: '10px 8px', borderRadius: '10px', fontSize: '13px',
                fontWeight: apiKey.provider === p.id ? '500' : '400',
                border: apiKey.provider === p.id
                  ? '1.5px solid var(--color-border-info)'
                  : '0.5px solid var(--color-border-tertiary)',
                background: apiKey.provider === p.id
                  ? 'var(--color-background-info)'
                  : 'var(--color-background-secondary)',
                color: apiKey.provider === p.id
                  ? 'var(--color-text-info)'
                  : 'var(--color-text-secondary)',
                cursor: 'pointer',
              }}>
              {p.name}
            </button>
          ))}
        </div>
      </div>

      {/* Model selector */}
      <div className="onboard-field">
        <label className="onboard-label">Model</label>
        <select className="onboard-input"
          value={apiKey.model}
          onChange={e => setApiKey(k => ({ ...k, model: e.target.value }))}>
          {selected?.models.map(m => <option key={m} value={m}>{m}</option>)}
        </select>
      </div>

      {/* API Key input */}
      <div className="onboard-field">
        <label className="onboard-label">API Key</label>
        <div style={{ display: 'flex', gap: '8px' }}>
          <input className="onboard-input" type="password"
            value={apiKey.key}
            onChange={e => setApiKey(k => ({ ...k, key: e.target.value }))}
            placeholder={selected?.placeholder}
            style={{ flex: 1 }}
          />
          <button onClick={onTest} disabled={testing || !apiKey.key.trim()} style={{
            padding: '10px 16px', borderRadius: '10px', fontSize: '13px', fontWeight: '500',
            background: 'var(--color-background-secondary)',
            border: '0.5px solid var(--color-border-secondary)',
            color: 'var(--color-text-primary)', whiteSpace: 'nowrap',
            opacity: (testing || !apiKey.key.trim()) ? 0.5 : 1,
          }}>
            {testing ? 'Testing…' : 'Test & Save'}
          </button>
        </div>
      </div>

      {keyTested === 'valid' && (
        <div style={{
          display: 'flex', alignItems: 'center', gap: '8px',
          padding: '10px 14px', borderRadius: '10px',
          background: 'var(--color-background-success)',
          border: '0.5px solid var(--color-border-success)',
          color: 'var(--color-text-success)', fontSize: '14px',
        }}>
          <Check size={16} /> Connection verified ✓
        </div>
      )}
      {keyTested === 'invalid' && (
        <div style={{
          padding: '10px 14px', borderRadius: '10px',
          background: 'var(--color-background-danger)',
          border: '0.5px solid var(--color-border-danger)',
          color: 'var(--color-text-danger)', fontSize: '14px',
        }}>
          Key saved but connection failed. Check the key and try again.
        </div>
      )}

      <p style={{ fontSize: '12px', color: 'var(--color-text-tertiary)', marginTop: '12px' }}>
        Get your key: {' '}
        <a href="https://console.anthropic.com" target="_blank" style={{ color: 'var(--color-text-info)' }}>Anthropic</a> ·{' '}
        <a href="https://platform.openai.com" target="_blank" style={{ color: 'var(--color-text-info)' }}>OpenAI</a> ·{' '}
        <a href="https://aistudio.google.com" target="_blank" style={{ color: 'var(--color-text-info)' }}>Google</a>
      </p>
    </div>
  );
}

// ─── STEP: Niche intro ──────────────────────────────────────────────────────
function StepNicheIntro() {
  return (
    <div className="onboard-step">
      <div style={{ fontSize: '40px', marginBottom: '16px' }}>🎯</div>
      <h2 style={{ fontSize: '20px', fontWeight: '500', marginBottom: '10px', color: 'var(--color-text-primary)' }}>
        Now let's define your niche
      </h2>
      <p style={{ fontSize: '15px', color: 'var(--color-text-secondary)', lineHeight: '1.6', marginBottom: '20px' }}>
        The Niche Builder takes 2 minutes and makes all the difference. The more specific you are about your audience, the better the AI-generated content.
      </p>
      <div style={{ padding: '16px', borderRadius: '12px', background: 'var(--color-background-secondary)', border: '0.5px solid var(--color-border-tertiary)' }}>
        <p style={{ fontSize: '14px', color: 'var(--color-text-secondary)', margin: '0 0 8px', fontWeight: '500' }}>What you'll define:</p>
        {['Industry & sub-niche (be very specific)', 'Audience: age, goals, pain points', 'Content platforms & formats', 'Seed keywords for trend scanning'].map((item, i) => (
          <div key={i} style={{ display: 'flex', gap: '10px', marginBottom: '6px', fontSize: '14px', color: 'var(--color-text-primary)' }}>
            <span style={{ color: 'var(--color-text-success)', fontWeight: '500' }}>✓</span>
            {item}
          </div>
        ))}
      </div>
      <p style={{ fontSize: '13px', color: 'var(--color-text-tertiary)', marginTop: '14px' }}>
        After this step, we'll open the Niche Builder where you can create multiple niches and switch between them.
      </p>
    </div>
  );
}

// ─── STEP: Done ─────────────────────────────────────────────────────────────
function StepDone({ user }) {
  return (
    <div className="onboard-step" style={{ textAlign: 'center', paddingTop: '8px' }}>
      <div style={{
        width: '64px', height: '64px', margin: '0 auto 20px',
        background: 'var(--color-background-success)',
        borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Check size={28} color="var(--color-text-success)" strokeWidth={2.5} />
      </div>
      <h2 style={{ fontSize: '22px', fontWeight: '500', marginBottom: '10px', color: 'var(--color-text-primary)' }}>
        You're all set!
      </h2>
      <p style={{ fontSize: '15px', color: 'var(--color-text-secondary)', lineHeight: '1.6', marginBottom: '24px' }}>
        Your pipeline is ready. Next: create your first niche profile and generate topics for approval.
      </p>
      <div style={{
        padding: '16px', borderRadius: '12px',
        background: 'var(--color-background-info)', border: '0.5px solid var(--color-border-info)',
        fontSize: '14px', color: 'var(--color-text-info)', lineHeight: '1.5',
      }}>
        🚀 Your first batch of content will be ready in <strong>~8 minutes</strong> after you run the pipeline.
      </div>
    </div>
  );
}
