'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { ArrowLeft, Save, Eye, Globe, Clock, Tag, User, Image as ImageIcon, Plus, X, Info, Search, List, Quote } from 'lucide-react';
import { useLanguage } from '@client/contexts/LanguageContext';
import { usePageHeader } from '@client/contexts/PageHeaderContext';

interface BlogEditorProps {
  isEdit?: boolean;
}

interface ContentBlock {
  id: string;
  type: 'paragraph' | 'heading2' | 'heading3' | 'callout' | 'teal-callout' | 'stats-grid' | 'step-list' | 'blockquote' | 'faq-list' | 'tags-list';
  content: string;
}

function getCategories(t: (k: string, f: string) => string) {
  return [
    t('blog.categories.aiFeatures', 'AI Features'),
    t('blog.categories.aiTechnology', 'AI & Technology'),
    t('blog.categories.caseStudies', 'Case Studies'),
    t('blog.categories.restaurantOps', 'Restaurant Operations'),
    t('blog.categories.customerExp', 'Customer Experience'),
    t('blog.categories.productUpdates', 'Product Updates'),
  ];
}

function getBlockTypeLabels(t: (k: string, f: string) => string): Record<ContentBlock['type'], string> {
  return {
    paragraph: t('blog.blocks.paragraph', 'Paragraph'),
    heading2: t('blog.blocks.heading2', 'Heading 2'),
    heading3: t('blog.blocks.heading3', 'Heading 3'),
    callout: t('blog.blocks.calloutOrange', 'Callout Box (Orange)'),
    'teal-callout': t('blog.blocks.calloutTeal', 'Callout Box (Teal)'),
    'stats-grid': t('blog.blocks.statsGrid', 'Stats Grid (3 cols)'),
    'step-list': t('blog.blocks.stepList', 'Step List'),
    blockquote: t('blog.blocks.blockquote', 'Blockquote'),
    'faq-list': t('blog.blocks.faqList', 'FAQ List'),
    'tags-list': t('blog.blocks.tagsList', 'Tags'),
  };
}

function getBlockTypePlaceholders(t: (k: string, f: string) => string): Record<ContentBlock['type'], string> {
  return {
    paragraph: t('blog.placeholders.paragraph', 'Write your paragraph here...'),
    heading2: t('blog.placeholders.heading2', 'Section heading...'),
    heading3: t('blog.placeholders.heading3', 'Sub-heading...'),
    callout: t('blog.placeholders.callout', 'Key Insight | Write your callout text here...'),
    'teal-callout': t('blog.placeholders.tealCallout', "What you'll need | Item 1\nItem 2\nItem 3"),
    'stats-grid': t('blog.placeholders.statsGrid', '23% | Calls missed during peak hours\n4.2min | Average hold time\n8.3% | Order error rate'),
    'step-list': t('blog.placeholders.stepList', '01 | Step title | Step description\n02 | Step title | Step description'),
    blockquote: t('blog.placeholders.blockquote', '"Quote text here" | Author Name | Author Title'),
    'faq-list': t('blog.placeholders.faqList', 'Question 1? | Answer 1\nQuestion 2? | Answer 2'),
    'tags-list': t('blog.placeholders.tagsList', 'AI Ordering, Restaurant Tech, Revenue Growth'),
  };
}

function generateId() {
  return Math.random().toString(36).slice(2, 9);
}

function slugify(text: string) {
  return text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
}

function calcReadTime(blocks: ContentBlock[]) {
  const words = blocks.map(b => b.content).join(' ').split(/\s+/).filter(Boolean).length;
  return Math.max(1, Math.ceil(words / 200));
}

