/* global React, Icons */
const { useState, useEffect, useRef } = React;

// ── Constants ────────────────────────────────────────────────────────────────

const PROMPTS_STORAGE_KEY = 'aip_script_prompts';

const DEFAULT_PROMPT_CONTENT =
`Write a {{reviewLength}}-second video review script for the Amazon Influencer Program. Use a natural, conversational tone — like advice from a knowledgeable friend.

Structure:
1. Hook (5–10 sec): The one thing a buyer most needs to hear immediately
2. What it is + who it's for (10–15 sec)
3. Key features (20–25 sec): 3–4 features explained as real-world benefits — not specs
4. Honest take (15 sec): Address the main concern or misconception directly
5. Verdict + CTA (5–10 sec)

Rules:
- Never state the specific price — use "great value", "mid-range", "on the pricier side", etc.
- No hype or exaggeration — be honest about limitations
- Sound natural, not scripted`;

const DEFAULT_PROMPTS = [
  { id: 'p-default', name: 'Standard Review', reviewLength: 60, content: DEFAULT_PROMPT_CONTENT },
];

// ── Helpers ───────────────────────────────────────────────────────────────────

function loadPrompts() {
  try {
    const stored = JSON.parse(localStorage.getItem(PROMPTS_STORAGE_KEY) || 'null');
    if (Array.isArray(stored) && stored.length) return stored;
  } catch (_) {}
  return DEFAULT_PROMPTS;
}

function savePrompts(prompts) {
  try { localStorage.setItem(PROMPTS_STORAGE_KEY, JSON.stringify(prompts)); } catch (_) {}
}

function statusColor(s) {
  if (s === 'ready') return 'var(--success)';
  if (s === 'in-progress') return 'var(--warn)';
  return 'var(--text-3)';
}
function statusLabel(s) {
  if (s === 'ready') return 'Ready';
  if (s === 'in-progress') return 'In Progress';
  return 'Scraped';
}

function generateBrief(product, prompt) {
  const promptText = prompt.content.replace(/\{\{reviewLength\}\}/g, prompt.reviewLength);

  // Only include a section if it has content
  const field = (heading, value) => {
    const v = (value || '').trim();
    return v ? `### ${heading}\n${v}\n\n` : '';
  };

  const productSections = [
    field('Features', product.features),
    field('Product Description', product.productDesc),
  ].join('');

  const buyerSections = [
    field('Summary of customer reviews (Amazon AI)', product.customerReviewsSummary),
    field('Top review topics', product.reviewTopics),
    field('What buyers are asking (suggested questions)', product.suggestedQuestions),
    field('What are buyers most afraid of getting wrong?', product.buyerFears),
    field('Common misconceptions', product.misconceptions),
    field('What to say in the first 5 seconds', product.firstFiveSeconds),
  ].join('');

  const creatorSections = [
    field('Personal experience with this product', product.personalNotes),
    field('Who buys this', product.buyerPersona),
    field('What existing videos don\'t show or answer', product.videoGaps),
    field('What you can physically show or demonstrate', product.demonstration),
  ].join('');

  let brief = `# Script Brief: ${product.title || product.asin}\n\n`;
  brief += `## Your Prompt\n\n${promptText}\n\n---\n\n`;
  brief += `## Product Data\n\n`;
  brief += `**ASIN:** ${product.asin}\n`;
  brief += `**Brand:** ${product.brand || '—'}\n`;
  brief += `**Product:** ${product.title || '—'}\n`;
  brief += `**Review length:** ${prompt.reviewLength} seconds\n\n`;
  if (productSections) brief += productSections + '---\n\n';
  if (buyerSections) brief += `## Buyer Insights\n\n${buyerSections}---\n\n`;
  if (creatorSections) brief += `## Creator Notes\n\n${creatorSections}`;

  return brief.trimEnd();
}

// ── Shared sub-components ─────────────────────────────────────────────────────

function FieldLabel({ label }) {
  return (
    <div style={{ marginBottom: 5 }}>
      <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--text-1)' }}>{label}</span>
    </div>
  );
}

function SectionHeader({ children }) {
  return (
    <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-3)', letterSpacing: '0.08em',
      textTransform: 'uppercase', paddingBottom: 8, borderBottom: '1px solid var(--line)',
      marginBottom: 16 }}>
      {children}
    </div>
  );
}

