// SCREEN: Video Intelligence
// Generate video scripts with AI, create hook variants, analyze retention patterns.

// ─── Mock data ────────────────────────────────────────────────────────────────
const VIDEO_MOCK_SCRIPT = {
  script_id: 'scr_001',
  topic: 'Why your attribution model is lying to you',
  platform: 'TikTok',
  duration_seconds: 60,
  target_audience: 'growth marketers',
  created_at: '2026-05-04T09:12:00Z',
  script: `[HOOK]
Your attribution model? It's lying to you.
Every day you're making budget decisions based on last-click data...
And every day, you're probably underfunding your best-performing channels.

[BODY]
Here's the truth: 73% of conversions touch 4+ channels before buying.
Last-click attribution credits just ONE of them.

So if someone sees your LinkedIn post, then a Meta ad, then searches Google —
Google gets 100% of the credit. LinkedIn and Meta get zero.

That means you defund LinkedIn. You pause Meta.
And then you wonder why conversions fall off a cliff.

Journey attribution fixes this by mapping EVERY touchpoint.
You can finally see which channels warm the lead vs. close the deal.

[CTA]
Drop a 🎯 if you want me to show you what journey attribution looks like.
And follow for more data-driven marketing breakdowns.`,
  hook_variants: [
    "You're losing budget every day because of one number on your dashboard.",
    'I analyzed $2M in ad spend. The attribution model was wrong 68% of the time.',
    'Hot take: last-click attribution is the most expensive lie in marketing.',
    "If your ROAS looks amazing, your attribution model might be covering up a disaster.",
  ],
  word_count: 158,
  char_count: 894,
};

const VIDEO_MOCK_HISTORY = [
  { script_id: 'scr_001', topic: 'Why your attribution model is lying to you', platform: 'TikTok',    duration_seconds: 60, created_at: '2026-05-04T09:12:00Z' },
  { script_id: 'scr_002', topic: '3 metrics every growth marketer tracks wrong', platform: 'Instagram', duration_seconds: 30, created_at: '2026-05-03T14:22:00Z' },
  { script_id: 'scr_003', topic: 'The RevOps stack that scales past $10M ARR',  platform: 'LinkedIn',   duration_seconds: 90, created_at: '2026-05-02T10:05:00Z' },
  { script_id: 'scr_004', topic: 'Why CAC keeps rising (and how to fix it)',     platform: 'YouTube',    duration_seconds: 60, created_at: '2026-05-01T16:40:00Z' },
  { script_id: 'scr_005', topic: 'TikTok vs Instagram Reels for B2B marketing',  platform: 'TikTok',    duration_seconds: 30, created_at: '2026-04-29T11:15:00Z' },
];

// Platform tips map
const VIDEO_PLATFORM_TIPS = {
  TikTok:    ['Hook must land in first 3 seconds', 'Use trending sounds to boost reach', '7-word CTAs outperform 12-word by 42%', 'Post between 6–9pm local time', 'Captions are indexed — include keywords'],
  Instagram: ['Captions drive 22% more saves', 'End on a strong visual cut', 'First frame = thumbnail, make it count', 'Carousel posts get 3x more reach than single images', 'Stories CTR peaks on Tues/Thurs'],
  YouTube:   ['Hook in the first 15s reduces drop-off by 30%', 'Add chapters for search discoverability', 'Shorts under 60s get pushed to Shorts feed', 'End screen + cards boost watch time', 'Title keyword front-loaded = higher CTR'],
  LinkedIn:  ['Thought leadership > promotional content', 'Carousels get 3x reach vs plain video', 'Native video (uploaded) outperforms YouTube links', 'Best reach: Tues–Thurs 8–10am', 'Text posts still outperform video on average — pair both'],
};

// ─── Sub-components ───────────────────────────────────────────────────────────

// Hook variant prediction badge
const VideoPerfBadge = ({ level }) => {
  const map = {
    High:   { cls: 'green',  label: 'High CTR' },
    Medium: { cls: 'amber',  label: 'Medium CTR' },
    Low:    { cls: 'plain',  label: 'Low CTR' },
  };
  const b = map[level] || map.Medium;
  return <span className={`badge ${b.cls}`}>{b.label}</span>;
};

// Hook performance prediction (heuristic based on hook text)
const predictHookPerf = (text) => {
  const lower = text.toLowerCase();
  if (lower.includes('you') && (lower.includes('?') || lower.includes('every'))) return 'High';
  if (lower.includes('$') || lower.includes('million') || lower.includes('%')) return 'High';
  if (lower.includes('hot take') || lower.includes('wrong') || lower.includes('lying')) return 'High';
  if (lower.includes('how') || lower.includes('why') || lower.includes('what')) return 'Medium';
  return 'Low';
};