export default function BlogEditorPage({ isEdit = false }: BlogEditorProps) {
  const { t } = useLanguage();
  const categories = getCategories(t);
  const blockTypeLabels = getBlockTypeLabels(t);
  const blockTypePlaceholders = getBlockTypePlaceholders(t);
  const [title, setTitle] = useState(isEdit ? t('admin.blog.sample.title', 'How AI Voice Ordering Helped 2,400+ Restaurants Capture Every Call') : '');
  usePageHeader(isEdit ? t('admin.blog.editPost', 'Edit Blog Post') : t('admin.blog.newPost', 'New Blog Post'), isEdit ? t('admin.blog.updateAndRepublish', 'Update and republish your post') : t('admin.blog.createANewBlogPost', 'Create a new blog post'));
  const [slug, setSlug] = useState(isEdit ? 'ai-voice-ordering-restaurants' : '');
  const [slugManual, setSlugManual] = useState(false);
  const [excerpt, setExcerpt] = useState(isEdit ? t('admin.blog.sample.excerpt', 'A deep dive into how AI-powered phone ordering is eliminating missed calls, reducing staff workload, and adding thousands in monthly revenue for restaurants of all sizes.') : '');
  const [category, setCategory] = useState(isEdit ? t('admin.blog.cat.aiFeatures', 'AI Features') : '');
  const [tags, setTags] = useState<string[]>(isEdit ? [t('admin.blog.sample.tag1', 'AI Ordering'), t('admin.blog.sample.tag2', 'Restaurant Tech'), t('admin.blog.sample.tag3', 'Revenue Growth')] : []);
  const [tagInput, setTagInput] = useState('');
  const [authorName, setAuthorName] = useState(isEdit ? t('admin.blog.sample.authorName', 'Alex Rivera') : '');
  const [authorBio, setAuthorBio] = useState(isEdit ? t('admin.blog.sample.authorBio', 'Alex has spent 8 years at the intersection of hospitality and technology. Before RestroAgent, he led product at two restaurant tech startups.') : '');
  const [authorInitials, setAuthorInitials] = useState(isEdit ? 'AR' : '');
  const [heroImageUrl, setHeroImageUrl] = useState('');
  const [heroImageAlt, setHeroImageAlt] = useState('');
  const [publishDate, setPublishDate] = useState('');
  const [status, setStatus] = useState<'draft' | 'published' | 'scheduled'>(isEdit ? 'published' : 'draft');
  const [metaTitle, setMetaTitle] = useState('');
  const [metaDesc, setMetaDesc] = useState('');
  const [activeTab, setActiveTab] = useState<'content' | 'seo' | 'preview'>('content');
  const [saved, setSaved] = useState(false);

  const [blocks, setBlocks] = useState<ContentBlock[]>(isEdit ? [
    { id: generateId(), type: 'paragraph', content: t('admin.blog.sample.block.intro', "Every restaurant owner knows the feeling: it's Friday night, the dining room is packed, the kitchen is firing on all cylinders — and the phone won't stop ringing. Your best server is stuck answering calls instead of serving tables. Orders get missed. Customers hang up frustrated. Revenue walks out the door.") },
    { id: generateId(), type: 'callout', content: t('admin.blog.sample.block.callout1', 'Key Insight | Restaurants using AI voice ordering report an average of zero missed calls during peak hours, compared to a 30-40% miss rate for manually-staffed phone lines.') },
    { id: generateId(), type: 'heading2', content: t('admin.blog.sample.block.h2problem', 'The Problem with Traditional Phone Orders') },
    { id: generateId(), type: 'paragraph', content: t('admin.blog.sample.block.problem', 'Traditional phone ordering creates a bottleneck that costs restaurants in three distinct ways: missed revenue from unanswered calls, reduced service quality when staff are pulled away from tables, and human error in order-taking.') },
    { id: generateId(), type: 'stats-grid', content: t('admin.blog.sample.block.stats', '23% | Calls missed during peak hours\n4.2min | Average hold time before hang-up\n8.3% | Order error rate (human)') },
    { id: generateId(), type: 'heading2', content: t('admin.blog.sample.block.h2how', 'How AI Voice Ordering Works') },
    { id: generateId(), type: 'step-list', content: t('admin.blog.sample.block.steps', '01 | Customer calls your number | The AI answers instantly — no hold music, no "please wait." It greets the customer using your restaurant\'s name and personality.\n02 | Natural conversation | The AI understands complex requests like "I\'d like the pasta but without mushrooms" — just like a human would.\n03 | Order confirmation | The AI reads back the complete order, confirms the total, and asks for payment or pickup/delivery details.\n04 | Instant kitchen notification | The confirmed order fires directly to your POS or kitchen display system. No manual entry, no errors.') },
    { id: generateId(), type: 'heading2', content: t('admin.blog.sample.block.h2results', 'Real-World Results') },
    { id: generateId(), type: 'blockquote', content: t('admin.blog.sample.block.quote', '"We went from missing 30% of phone orders during rush hour to zero missed calls. The ROI was clear within the first week." | Marco Rossi | Owner, Bella Napoli, New York') },
    { id: generateId(), type: 'heading2', content: t('admin.blog.sample.block.h2impl', 'Implementation Guide') },
    { id: generateId(), type: 'teal-callout', content: t('admin.blog.sample.block.callout2', "What you'll need to get started | Your current menu (PDF, image, or POS export)\nYour phone number (we handle the forwarding)\n15 minutes to review and approve the AI's responses\nOptional: POS integration credentials") },
    { id: generateId(), type: 'heading2', content: t('admin.blog.sample.block.h2concerns', 'Addressing Common Concerns') },
    { id: generateId(), type: 'faq-list', content: t('admin.blog.sample.block.faq', "Will customers know they're talking to an AI? | The AI is transparent about being an automated system when asked directly. However, most customers simply don't ask — they just want their order taken quickly.\nWhat about complex orders or complaints? | The AI handles modifications and special requests natively. For complaints, it escalates to a staff member in under 3 seconds.\nWhat if the AI makes a mistake? | The AI's order accuracy rate is 98.7% — significantly higher than the human average of 91.7%.") },
    { id: generateId(), type: 'heading2', content: t('admin.blog.sample.block.h2conclusion', 'Conclusion') },
    { id: generateId(), type: 'paragraph', content: t('admin.blog.sample.block.conclusion', 'AI voice ordering has moved from a novelty to a necessity for competitive restaurants. The data is clear: restaurants that adopt AI phone ordering capture more revenue, reduce staff stress, and deliver a better customer experience.') },
  ] : [{ id: generateId(), type: 'paragraph', content: '' }]);

  const readTime = calcReadTime(blocks);

  useEffect(() => {
    if (!slugManual && title) setSlug(slugify(title));
  }, [title, slugManual]);

  useEffect(() => {
    if (authorName && !isEdit) {
      setAuthorInitials(authorName.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2));
    }
  }, [authorName, isEdit]);

  const addBlock = (type: ContentBlock['type']) => {
    setBlocks(prev => [...prev, { id: generateId(), type, content: '' }]);
  };

  const updateBlock = (id: string, content: string) => {
    setBlocks(prev => prev.map(b => b.id === id ? { ...b, content } : b));
  };

  const removeBlock = (id: string) => {
    setBlocks(prev => prev.filter(b => b.id !== id));
  };

  const moveBlock = (id: string, dir: 'up' | 'down') => {
    setBlocks(prev => {
      const idx = prev.findIndex(b => b.id === id);
      if (dir === 'up' && idx === 0) return prev;
      if (dir === 'down' && idx === prev.length - 1) return prev;
      const next = [...prev];
      const swap = dir === 'up' ? idx - 1 : idx + 1;
      [next[idx], next[swap]] = [next[swap], next[idx]];
      return next;
    });
  };

  const addTag = () => {
    const t = tagInput.trim();
    if (t && !tags.includes(t)) setTags(prev => [...prev, t]);
    setTagInput('');
  };

  const handleSave = () => {
    setSaved(true);
    setTimeout(() => setSaved(false), 2500);
  };

  // Preview renderer
  const renderPreviewBlock = (block: ContentBlock) => {
    switch (block.type) {
      case 'paragraph':
        return <p key={block.id} className="text-base text-slate-600 dark:text-slate-400 leading-relaxed mb-5">{block.content}</p>;
      case 'heading2':
        return <h2 key={block.id} className="text-2xl sm:text-3xl font-bold text-slate-900 dark:text-white mb-4 mt-10">{block.content}</h2>;
      case 'heading3':
        return <h3 key={block.id} className="text-xl font-bold text-slate-900 dark:text-white mb-3 mt-6">{block.content}</h3>;
      case 'callout': {
        const [label, ...rest] = block.content.split(' | ');
        return (
          <div key={block.id} className="my-8 p-5 sm:p-6 rounded-2xl bg-orange-50 dark:bg-orange-950/30 border border-orange-100 dark:border-orange-900/50">
            <div className="flex items-start gap-3">
              <div className="w-8 h-8 rounded-lg bg-orange-100 dark:bg-orange-900/50 flex items-center justify-center flex-shrink-0 mt-0.5">
                <Info size={14} className="text-orange-500" />
              </div>
              <div>
                <p className="text-sm font-semibold text-orange-800 dark:text-orange-200 mb-1">{label}</p>
                <p className="text-sm text-orange-700 dark:text-orange-300 leading-relaxed">{rest.join(' | ')}</p>
              </div>
            </div>
          </div>
        );
      }
      case 'teal-callout': {
        const lines = block.content.split('\n');
        const [header, ...items] = lines;
        const [label, ...rest] = (header || '').split(' | ');
        const listItems = rest.length > 0 ? rest.join(' | ').split('\n') : items;
        return (
          <div key={block.id} className="my-6 p-5 sm:p-6 rounded-2xl bg-teal-50 dark:bg-teal-950/30 border border-teal-100 dark:border-teal-900/50">
            <h4 className="text-sm font-bold text-teal-800 dark:text-teal-200 mb-3">{label}</h4>
            <ul className="space-y-2">
              {listItems.map((item, i) => (
                <li key={i} className="flex items-start gap-2 text-sm text-teal-700 dark:text-teal-300">
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="text-teal-500 flex-shrink-0 mt-0.5"><polyline points="20 6 9 17 4 12"/></svg>
                  {item.trim()}
                </li>
              ))}
            </ul>
          </div>
        );
      }
      case 'stats-grid': {
        const stats = block.content.split('\n').map(line => { const [value, label] = line.split(' | '); return { value: value?.trim(), label: label?.trim() }; });
        const colors = ['text-red-500 bg-red-50 dark:bg-red-950/30 border-red-100 dark:border-red-900/50', 'text-amber-500 bg-amber-50 dark:bg-amber-950/30 border-amber-100 dark:border-amber-900/50', 'text-orange-500 bg-orange-50 dark:bg-orange-950/30 border-orange-100 dark:border-orange-900/50'];
        return (
          <div key={block.id} className="grid grid-cols-1 sm:grid-cols-3 gap-4 my-8">
            {stats.map((s, i) => (
              <div key={i} className={`p-4 rounded-xl border text-center ${colors[i % colors.length]}`}>
                <div className="text-3xl font-bold mb-1">{s.value}</div>
                <p className="text-xs text-slate-500 dark:text-slate-400 leading-tight">{s.label}</p>
              </div>
            ))}
          </div>
        );
      }
      case 'step-list': {
        const steps = block.content.split('\n').map(line => { const [step, title, desc] = line.split(' | '); return { step: step?.trim(), title: title?.trim(), desc: desc?.trim() }; });
        return (
          <div key={block.id} className="space-y-4 my-6">
            {steps.map((s, i) => (
              <div key={i} className="flex gap-4 p-4 rounded-xl bg-slate-50 dark:bg-slate-900/50 border border-slate-100 dark:border-slate-800">
                <div className="w-8 h-8 rounded-lg bg-orange-100 dark:bg-orange-900/40 flex items-center justify-center text-xs font-bold text-orange-600 dark:text-orange-400 flex-shrink-0">{s.step}</div>
                <div>
                  <h4 className="text-sm font-semibold text-slate-900 dark:text-white mb-1">{s.title}</h4>
                  <p className="text-sm text-slate-500 dark:text-slate-400 leading-relaxed">{s.desc}</p>
                </div>
              </div>
            ))}
          </div>
        );
      }
      case 'blockquote': {
        const [quote, author, role] = block.content.split(' | ');
        return (
          <blockquote key={block.id} className="my-8 pl-5 border-l-4 border-orange-400">
            <p className="text-lg sm:text-xl text-slate-700 dark:text-slate-300 italic leading-relaxed mb-3">{quote}</p>
            <footer className="flex items-center gap-3">
              <div className="w-8 h-8 rounded-full bg-gradient-to-br from-orange-400 to-orange-600 flex items-center justify-center text-white text-xs font-bold">
                {author?.split(' ').map((n: string) => n[0]).join('') || 'A'}
              </div>
              <div>
                <p className="text-sm font-semibold text-slate-900 dark:text-white">{author}</p>
                <p className="text-xs text-slate-500 dark:text-slate-400">{role}</p>
              </div>
            </footer>
          </blockquote>
        );
      }
      case 'faq-list': {
        const faqs = block.content.split('\n').map(line => { const [q, a] = line.split(' | '); return { q: q?.trim(), a: a?.trim() }; });
        return (
          <div key={block.id} className="space-y-4">
            {faqs.map((item, i) => (
              <div key={i} className="p-4 sm:p-5 rounded-xl border border-slate-100 dark:border-slate-800 bg-slate-50 dark:bg-slate-900/50">
                <h4 className="text-sm font-semibold text-slate-900 dark:text-white mb-2">{item.q}</h4>
                <p className="text-sm text-slate-500 dark:text-slate-400 leading-relaxed">{item.a}</p>
              </div>
            ))}
          </div>
        );
      }
      case 'tags-list': {
        const tagList = block.content.split(',').map(t => t.trim()).filter(Boolean);
        return (
          <div key={block.id} className="flex flex-wrap gap-2 mt-8">
            {tagList.map((tag) => (
              <span key={tag} className="px-3 py-1 rounded-full bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 text-xs font-medium">#{tag}</span>
            ))}
          </div>
        );
      }
      default: return null;
    }
  };

  return (
    <>
          {/* Admin Banner */}
      <div className="flex items-center gap-3 px-4 py-3 rounded-xl mb-6" style={{ backgroundColor: 'hsl(231, 40%, 14%)', color: 'white' }}>
        <div className="w-2 h-2 rounded-full bg-orange-400 animate-pulse" />
        <span className="text-sm font-semibold">{t('admin.blog.adminPanel', 'Admin Panel')}</span>
        <span className="text-xs opacity-60">— {isEdit ? t('admin.blog.editingExistingPost', 'Editing existing post') : t('admin.blog.creatingNewBlogPost', 'Creating new blog post')}</span>
      </div>

      {/* Top Bar */}
      <div className="flex items-center justify-between mb-6 gap-4">
        <Link href="/admin/blog" className="flex items-center gap-2 text-sm font-medium transition-colors hover:text-orange-500" style={{ color: 'hsl(var(--foreground-secondary))' }}>
          <ArrowLeft size={16} /> {t('admin.blog.backToBlog', 'Back to Blog')}
        </Link>
        <div className="flex items-center gap-2">
          {/* Status Toggle */}
          <div className="flex items-center gap-2 px-3 py-2 rounded-lg" style={{ backgroundColor: 'hsl(var(--muted))' }}>
            <span className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.status', 'Status')}:</span>
            <select
              className="text-xs font-semibold bg-transparent border-none outline-none cursor-pointer"
              value={status}
              onChange={e => setStatus(e.target.value as typeof status)}
              style={{ color: status === 'published' ? '#10b981' : status === 'scheduled' ? '#3b82f6' : 'hsl(var(--foreground-secondary))' }}
            >
              <option value="draft">{t('admin.blog.draft', 'Draft')}</option>
              <option value="published">{t('admin.blog.published', 'Published')}</option>
              <option value="scheduled">{t('admin.blog.scheduled', 'Scheduled')}</option>
            </select>
          </div>
          <button onClick={handleSave} className={`btn-primary flex items-center gap-2 text-sm px-4 py-2 transition-all ${saved ? 'bg-emerald-500 hover:bg-emerald-600' : ''}`}>
            <Save size={14} />
            {saved ? t('admin.blog.saved', 'Saved!') : isEdit ? t('admin.blog.updatePost', 'Update Post') : t('admin.blog.savePost', 'Save Post')}
          </button>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 mb-6 p-1 rounded-xl w-fit" style={{ backgroundColor: 'hsl(var(--muted))' }}>
        {(['content', 'seo', 'preview'] as const).map(tab => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className="px-4 py-2 rounded-lg text-sm font-semibold capitalize transition-all"
            style={activeTab === tab ? { backgroundColor: 'hsl(var(--surface))', color: 'hsl(var(--foreground))', boxShadow: '0 1px 3px rgba(0,0,0,0.1)' } : { color: 'hsl(var(--muted-foreground))' }}
          >
            {tab === 'preview' ? `👁 ${t('admin.blog.preview', 'Preview')}` : tab === 'seo' ? `🔍 ${t('admin.blog.seo', 'SEO')}` : `✏️ ${t('admin.blog.content', 'Content')}`}
          </button>
        ))}
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-[1fr_320px] gap-6">
        {/* Main Editor */}
        <div className="space-y-5">
          {activeTab === 'content' && (
            <>
              {/* Title */}
              <div className="card p-5">
                <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.postTitle', 'Post Title')} *</label>
                <input
                  className="input-base text-xl font-bold py-3 w-full"
                  placeholder={t('admin.blog.enterPostTitle', 'Enter a compelling blog post title...')}
                  value={title}
                  onChange={e => setTitle(e.target.value)}
                />
                <div className="flex items-center gap-2 mt-3">
                  <label className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.slug', 'Slug')}:</label>
                  <input
                    className="input-base text-xs py-1.5 flex-1"
                    value={slug}
                    onChange={e => { setSlug(e.target.value); setSlugManual(true); }}
                    placeholder={t('admin.blog.autoGeneratedFromTitle', 'auto-generated-from-title')}
                  />
                  {slugManual && (
                    <button onClick={() => { setSlugManual(false); setSlug(slugify(title)); }} className="text-xs text-orange-500 hover:text-orange-600 font-medium whitespace-nowrap">{t('admin.blog.autoGenerate', 'Auto-generate')}</button>
                  )}
                </div>
              </div>

              {/* Excerpt */}
              <div className="card p-5">
                <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.excerptSubtitle', 'Excerpt / Subtitle')}</label>
                <textarea
                  className="input-base w-full resize-none"
                  rows={3}
                  placeholder={t('admin.blog.briefDescriptionPlaceholder', 'A brief description shown on the blog listing page and in search results...')}
                  value={excerpt}
                  onChange={e => setExcerpt(e.target.value)}
                />
                <p className="text-xs mt-1.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{excerpt.length}/{t('admin.blog.charactersRecommended', '200 characters recommended')}</p>
              </div>

              {/* Hero Image */}
              <div className="card p-5">
                <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.heroImage', 'Hero Image')}</label>
                <div className="flex gap-3">
                  <div className="flex-1">
                    <input
                      className="input-base w-full mb-2"
                      placeholder={t('blog.heroImagePlaceholder', 'https://example.com/hero-image.jpg')}
                      value={heroImageUrl}
                      onChange={e => setHeroImageUrl(e.target.value)}
                    />
                    <input
                      className="input-base w-full text-sm"
                      placeholder={t('admin.blog.altTextPlaceholder', 'Alt text: describe what the image shows...')}
                      value={heroImageAlt}
                      onChange={e => setHeroImageAlt(e.target.value)}
                    />
                  </div>
                  {heroImageUrl ? (
                    <div className="w-24 h-16 rounded-xl overflow-hidden flex-shrink-0 border" style={{ borderColor: 'hsl(var(--border))' }}>
                      <img src={heroImageUrl} alt={heroImageAlt} className="w-full h-full object-cover" onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }} />
                    </div>
                  ) : (
                    <div className="w-24 h-16 rounded-xl flex-shrink-0 flex items-center justify-center" style={{ backgroundColor: 'hsl(var(--muted))', border: '2px dashed hsl(var(--border))' }}>
                      <ImageIcon size={18} style={{ color: 'hsl(var(--muted-foreground))' }} />
                    </div>
                  )}
                </div>
                <p className="text-xs mt-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {t('admin.blog.heroImageHelpText', 'If no image URL is provided, a gradient placeholder will be shown (matching the existing blog template).')}
                </p>
              </div>

              {/* Content Blocks */}
              <div className="card p-5">
                <div className="flex items-center justify-between mb-4">
                  <div>
                    <label className="block text-xs font-bold uppercase tracking-wide" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.articleContent', 'Article Content')}</label>
                    <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {t('admin.blog.contentBlocksHelpText', 'Each block maps to a specific layout element in the published post. Use the format hints in each block.')}
                    </p>
                  </div>
                  <span className="text-xs px-2 py-1 rounded-full" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground-secondary))' }}>
                    ~{readTime} {t('admin.blog.minRead', 'min read')}
                  </span>
                </div>

                <div className="space-y-3">
                  {blocks.map((block, idx) => (
                    <div key={block.id} className="rounded-xl border overflow-hidden" style={{ borderColor: 'hsl(var(--border))' }}>
                      {/* Block Header */}
                      <div className="flex items-center gap-2 px-3 py-2" style={{ backgroundColor: 'hsl(var(--muted))', borderBottom: '1px solid hsl(var(--border))' }}>
                        <span className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground-secondary))' }}>{blockTypeLabels[block.type]}</span>
                        <div className="flex items-center gap-1 ml-auto">
                          <button onClick={() => moveBlock(block.id, 'up')} disabled={idx === 0} className="p-1 rounded hover:bg-white/50 disabled:opacity-30 transition-colors" title={t('admin.blog.moveUp', 'Move up')}>
                            <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="18 15 12 9 6 15"/></svg>
                          </button>
                          <button onClick={() => moveBlock(block.id, 'down')} disabled={idx === blocks.length - 1} className="p-1 rounded hover:bg-white/50 disabled:opacity-30 transition-colors" title={t('admin.blog.moveDown', 'Move down')}>
                            <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
                          </button>
                          <button onClick={() => removeBlock(block.id)} className="p-1 rounded hover:bg-red-100 dark:hover:bg-red-900/30 transition-colors" title={t('admin.blog.removeBlock', 'Remove block')}>
                            <X size={12} className="text-red-500" />
                          </button>
                        </div>
                      </div>
                      {/* Block Content */}
                      <textarea
                        className="w-full px-3 py-2.5 text-sm resize-none outline-none bg-transparent"
                        style={{ color: 'hsl(var(--foreground))', minHeight: block.type === 'paragraph' ? '80px' : block.type === 'step-list' || block.type === 'faq-list' || block.type === 'teal-callout' ? '120px' : '48px' }}
                        placeholder={blockTypePlaceholders[block.type]}
                        value={block.content}
                        onChange={e => updateBlock(block.id, e.target.value)}
                      />
                    </div>
                  ))}
                </div>

                {/* Add Block */}
                <div className="mt-4">
                  <p className="text-xs font-semibold mb-2" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.addBlock', 'Add Block')}:</p>
                  <div className="flex flex-wrap gap-2">
                    {(Object.keys(blockTypeLabels) as ContentBlock['type'][]).map(type => (
                      <button
                        key={type}
                        onClick={() => addBlock(type)}
                        className="flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all hover:-translate-y-0.5"
                        style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground-secondary))', border: '1px solid hsl(var(--border))' }}
                      >
                        <Plus size={10} /> {blockTypeLabels[type]}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </>
          )}

          {activeTab === 'seo' && (
            <div className="card p-5 space-y-5">
              <div>
                <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.seoMetaTitle', 'SEO Meta Title')}</label>
                <input
                  className="input-base w-full"
                  placeholder={title || t('admin.blog.enterSeoTitlePlaceholder', 'Enter SEO title (50-60 chars recommended)')}
                  value={metaTitle}
                  onChange={e => setMetaTitle(e.target.value)}
                />
                <div className="flex items-center justify-between mt-1.5">
                  <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.blog.recommended5060Chars', 'Recommended: 50-60 characters')}</p>
                  <span className={`text-xs font-semibold ${(metaTitle || title).length > 60 ? 'text-red-500' : 'text-emerald-500'}`}>{(metaTitle || title).length}/60</span>
                </div>
              </div>
              <div>
                <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.seoMetaDescription', 'SEO Meta Description')}</label>
                <textarea
                  className="input-base w-full resize-none"
                  rows={3}
                  placeholder={excerpt || t('admin.blog.enterMetaDescriptionPlaceholder', 'Enter meta description (150-160 chars recommended)')}
                  value={metaDesc}
                  onChange={e => setMetaDesc(e.target.value)}
                />
                <div className="flex items-center justify-between mt-1.5">
                  <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.blog.recommended150160Chars', 'Recommended: 150-160 characters')}</p>
                  <span className={`text-xs font-semibold ${(metaDesc || excerpt).length > 160 ? 'text-red-500' : 'text-emerald-500'}`}>{(metaDesc || excerpt).length}/160</span>
                </div>
              </div>

              {/* Preview */}
              <div className="p-4 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                <p className="text-xs font-semibold mb-3" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.googleSearchPreview', 'Google Search Preview')}</p>
                <div className="bg-white dark:bg-slate-900 rounded-lg p-4 border" style={{ borderColor: 'hsl(var(--border))' }}>
                  <p className="text-xs text-slate-400 mb-1">{(typeof window !== 'undefined' ? window.location.host : 'your-site.com')} › blog › {slug || 'post-slug'}</p>
                  <p className="text-blue-600 dark:text-blue-400 font-medium text-sm mb-1 line-clamp-1">{metaTitle || title || t('admin.blog.postTitlePreview', 'Post Title')}</p>
                  <p className="text-xs text-slate-500 dark:text-slate-400 line-clamp-2">{metaDesc || excerpt || t('admin.blog.metaDescriptionPreview', 'Meta description will appear here...')}</p>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'preview' && (
            <div className="card p-6 overflow-hidden">
              <div className="flex items-center gap-2 mb-6 pb-4" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                <Eye size={16} style={{ color: 'hsl(var(--primary))' }} />
                <span className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.blog.livePreviewHelpText', 'Live Preview — matches /blog/[slug] template')}</span>
              </div>

              {/* Preview Hero */}
              <div className="mb-6">
                <div className="flex flex-wrap items-center gap-2.5 mb-4">
                  {category && <span className="px-2.5 py-1 rounded-full bg-orange-100 dark:bg-orange-900/40 text-orange-700 dark:text-orange-300 text-xs font-semibold">{category}</span>}
                  <span className="text-xs text-slate-500 dark:text-slate-400 flex items-center gap-1">
                    <Clock size={11} /> {readTime} {t('admin.blog.minRead', 'min read')}
                  </span>
                  {publishDate && <span className="text-xs text-slate-500 dark:text-slate-400">{publishDate}</span>}
                </div>
                <h1 className="text-2xl sm:text-3xl font-bold text-slate-900 dark:text-white leading-tight mb-3">
                  {title || t('admin.blog.postTitlePreview', 'Post Title')}
                </h1>
                <p className="text-base text-slate-500 dark:text-slate-400 leading-relaxed mb-5">
                  {excerpt || t('admin.blog.excerptPreview', 'Excerpt will appear here...')}
                </p>
                {authorName && (
                  <div className="flex items-center gap-3 pb-5" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                    <div className="w-9 h-9 rounded-full bg-gradient-to-br from-orange-400 to-orange-600 flex items-center justify-center text-white text-sm font-bold flex-shrink-0">
                      {authorInitials || authorName.split(' ').map(n => n[0]).join('')}
                    </div>
                    <div>
                      <p className="text-sm font-semibold text-slate-900 dark:text-white">{authorName}</p>
                      {authorBio && <p className="text-xs text-slate-500 dark:text-slate-400 line-clamp-1">{authorBio}</p>}
                    </div>
                  </div>
                )}
              </div>

              {/* Hero Image Preview */}
              <div className="relative rounded-2xl overflow-hidden bg-gradient-to-br from-slate-900 via-orange-950/40 to-slate-900 aspect-[16/7] mb-8">
                {heroImageUrl ? (
                  <img src={heroImageUrl} alt={heroImageAlt} className="w-full h-full object-cover" />
                ) : (
                  <>
                    <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_center,rgba(249,115,22,0.2),transparent_60%)]" />
                    <div className="absolute inset-0 flex items-center justify-center">
                      <div className="text-center">
                        <div className="text-5xl mb-3">📝</div>
                        <p className="text-white/60 text-sm font-medium">{t('admin.blog.heroImagePlaceholder', 'Hero image placeholder')}</p>
                      </div>
                    </div>
                  </>
                )}
              </div>

              {/* Content Blocks Preview */}
              <article className="max-w-2xl">
                {blocks.map(block => renderPreviewBlock(block))}
              </article>

              {/* Author Bio Preview */}
              {authorName && (
                <div className="mt-10 p-5 rounded-2xl border" style={{ borderColor: 'hsl(var(--border))', backgroundColor: 'hsl(var(--muted))' }}>
                  <div className="flex items-start gap-4">
                    <div className="w-12 h-12 rounded-full bg-gradient-to-br from-orange-400 to-orange-600 flex items-center justify-center text-white font-bold flex-shrink-0">
                      {authorInitials || authorName.split(' ').map(n => n[0]).join('')}
                    </div>
                    <div>
                      <h3 className="font-bold" style={{ color: 'hsl(var(--foreground))' }}>{authorName}</h3>
                      {authorBio && <p className="text-sm mt-1" style={{ color: 'hsl(var(--foreground-secondary))' }}>{authorBio}</p>}
                    </div>
                  </div>
                </div>
              )}

              {/* Tags Preview */}
              {tags.length > 0 && (
                <div className="mt-6 flex flex-wrap gap-2">
                  {tags.map(tag => (
                    <span key={tag} className="px-3 py-1 rounded-full bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 text-xs font-medium">#{tag}</span>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>

        {/* Sidebar Settings */}
        <div className="space-y-4">
          {/* Publish Settings */}
          <div className="card p-5">
            <h3 className="text-xs font-bold uppercase tracking-wide mb-4 flex items-center gap-2" style={{ color: 'hsl(var(--foreground-secondary))' }}>
              <Globe size={13} /> {t('admin.blog.publishSettings', 'Publish Settings')}
            </h3>
            <div className="space-y-3">
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.status', 'Status')}</label>
                <select className="input-base w-full text-sm" value={status} onChange={e => setStatus(e.target.value as typeof status)}>
                  <option value="draft">{t('admin.blog.draft', 'Draft')}</option>
                  <option value="published">{t('admin.blog.published', 'Published')}</option>
                  <option value="scheduled">{t('admin.blog.scheduled', 'Scheduled')}</option>
                </select>
              </div>
              {status === 'scheduled' && (
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.scheduleDateTime', 'Schedule Date & Time')}</label>
                  <input type="datetime-local" className="input-base w-full text-sm" value={publishDate} onChange={e => setPublishDate(e.target.value)} />
                </div>
              )}
              {status === 'published' && (
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.publishDate', 'Publish Date')}</label>
                  <input type="date" className="input-base w-full text-sm" value={publishDate} onChange={e => setPublishDate(e.target.value)} />
                </div>
              )}
              <div className="flex items-center gap-2 p-2.5 rounded-lg" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                <Clock size={12} style={{ color: 'hsl(var(--muted-foreground))' }} />
                <span className="text-xs" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.readingTime', 'Reading time')}: ~{readTime} {t('admin.blog.min', 'min')}</span>
              </div>
            </div>
          </div>

          {/* Category & Tags */}
          <div className="card p-5">
            <h3 className="text-xs font-bold uppercase tracking-wide mb-4 flex items-center gap-2" style={{ color: 'hsl(var(--foreground-secondary))' }}>
              <Tag size={13} /> {t('admin.blog.categoryAndTags', 'Category & Tags')}
            </h3>
            <div className="space-y-3">
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.categoryLabel', 'Category *')}</label>
                <select className="input-base w-full text-sm" value={category} onChange={e => setCategory(e.target.value)}>
                  <option value="">{t('admin.blog.selectCategoryPlaceholder', 'Select category...')}</option>
                  {categories.map(c => <option key={c}>{c}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.tags', 'Tags')}</label>
                <div className="flex gap-2 mb-2">
                  <input
                    className="input-base flex-1 text-sm py-1.5"
                    placeholder={t('admin.blog.addTagPlaceholder', 'Add tag...')}
                    value={tagInput}
                    onChange={e => setTagInput(e.target.value)}
                    onKeyDown={e => e.key === 'Enter' && (e.preventDefault(), addTag())}
                  />
                  <button onClick={addTag} className="px-2.5 py-1.5 rounded-lg text-xs font-semibold" style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}>
                    <Plus size={12} />
                  </button>
                </div>
                <div className="flex flex-wrap gap-1.5">
                  {tags.map(tag => (
                    <span key={tag} className="flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground-secondary))' }}>
                      {tag}
                      <button onClick={() => setTags(prev => prev.filter(t => t !== tag))}><X size={10} /></button>
                    </span>
                  ))}
                </div>
              </div>
            </div>
          </div>

          {/* Author */}
          <div className="card p-5">
            <h3 className="text-xs font-bold uppercase tracking-wide mb-4 flex items-center gap-2" style={{ color: 'hsl(var(--foreground-secondary))' }}>
              <User size={13} /> {t('admin.blog.author', 'Author')}
            </h3>
            <div className="space-y-3">
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.authorNameLabel', 'Author Name *')}</label>
                <input className="input-base w-full text-sm" placeholder={t('admin.blog.fullNamePlaceholder', 'Full name...')} value={authorName} onChange={e => setAuthorName(e.target.value)} />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.authorInitialsLabel', 'Author Initials (Avatar)')}</label>
                <input className="input-base w-full text-sm" placeholder={t('admin.blog.initialsPlaceholder', 'e.g. AR')} maxLength={2} value={authorInitials} onChange={e => setAuthorInitials(e.target.value.toUpperCase())} />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.authorBio', 'Author Bio')}</label>
                <textarea className="input-base w-full text-sm resize-none" rows={3} placeholder={t('admin.blog.shortBioPlaceholder', 'Short bio shown at the bottom of the post...')} value={authorBio} onChange={e => setAuthorBio(e.target.value)} />
              </div>
              {authorName && (
                <div className="flex items-center gap-3 p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                  <div className="w-9 h-9 rounded-full bg-gradient-to-br from-orange-400 to-orange-600 flex items-center justify-center text-white text-sm font-bold flex-shrink-0">
                    {authorInitials || authorName.split(' ').map(n => n[0]).join('')}
                  </div>
                  <div>
                    <p className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{authorName}</p>
                    {authorBio && <p className="text-xs line-clamp-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{authorBio}</p>}
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Content Structure Guide */}
          <div className="card p-5">
            <h3 className="text-xs font-bold uppercase tracking-wide mb-3 flex items-center gap-2" style={{ color: 'hsl(var(--foreground-secondary))' }}>
              <Info size={13} /> {t('admin.blog.blockFormatGuide', 'Block Format Guide')}
            </h3>
            <div className="space-y-2 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
              <p><strong className="text-orange-500">{t('admin.blog.callout', 'Callout')}:</strong> {t('admin.blog.calloutGuide', 'Title | Body text')}</p>
              <p><strong className="text-teal-500">{t('admin.blog.tealCallout', 'Teal Callout')}:</strong> {t('admin.blog.tealCalloutGuide', 'Title | Item 1↵Item 2')}</p>
              <p><strong style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.statsGrid', 'Stats Grid')}:</strong> {t('admin.blog.statsGridGuide', 'Value | Label↵Value | Label')}</p>
              <p><strong style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.stepList', 'Step List')}:</strong> {t('admin.blog.stepListGuide', '01 | Title | Desc↵02 | Title | Desc')}</p>
              <p><strong style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.blockquote', 'Blockquote')}:</strong> {t('admin.blog.blockquoteGuide', '"Quote" | Author | Role')}</p>
              <p><strong style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.faqList', 'FAQ List')}:</strong> {t('admin.blog.faqListGuide', 'Question? | Answer↵Q2? | A2')}</p>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