function TA({ value, onChange, rows = 4, placeholder }) {
  return (
    <textarea
      value={value || ''}
      onChange={e => onChange(e.target.value)}
      rows={rows}
      placeholder={placeholder}
      style={{ width: '100%', padding: '8px 10px', border: '1px solid var(--line)',
        borderRadius: 6, background: 'var(--bg-0)', color: 'var(--text-1)',
        fontSize: 12, lineHeight: 1.6, resize: 'vertical', fontFamily: 'inherit',
        outline: 'none', transition: 'border-color 0.12s' }}
      onFocus={e => { e.target.style.borderColor = 'var(--accent)'; }}
      onBlur={e =>  { e.target.style.borderColor = 'var(--line)'; }}
    />
  );
}

// ── Product list (left panel) ─────────────────────────────────────────────────

function ProductList({ scripts, activeId, onSelect }) {
  if (!scripts.length) {
    return (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center',
        justifyContent: 'center', padding: '24px 16px', textAlign: 'center', gap: 10 }}>
        <div style={{ width: 40, height: 40, borderRadius: 10, background: 'var(--accent-soft)',
          display: 'grid', placeItems: 'center', color: 'var(--accent)' }}>
          <Icons.video size={18}/>
        </div>
        <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-1)' }}>No products yet</div>
        <div style={{ fontSize: 11, color: 'var(--text-3)', lineHeight: 1.5 }}>
          Open the AIP extension on any Amazon product page and click <strong>Generate Script Brief</strong>
        </div>
      </div>
    );
  }

  return (
    <div style={{ overflowY: 'auto', flex: 1 }}>
      {scripts.map(p => (
        <div key={p.id} onClick={() => onSelect(p.id)}
          style={{ padding: '10px 12px', cursor: 'pointer',
            borderLeft: `3px solid ${activeId === p.id ? 'var(--accent)' : 'transparent'}`,
            background: activeId === p.id ? 'var(--accent-soft)' : 'transparent',
            transition: 'background 0.1s' }}>
          <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
            {p.image ? (
              <img src={p.image} alt="" onError={e => { e.target.style.display = 'none'; }}
                style={{ width: 34, height: 34, objectFit: 'contain', borderRadius: 4,
                  flexShrink: 0, background: 'var(--bg-2)' }}/>
            ) : (
              <div style={{ width: 34, height: 34, borderRadius: 4, flexShrink: 0,
                background: 'var(--bg-2)', display: 'grid', placeItems: 'center' }}>
                <Icons.package size={14} style={{ color: 'var(--text-3)' }}/>
              </div>
            )}
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--text-0)', lineHeight: 1.3,
                overflow: 'hidden', display: '-webkit-box',
                WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>
                {p.title || p.asin}
              </div>
              <div style={{ marginTop: 4, display: 'flex', alignItems: 'center', gap: 5 }}>
                <span style={{ width: 6, height: 6, borderRadius: 99,
                  background: statusColor(p.status), flexShrink: 0 }}/>
                <span style={{ fontSize: 10, color: 'var(--text-3)' }}>{statusLabel(p.status)}</span>
              </div>
              <div style={{ fontSize: 10, color: 'var(--text-3)', marginTop: 1,
                fontFamily: 'var(--font-mono)' }}>{p.asin}</div>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

// ── Product editor (right panel) ──────────────────────────────────────────────

function ProductEditor({ product, prompts, onChange, onStatusChange }) {
  const [activePromptId, setActivePromptId] = useState(() => prompts[0]?.id || '');
  const [copied, setCopied] = useState(false);

  // Stay on a valid prompt if the list changes
  const activePrompt = prompts.find(p => p.id === activePromptId) || prompts[0];

  const set = field => val => onChange(product.id, field, val);

  function handleCopy() {
    if (!activePrompt) return;
    navigator.clipboard.writeText(generateBrief(product, activePrompt)).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2500);
    });
  }

  function handleDownload() {
    if (!activePrompt) return;
    const text = generateBrief(product, activePrompt);
    const slug = (product.title || product.asin)
      .replace(/[^a-z0-9]/gi, '-').toLowerCase().slice(0, 40);
    const blob = new Blob([text], { type: 'text/markdown' });
    const url  = URL.createObjectURL(blob);
    const a    = document.createElement('a');
    a.href = url; a.download = `script-${slug}.md`;
    document.body.appendChild(a); a.click();
    document.body.removeChild(a); URL.revokeObjectURL(url);
  }

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden',
      borderLeft: '1px solid var(--line)' }}>

      {/* Header */}
      <div style={{ padding: '12px 18px', borderBottom: '1px solid var(--line)',
        background: 'var(--bg-1)', display: 'flex', alignItems: 'center',
        gap: 10, flexShrink: 0 }}>
        {product.image ? (
          <img src={product.image} alt="" onError={e => { e.target.style.display = 'none'; }}
            style={{ width: 38, height: 38, objectFit: 'contain', borderRadius: 6,
              background: 'var(--bg-2)', flexShrink: 0 }}/>
        ) : null}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--text-0)',
            lineHeight: 1.3, overflow: 'hidden', whiteSpace: 'nowrap',
            textOverflow: 'ellipsis' }}>
            {product.title || product.asin}
          </div>
          <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 2 }}>
            {product.brand}{product.brand && ' · '}
            <span style={{ fontFamily: 'var(--font-mono)' }}>{product.asin}</span>
          </div>
        </div>
        <select value={product.status} onChange={e => onStatusChange(product.id, e.target.value)}
          style={{ padding: '4px 8px', borderRadius: 6, border: '1px solid var(--line)',
            background: 'var(--bg-2)', color: statusColor(product.status),
            fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
            flexShrink: 0 }}>
          <option value="scraped">Scraped</option>
          <option value="in-progress">In Progress</option>
          <option value="ready">Ready</option>
        </select>
      </div>

      {/* Scrollable body */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 22px',
        display: 'flex', flexDirection: 'column', gap: 28 }}>

        {/* ── PRODUCT INFO ── */}
        <div>
          <SectionHeader>Product Info</SectionHeader>
          <div>
            <FieldLabel label="Features / Bullets"/>
            <TA value={product.features} onChange={set('features')} rows={6}
              placeholder="Feature bullets from the listing…"/>
          </div>
          <div style={{ marginTop: 14 }}>
            <FieldLabel label="Product Description"/>
            <TA value={product.productDesc} onChange={set('productDesc')} rows={4}
              placeholder="Manufacturer's product description…"/>
          </div>
        </div>

        {/* ── BUYER INSIGHTS ── */}
        <div>
          <SectionHeader>Buyer Insights</SectionHeader>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div>
              <FieldLabel label="Summary of customer reviews"/>
              <TA value={product.customerReviewsSummary} onChange={set('customerReviewsSummary')} rows={3}
                placeholder="Amazon's AI-generated summary of what customers say…"/>
              {product.reviewTopics && (
                <div style={{ marginTop: 6, fontSize: 11, color: 'var(--text-2)',
                  padding: '5px 10px', background: 'var(--bg-2)', borderRadius: 5,
                  border: '1px solid var(--line)' }}>
                  <span style={{ color: 'var(--text-3)', marginRight: 4 }}>Top topics:</span>
                  {product.reviewTopics}
                </div>
              )}
            </div>
            <div>
              <FieldLabel label="What buyers are asking"/>
              <TA value={product.suggestedQuestions} onChange={set('suggestedQuestions')} rows={3}
                placeholder="Suggested questions from Amazon's 'Looking for specific info?' section…"/>
            </div>
          </div>
        </div>

        {/* ── CREATOR NOTES ── */}
        <div>
          <SectionHeader>Creator Notes</SectionHeader>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div>
              <FieldLabel label="What are buyers most afraid of getting wrong?"/>
              <TA value={product.buyerFears} onChange={set('buyerFears')} rows={4}
                placeholder="Questions and concerns from reviews and Q&As…"/>
            </div>
            <div>
              <FieldLabel label="Common misconception about this product"/>
              <TA value={product.misconceptions} onChange={set('misconceptions')} rows={3}
                placeholder="What do buyers consistently misunderstand?"/>
            </div>
            <div>
              <FieldLabel label="What would a buyer feel relieved to hear in the first 5 seconds?"/>
              <TA value={product.firstFiveSeconds} onChange={set('firstFiveSeconds')} rows={3}
                placeholder="The one thing that immediately addresses the biggest doubt…"/>
            </div>
            <div>
              <FieldLabel label="My personal notes and experience with this product"/>
              <TA value={product.personalNotes} onChange={set('personalNotes')} rows={3}
                placeholder="Anything you noticed firsthand worth including…"/>
            </div>
            <div>
              <FieldLabel label="Who buys this"/>
              <TA value={product.buyerPersona} onChange={set('buyerPersona')} rows={2}
                placeholder="e.g. gift, personal splurge, practical household buy, hobbyist…"/>
            </div>
            <div>
              <FieldLabel label="What do existing influencer videos NOT show or answer?"/>
              <TA value={product.videoGaps} onChange={set('videoGaps')} rows={3}
                placeholder="What gap can you fill that other reviews miss?"/>
            </div>
            <div>
              <FieldLabel label="What can you physically show or demonstrate?"/>
              <TA value={product.demonstration} onChange={set('demonstration')} rows={3}
                placeholder="Scale, texture, sound, real-world size, setup time, how it feels to use…"/>
            </div>
          </div>
        </div>

        {/* Spacer so content clears the sticky bar */}
        <div style={{ height: 4 }}/>
      </div>

      {/* Sticky generate bar */}
      <div style={{ borderTop: '1px solid var(--line)', padding: '10px 18px',
        background: 'var(--bg-1)', display: 'flex', alignItems: 'center',
        gap: 8, flexShrink: 0 }}>
        <select value={activePromptId} onChange={e => setActivePromptId(e.target.value)}
          style={{ flex: 1, padding: '6px 10px', borderRadius: 6,
            border: '1px solid var(--line)', background: 'var(--bg-2)',
            color: 'var(--text-1)', fontSize: 12, fontFamily: 'inherit', cursor: 'pointer' }}>
          {prompts.map(p => (
            <option key={p.id} value={p.id}>{p.name} ({p.reviewLength}s)</option>
          ))}
        </select>
        <button onClick={handleCopy}
          style={{ display: 'flex', alignItems: 'center', gap: 5, padding: '6px 14px',
            borderRadius: 6, border: '1px solid var(--line)',
            background: copied ? 'rgba(34,197,94,0.12)' : 'var(--bg-2)',
            color: copied ? 'var(--success)' : 'var(--text-1)',
            fontSize: 12, fontWeight: 500, cursor: 'pointer',
            flexShrink: 0, transition: 'all 0.12s', fontFamily: 'inherit' }}>
          {copied ? <Icons.check size={12}/> : <Icons.copy size={12}/>}
          {copied ? 'Copied!' : 'Copy'}
        </button>
        <button onClick={handleDownload}
          style={{ display: 'flex', alignItems: 'center', gap: 5, padding: '6px 12px',
            borderRadius: 6, border: '1px solid var(--line)', background: 'var(--bg-2)',
            color: 'var(--text-1)', fontSize: 12, fontWeight: 500, cursor: 'pointer',
            flexShrink: 0, fontFamily: 'inherit' }}>
          <Icons.download size={12}/>
          .md
        </button>
      </div>
    </div>
  );
}