// Estimate read time from word count
const estimateReadTime = (text) => {
  const words = (text || '').trim().split(/\s+/).length;
  const wps = 2.5; // words per second (presenter pace)
  const secs = Math.round(words / wps);
  return { words, chars: text.length, secs };
};

// Format platform duration label
const fmtDuration = (s) => s < 60 ? `${s}s` : `${s / 60}m`;

// Format relative time
const fmtRelTime = (iso) => {
  const diff = Date.now() - new Date(iso).getTime();
  const h = Math.round(diff / 3600000);
  if (h < 1) return 'just now';
  if (h < 24) return `${h}h ago`;
  return `${Math.round(h / 24)}d ago`;
};

// ─── Script Display ───────────────────────────────────────────────────────────
const VideoScriptDisplay = ({ script }) => {
  const lines = (script || '').split('\n');
  const stats = estimateReadTime(script || '');

  const renderLine = (line, idx) => {
    if (line.startsWith('[HOOK]')) {
      return <div key={idx} style={{color: 'var(--accent)', fontWeight: 600, fontSize: 11, letterSpacing: '0.08em', marginTop: idx > 0 ? 12 : 0}}>{line}</div>;
    }
    if (line.startsWith('[BODY]')) {
      return <div key={idx} style={{color: 'var(--cyan)', fontWeight: 600, fontSize: 11, letterSpacing: '0.08em', marginTop: 12}}>{line}</div>;
    }
    if (line.startsWith('[CTA]')) {
      return <div key={idx} style={{color: 'var(--emerald)', fontWeight: 600, fontSize: 11, letterSpacing: '0.08em', marginTop: 12}}>{line}</div>;
    }
    if (line.trim() === '') {
      return <div key={idx} style={{height: 6}} />;
    }
    // Determine section color based on preceding section header
    let prevSection = 'body';
    for (let i = idx - 1; i >= 0; i--) {
      if (lines[i].startsWith('[HOOK]')) { prevSection = 'hook'; break; }
      if (lines[i].startsWith('[BODY]')) { prevSection = 'body'; break; }
      if (lines[i].startsWith('[CTA]'))  { prevSection = 'cta';  break; }
    }
    const color = prevSection === 'hook' ? 'rgba(139,92,246,0.9)' : prevSection === 'cta' ? 'rgba(16,185,129,0.9)' : 'var(--text-1)';
    return (
      <div key={idx} style={{display: 'flex', gap: 12, alignItems: 'flex-start'}}>
        <span className="mono" style={{fontSize: 10, color: 'var(--text-4)', flexShrink: 0, paddingTop: 2, minWidth: 24, textAlign: 'right'}}>{idx + 1}</span>
        <span style={{fontSize: 13, lineHeight: 1.65, color}}>{line}</span>
      </div>
    );
  };

  return (
    <div>
      {/* Stats bar */}
      <div style={{display: 'flex', gap: 16, fontSize: 11, color: 'var(--text-3)', marginBottom: 14, flexWrap: 'wrap'}}>
        <span className="mono">{stats.words} words</span>
        <span className="mono">{stats.chars} chars</span>
        <span className="mono">~{stats.secs}s read time</span>
        <span className="mono" style={{color: stats.secs > 65 ? 'var(--rose)' : stats.secs < 45 ? 'var(--amber)' : 'var(--emerald)'}}>
          {stats.secs > 65 ? '⚠ Over target' : stats.secs < 45 ? '⚠ Under target' : '✓ On target'}
        </span>
      </div>
      {/* Script body (terminal-style) */}
      <div style={{background: 'var(--bg-0)', border: '1px solid var(--border)', borderRadius: 8, padding: '14px 16px', fontFamily: 'var(--mono)', fontSize: 13, display: 'flex', flexDirection: 'column', gap: 2, lineHeight: 1.7, overflowY: 'auto', maxHeight: 440}}>
        {lines.map((line, i) => renderLine(line, i))}
      </div>
    </div>
  );
};

// ─── Hook Variants ────────────────────────────────────────────────────────────
const VideoHookVariants = ({ hooks }) => {
  const [copiedIdx, setCopiedIdx] = React.useState(null);
  const copyTimer = React.useRef(null);

  const handleCopy = (text, idx) => {
    navigator.clipboard.writeText(text)
      .then(() => {
        setCopiedIdx(idx);
        clearTimeout(copyTimer.current); copyTimer.current = setTimeout(() => setCopiedIdx(null), 2000);
      })
      .catch(() => {});
  };

  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
      {hooks.map((hook, i) => {
        const perf = predictHookPerf(hook);
        return (
          <div key={i} style={{display: 'flex', alignItems: 'flex-start', gap: 12, padding: '12px 14px', background: 'var(--bg-3)', border: '1px solid var(--border)', borderRadius: 8}}>
            <span className="mono" style={{fontSize: 11, color: 'var(--text-4)', paddingTop: 2, minWidth: 18}}>#{i + 1}</span>
            <div style={{flex: 1, fontSize: 13, color: 'var(--text-1)', lineHeight: 1.55}}>{hook}</div>
            <div style={{display: 'flex', gap: 8, alignItems: 'center', flexShrink: 0}}>
              <VideoPerfBadge level={perf} />
              <button className="btn ghost" style={{fontSize: 11, padding: '3px 8px', color: copiedIdx === i ? 'var(--emerald)' : 'var(--text-3)'}} onClick={() => handleCopy(hook, i)}>
                <Icon name={copiedIdx === i ? 'check' : 'copy'} size={11} />
                {copiedIdx === i ? 'Copied' : 'Copy'}
              </button>
            </div>
          </div>
        );
      })}
    </div>
  );
};

// ─── Platform Tips ────────────────────────────────────────────────────────────
const VideoPlatformTips = ({ platform }) => {
  const tips = VIDEO_PLATFORM_TIPS[platform] || VIDEO_PLATFORM_TIPS.TikTok;
  return (
    <div style={{display: 'flex', gap: 10, flexWrap: 'wrap'}}>
      {tips.map((tip, i) => (
        <div key={i} style={{display: 'flex', alignItems: 'flex-start', gap: 8, padding: '8px 12px', background: 'var(--bg-3)', border: '1px solid var(--border)', borderRadius: 6, fontSize: 12, color: 'var(--text-2)', lineHeight: 1.4, flex: '1 1 220px'}}>
          <span style={{color: 'var(--accent)', flexShrink: 0, marginTop: 1}}>→</span>
          {tip}
        </div>
      ))}
    </div>
  );
};