// ── Prompts panel ──────────────────────────────────────────────────────────────

function PromptsPanel({ prompts, setPrompts }) {
  const [activeId, setActiveId] = useState(() => prompts[0]?.id || '');
  const [saved, setSaved]       = useState(false);
  const [lengthInput, setLengthInput] = useState(() => String(prompts[0]?.reviewLength || 60));

  const active = prompts.find(p => p.id === activeId) || prompts[0];
  const set = field => val =>
    setPrompts(prev => prev.map(p => p.id === activeId ? { ...p, [field]: val } : p));

  // Keep the length text input in sync when switching prompts
  useEffect(() => {
    if (active) setLengthInput(String(active.reviewLength));
  }, [active?.id]);

  function handleSave() {
    savePrompts(prompts);
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  }

  function handleNew() {
    const id = 'p-' + Date.now();
    const newP = { id, name: 'New Prompt', reviewLength: 60, content: DEFAULT_PROMPT_CONTENT };
    setPrompts(prev => [...prev, newP]);
    setActiveId(id);
  }

  function handleDelete() {
    if (prompts.length <= 1) return;
    const remaining = prompts.filter(p => p.id !== activeId);
    setPrompts(remaining);
    setActiveId(remaining[0].id);
    savePrompts(remaining);
  }

  return (
    <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
      {/* Prompt list */}
      <div style={{ width: 200, borderRight: '1px solid var(--line)',
        display: 'flex', flexDirection: 'column', flexShrink: 0 }}>
        <div style={{ padding: '10px 12px 8px', borderBottom: '1px solid var(--line)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-3)',
            textTransform: 'uppercase', letterSpacing: '0.06em' }}>
            {prompts.length} Prompt{prompts.length !== 1 ? 's' : ''}
          </span>
          <button onClick={handleNew}
            style={{ display: 'flex', alignItems: 'center', gap: 3, padding: '3px 8px',
              borderRadius: 5, border: '1px solid var(--line)', background: 'transparent',
              color: 'var(--text-2)', fontSize: 11, cursor: 'pointer', fontFamily: 'inherit' }}>
            <Icons.plus size={10}/> New
          </button>
        </div>
        <div style={{ overflowY: 'auto', flex: 1 }}>
          {prompts.map(p => (
            <div key={p.id} onClick={() => setActiveId(p.id)}
              style={{ padding: '10px 14px', cursor: 'pointer',
                borderLeft: `3px solid ${activeId === p.id ? 'var(--accent)' : 'transparent'}`,
                background: activeId === p.id ? 'var(--accent-soft)' : 'transparent',
                fontSize: 12, fontWeight: activeId === p.id ? 600 : 400,
                color: activeId === p.id ? 'var(--accent)' : 'var(--text-1)' }}>
              {p.name}
              <div style={{ fontSize: 10, color: 'var(--text-3)', marginTop: 2 }}>
                {p.reviewLength}s
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Prompt editor */}
      {active && (
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          <div style={{ flex: 1, overflowY: 'auto', padding: '20px 24px',
            display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div>
              <FieldLabel label="Prompt name"/>
              <input value={active.name} onChange={e => set('name')(e.target.value)}
                style={{ width: '100%', padding: '7px 10px', border: '1px solid var(--line)',
                  borderRadius: 6, background: 'var(--bg-0)', color: 'var(--text-1)',
                  fontSize: 13, fontFamily: 'inherit', outline: 'none' }}
                onFocus={e => { e.target.style.borderColor = 'var(--accent)'; }}
                onBlur={e =>  { e.target.style.borderColor = 'var(--line)'; }}
              />
            </div>
            <div>
              <FieldLabel label="Prompt template"/>
              <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 6 }}>
                Use{' '}
                <code style={{ background: 'var(--bg-2)', padding: '1px 5px',
                  borderRadius: 3, fontFamily: 'var(--font-mono)', fontSize: 11 }}>
                  {'{{reviewLength}}'}
                </code>
                {' '}to insert the review length.
              </div>
              <TA value={active.content} onChange={set('content')} rows={18}
                placeholder="Write your prompt instructions here…"/>
            </div>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 14 }}>
              <div>
                <FieldLabel label="Review length (seconds)"/>
                <input type="number" value={lengthInput} min={15} max={600} step={5}
                  onChange={e => setLengthInput(e.target.value)}
                  onBlur={e => {
                    const n = Math.max(15, parseInt(e.target.value, 10) || 15);
                    set('reviewLength')(n);
                    setLengthInput(String(n));
                    e.target.style.borderColor = 'var(--line)';
                  }}
                  style={{ width: 90, padding: '7px 10px', border: '1px solid var(--line)',
                    borderRadius: 6, background: 'var(--bg-0)', color: 'var(--text-1)',
                    fontSize: 13, fontFamily: 'inherit', outline: 'none' }}
                  onFocus={e => { e.target.style.borderColor = 'var(--accent)'; }}
                />
              </div>
              <div style={{ fontSize: 12, color: 'var(--text-3)', paddingBottom: 9 }}>
                ≈ {(active.reviewLength / 60).toFixed(1)} min
              </div>
            </div>
          </div>
          <div style={{ borderTop: '1px solid var(--line)', padding: '10px 20px',
            background: 'var(--bg-1)', display: 'flex', gap: 8 }}>
            <button onClick={handleSave} className="btn btn-primary"
              style={{ fontSize: 12, display: 'flex', alignItems: 'center', gap: 5 }}>
              {saved ? <><Icons.check size={12}/> Saved</> : 'Save Changes'}
            </button>
            {prompts.length > 1 && (
              <button onClick={handleDelete}
                style={{ padding: '6px 12px', borderRadius: 6, border: '1px solid var(--line)',
                  background: 'transparent', color: 'var(--danger)', fontSize: 12,
                  cursor: 'pointer', fontFamily: 'inherit' }}>
                Delete
              </button>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

// ── Main page ──────────────────────────────────────────────────────────────────

function ScriptPage({ scripts, setScripts }) {
  const [view, setView]     = useState('products'); // 'products' | 'prompts'
  const [activeId, setActiveId] = useState(null);
  const [prompts, setPrompts]   = useState(loadPrompts);

  // Auto-select: pick first product when list changes and nothing is selected (or selection gone)
  const activeIdRef = useRef(activeId);
  activeIdRef.current = activeId;
  useEffect(() => {
    if (!scripts.length) { setActiveId(null); return; }
    if (activeIdRef.current && scripts.find(p => p.id === activeIdRef.current)) return;
    setActiveId(scripts[0].id);
  }, [scripts]);

  const activeProduct = scripts.find(p => p.id === activeId) || null;

  function handleChange(id, field, value) {
    setScripts(prev => prev.map(p => p.id === id ? { ...p, [field]: value } : p));
  }
  function handleStatusChange(id, status) {
    setScripts(prev => prev.map(p => p.id === id ? { ...p, status } : p));
  }

  return (
    <div className="page" style={{ display: 'flex', flexDirection: 'column' }}>
      {/* Page header */}
      <div className="page-header" style={{ flexShrink: 0 }}>
        <div className="page-title-block">
          <h1>Scripts</h1>
          <div className="subtitle">Generate structured script briefs from Amazon listings</div>
        </div>
        <div className="page-actions">
          <div style={{ display: 'flex', border: '1px solid var(--line)',
            borderRadius: 7, overflow: 'hidden' }}>
            {[['products', 'Products'], ['prompts', 'Prompts']].map(([v, label]) => (
              <button key={v} onClick={() => setView(v)}
                style={{ padding: '5px 16px', fontSize: 12, fontWeight: 500,
                  cursor: 'pointer', border: 'none', fontFamily: 'inherit',
                  background: view === v ? 'var(--accent)' : 'transparent',
                  color: view === v ? '#fff' : 'var(--text-2)',
                  transition: 'all 0.12s' }}>
                {label}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Body */}
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>

        {view === 'products' && (
          <>
            {/* Left: product list */}
            <div style={{ width: 220, borderRight: '1px solid var(--line)',
              display: 'flex', flexDirection: 'column', flexShrink: 0 }}>
              <div style={{ padding: '10px 12px 8px', borderBottom: '1px solid var(--line)',
                display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-3)',
                  textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                  {scripts.length} Product{scripts.length !== 1 ? 's' : ''}
                </span>
              </div>
              <ProductList scripts={scripts} activeId={activeId} onSelect={setActiveId}/>
            </div>

            {/* Right: editor or empty state */}
            {activeProduct ? (
              <ProductEditor
                product={activeProduct}
                prompts={prompts}
                onChange={handleChange}
                onStatusChange={handleStatusChange}
              />
            ) : (
              <div style={{ flex: 1, display: 'flex', flexDirection: 'column',
                alignItems: 'center', justifyContent: 'center', gap: 14 }}>
                <div style={{ width: 52, height: 52, borderRadius: 14,
                  background: 'var(--accent-soft)', display: 'grid',
                  placeItems: 'center', color: 'var(--accent)' }}>
                  <Icons.video size={22}/>
                </div>
                <div style={{ textAlign: 'center' }}>
                  <div style={{ fontWeight: 600, color: 'var(--text-1)', fontSize: 15, marginBottom: 4 }}>
                    Select a product to edit
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--text-3)' }}>
                    Or use the AIP extension on any Amazon product page
                  </div>
                </div>
              </div>
            )}
          </>
        )}

        {view === 'prompts' && (
          <PromptsPanel prompts={prompts} setPrompts={setPrompts}/>
        )}

      </div>
    </div>
  );
}