// ─── Script History Table ─────────────────────────────────────────────────────
const VideoHistoryTable = ({ history, onLoad }) => (
  <div style={{overflow: 'auto'}}>
    <table className="data-table">
      <thead>
        <tr>
          <th>Topic</th>
          <th>Platform</th>
          <th style={{textAlign: 'center'}}>Duration</th>
          <th>Created</th>
          <th style={{textAlign: 'right'}}>Actions</th>
        </tr>
      </thead>
      <tbody>
        {history.map((s, i) => (
          <tr key={s.script_id} style={{cursor: 'pointer'}} onClick={() => onLoad && onLoad(s)}>
            <td style={{color: 'var(--text-1)', fontWeight: 500, maxWidth: 280}}>
              <span style={{fontSize: 13}}>{s.topic}</span>
            </td>
            <td>
              <span className="badge cyan" style={{fontSize: 11}}>{s.platform}</span>
            </td>
            <td className="mono" style={{textAlign: 'center', fontSize: 12}}>{fmtDuration(s.duration_seconds)}</td>
            <td style={{fontSize: 12, color: 'var(--text-3)'}}>{fmtRelTime(s.created_at)}</td>
            <td style={{textAlign: 'right'}}>
              <div style={{display: 'flex', gap: 6, justifyContent: 'flex-end'}}>
                <button className="btn ghost" style={{fontSize: 11, padding: '3px 8px'}} onClick={e => { e.stopPropagation(); onLoad && onLoad(s); }}>
                  <Icon name="eye" size={11} /> View
                </button>
                <button className="btn ghost" style={{fontSize: 11, padding: '3px 8px'}} onClick={e => { e.stopPropagation(); navigator.clipboard.writeText(s.topic).catch(() => {}); }}>
                  <Icon name="copy" size={11} /> Copy
                </button>
              </div>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  </div>
);

// ─── Main Screen ──────────────────────────────────────────────────────────────
const VideoScreen = () => {
  // Form state (left panel)
  const [form, setForm] = React.useState({
    topic: 'Why your attribution model is lying to you',
    platform: 'TikTok',
    duration_seconds: 60,
    target_audience: 'growth marketers',
  });

  // Script output state
  const [currentScript, setCurrentScript] = React.useState(VIDEO_MOCK_SCRIPT);
  const [generating, setGenerating] = React.useState(false);
  const [history, setHistory] = React.useState(VIDEO_MOCK_HISTORY);
  const genCountRef = React.useRef(0);
  const loadCountRef = React.useRef(0);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  // Attempt to load script history
  React.useEffect(() => {
    arFetch('/v1/video/scripts')
      .then(d => { if (Array.isArray(d) && d.length) setHistory(d); })
      .catch(() => {});
  }, []);

  // Generate script
  const handleGenerate = () => {
    if (!form.topic.trim()) return;
    genCountRef.current += 1; const myGen = genCountRef.current;
    setGenerating(true);
    arFetch('/v1/video/script', { method: 'POST', body: JSON.stringify({ ...form, duration_seconds: parseInt(form.duration_seconds) }) })
      .then(d => {
        if (d && (d.script || d.script_id)) {
          if (genCountRef.current !== myGen) return;
          setCurrentScript(d);
          // Prepend to history
          setHistory(prev => [{ script_id: d.script_id, topic: form.topic, platform: form.platform, duration_seconds: parseInt(form.duration_seconds), created_at: d.created_at || new Date().toISOString() }, ...prev.slice(0, 9)]);
        } else {
          if (genCountRef.current !== myGen) return;
          setCurrentScript({ ...VIDEO_MOCK_SCRIPT, topic: form.topic, platform: form.platform, duration_seconds: parseInt(form.duration_seconds) });
        }
      })
      .catch(() => {
        // Silently use MOCK with current form values
        if (genCountRef.current !== myGen) return;
        setCurrentScript({ ...VIDEO_MOCK_SCRIPT, topic: form.topic, platform: form.platform, duration_seconds: parseInt(form.duration_seconds) });
      })
      .finally(() => setGenerating(false));
  };

  const handleLoadFromHistory = (entry) => {
    loadCountRef.current += 1; const myLoad = loadCountRef.current;
    setForm(f => ({
      ...f,
      topic: entry.topic,
      platform: entry.platform,
      duration_seconds: parseInt(entry.duration_seconds) || 60,
    }));
    arFetch(`/v1/video/scripts/${entry.script_id || entry.id}`)
      .then(d => {
        if (loadCountRef.current !== myLoad) return;
        if (d && d.output_json) setCurrentScript(d.output_json);
        else setCurrentScript({ ...VIDEO_MOCK_SCRIPT, topic: entry.topic });
      })
      .catch(() => {
        if (loadCountRef.current !== myLoad) return;
        setCurrentScript({ ...VIDEO_MOCK_SCRIPT, topic: entry.topic });
      });
  };

  const inputStyle = { width: '100%', padding: '8px 12px', background: 'var(--bg-3)', border: '1px solid var(--border)', borderRadius: 8, color: 'var(--text-1)', fontSize: 13, outline: 'none', fontFamily: 'inherit' };
  const labelStyle = { fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 6, display: 'block' };

  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 20}}>

      {/* ── Header ── */}
      <div>
        <div style={{fontSize: 11, color: 'var(--text-4)', fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 6}}>Creator Suite / Video</div>
        <div style={{fontSize: 24, fontWeight: 700, letterSpacing: '-0.02em'}}>Video Intelligence</div>
        <div style={{fontSize: 13, color: 'var(--text-3)', marginTop: 2}}>Generate AI scripts, create hook variants for A/B testing, and analyse retention patterns</div>
      </div>

      {/* ── Main two-column layout ── */}
      <div style={{display: 'grid', gridTemplateColumns: '2fr 3fr', gap: 16, alignItems: 'start'}}>

        {/* ── LEFT: Script Generator Form ── */}
        <div style={{display: 'flex', flexDirection: 'column', gap: 0}}>
          <div className="card" style={{display: 'flex', flexDirection: 'column', gap: 16}}>
            {/* Card header */}
            <div className="card-header" style={{marginBottom: 4}}>
              <div>
                <div className="card-title">Script Generator</div>
                <div className="card-sub">Configure your video parameters</div>
              </div>
              <Icon name="play" size={16} style={{color: 'var(--accent)'}} />
            </div>

            {/* Topic */}
            <div>
              <label style={labelStyle}>Topic / Hook Idea *</label>
              <textarea
                value={form.topic}
                onChange={e => set('topic', e.target.value)}
                rows={3}
                style={{...inputStyle, resize: 'vertical', lineHeight: 1.5}}
                placeholder="e.g. Why your attribution model is lying to you"
              />
            </div>

            {/* Platform */}
            <div>
              <label style={labelStyle}>Platform</label>
              <select style={inputStyle} value={form.platform} onChange={e => set('platform', e.target.value)}>
                <option value="TikTok">TikTok</option>
                <option value="Instagram">Instagram Reels</option>
                <option value="YouTube">YouTube Shorts</option>
                <option value="LinkedIn">LinkedIn</option>
              </select>
            </div>

            {/* Duration */}
            <div>
              <label style={labelStyle}>Duration</label>
              <div className="seg">
                {[15, 30, 60, 90].map(d => (
                  <button key={d} className={form.duration_seconds === d ? 'active' : ''} onClick={() => set('duration_seconds', d)}>{d}s</button>
                ))}
              </div>
            </div>

            {/* Target audience */}
            <div>
              <label style={labelStyle}>Target Audience</label>
              <input style={inputStyle} value={form.target_audience} onChange={e => set('target_audience', e.target.value)} placeholder="e.g. growth marketers, CMOs, founders" />
            </div>

            {/* Generate button */}
            <button className="btn primary" style={{width: '100%', justifyContent: 'center', marginTop: 4}} disabled={generating || !form.topic.trim()} onClick={handleGenerate}>
              {generating ? (
                <>
                  <span className="dot pulse violet" style={{width: 8, height: 8, marginRight: 4}} />
                  Generating script…
                </>
              ) : (
                <>
                  <Icon name="sparkle" size={13} />
                  Generate Script
                </>
              )}
            </button>
          </div>
        </div>

        {/* ── RIGHT: Generated Script Output ── */}
        <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>
          <div className="card">
            <div className="card-header">
              <div>
                <div className="card-title">{currentScript ? currentScript.topic : 'Script Output'}</div>
                <div className="card-sub">
                  {currentScript ? `${currentScript.platform} · ${fmtDuration(currentScript.duration_seconds)} · ${currentScript.target_audience || form.target_audience}` : 'Generated script will appear here'}
                </div>
              </div>
              <div style={{display: 'flex', gap: 6}}>
                {/* Section legend */}
                <span style={{fontSize: 10, color: 'var(--accent)', fontFamily: 'var(--mono)'}}>[HOOK]</span>
                <span style={{fontSize: 10, color: 'var(--text-3)', fontFamily: 'var(--mono)'}}>[BODY]</span>
                <span style={{fontSize: 10, color: 'var(--cyan)', fontFamily: 'var(--mono)'}}>[CTA]</span>
              </div>
            </div>

            {generating && (
              <div style={{padding: 40, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, color: 'var(--text-3)'}}>
                <span className="dot pulse violet" style={{width: 14, height: 14}} />
                <div style={{fontSize: 13}}>Generating your {fmtDuration(form.duration_seconds)} {form.platform} script…</div>
                <div style={{fontSize: 11, color: 'var(--text-4)', fontFamily: 'var(--mono)'}}>topic="{form.topic.slice(0, 50)}{form.topic.length > 50 ? '…' : ''}"</div>
              </div>
            )}

            {!generating && currentScript && (
              <VideoScriptDisplay script={currentScript.script} />
            )}

            {!generating && !currentScript && (
              <div style={{padding: 40, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, color: 'var(--text-4)', textAlign: 'center'}}>
                <Icon name="play" size={28} />
                <div style={{fontSize: 13}}>Configure your parameters and click Generate Script.</div>
              </div>
            )}
          </div>

          {/* ── Hook Variants ── */}
          {currentScript && currentScript.hook_variants && currentScript.hook_variants.length > 0 && !generating && (
            <div className="card">
              <div className="card-header">
                <div>
                  <div className="card-title">Hook Variants</div>
                  <div className="card-sub">A/B test these alternative opening lines</div>
                </div>
                <span className="badge violet">{currentScript.hook_variants.length} variants</span>
              </div>
              <VideoHookVariants hooks={currentScript.hook_variants} />
            </div>
          )}
        </div>
      </div>

      {/* ── Platform Tips ── */}
      <div className="card">
        <div className="card-header">
          <div>
            <div className="card-title">Platform Tips — {form.platform}</div>
            <div className="card-sub">Best practices that update based on your selected platform</div>
          </div>
          <Icon name="bulb" size={14} style={{color: 'var(--amber)'}} />
        </div>
        <VideoPlatformTips platform={form.platform} />
      </div>

      {/* ── Script History ── */}
      <div className="card" style={{padding: 0}}>
        <div style={{padding: '16px 16px 0', marginBottom: 2}}>
          <div className="card-title">Script Library</div>
          <div className="card-sub">Click a row to load the script in the editor above</div>
        </div>
        <VideoHistoryTable history={history} onLoad={handleLoadFromHistory} />
      </div>

    </div>
  );
};

window.VideoScreen = VideoScreen;
