'use client'; import React, { useState, useEffect, useRef } from 'react'; import Link from 'next/link'; import { useAuth } from '@/contexts/AuthContext'; import { useRouter } from 'next/navigation'; import { BB_PEN_NAMES, AV_PEN_NAMES } from '@/lib/auth/permissions'; // ─── Types ──────────────────────────────────────────────────────────────────── interface Message { id: string; role: 'user' | 'assistant'; content: string; timestamp: Date; provider?: 'ollama' | 'anthropic'; } interface Session { id: string; site_id: number; pen_name: string | null; first_message_preview: string; provider_used: string; last_message_at: string; } interface AIStatus { ollama: { online: boolean; latencyMs: number; models: string[] }; anthropic: { configured: boolean }; currentProvider: 'ollama' | 'anthropic'; } // ─── Pen name style guide data ──────────────────────────────────────────────── interface PenNameProfile { name: string; title: string; beat: string; site: 'BB' | 'AV'; styleNotes: string; toneKeywords: string[]; exampleLead: string; } const PEN_NAME_PROFILES: PenNameProfile[] = [ { name: 'Michael Strand', title: 'Senior Technology Editor', site: 'BB', beat: 'Broadcast technology, industry news, NAB Show primary correspondent', styleNotes: 'Authoritative and comprehensive. Leads with the big-picture industry implication before drilling into product specifics. Favors longer paragraphs with technical depth. Uses precise broadcast engineering terminology without over-explaining.', toneKeywords: ['authoritative', 'comprehensive', 'technical', 'industry-wide'], exampleLead: 'The shift toward IP-based production infrastructure reached a new milestone this week as...', }, { name: 'David Harlow', title: 'Broadcast Engineering Correspondent', site: 'BB', beat: 'Broadcast engineering, transmission, RF, satellite, signal distribution', styleNotes: 'Engineering-first perspective. Leads with the technical specification or engineering challenge being solved. Uses RF and transmission terminology fluently. Concise, factual sentences. Avoids marketing language entirely.', toneKeywords: ['engineering-focused', 'technical', 'concise', 'specification-driven'], exampleLead: 'A new RF transmission system capable of sustaining 4K HDR delivery across legacy infrastructure...', }, { name: 'Karen Fielding', title: 'Post Production Editor', site: 'BB', beat: 'Post production, editing, color grading, VFX, media asset management', styleNotes: 'Workflow-oriented. Explains how tools fit into real post production pipelines. Speaks to colorists, editors, and MAM administrators. Uses post-specific terminology (LUT, roundtrip, proxy, conform) naturally.', toneKeywords: ['workflow-focused', 'practical', 'pipeline-aware', 'post-specific'], exampleLead: 'Colorists working in high-volume episodic environments will find the new grading pipeline...', }, { name: 'James Mercer', title: 'NAB Show Senior Correspondent', site: 'BB', beat: 'NAB Show Las Vegas, NAB Show New York, show floor coverage, exhibitor news', styleNotes: 'Show-floor energy. Vivid, present-tense descriptions of booth experiences and product demos. Contextualizes announcements within the broader NAB narrative. Primary byline for all major NAB pillar content.', toneKeywords: ['show-floor', 'vivid', 'contextual', 'event-driven'], exampleLead: 'Walking the South Hall at NAB Show Las Vegas, the density of IP production announcements...', }, { name: 'Peter Calloway', title: 'Radio & Transmission Reporter', site: 'BB', beat: 'Radio broadcasting, AM/FM/DAB, transmission infrastructure, tower and antenna technology', styleNotes: 'Radio-industry insider voice. Understands the economics of tower infrastructure and the regulatory landscape. Writes for station engineers and broadcast directors. Straightforward, no-nonsense style.', toneKeywords: ['radio-focused', 'regulatory-aware', 'infrastructure', 'practical'], exampleLead: 'Station engineers managing aging AM transmitter infrastructure now have a cost-effective upgrade path...', }, { name: 'Sandra Voss', title: 'Production Technology Editor', site: 'BB', beat: 'Studio production, cameras, switchers, graphics systems, live production', styleNotes: 'Live production specialist. Focuses on the director and technical director perspective. Evaluates cameras and switchers in terms of production flexibility and reliability under live conditions.', toneKeywords: ['live-production', 'reliability-focused', 'director-perspective', 'studio-aware'], exampleLead: "Technical directors running multi-camera live productions will appreciate the new switcher's...", }, { name: 'Brian Kowalski', title: 'Streaming & OTT Correspondent', site: 'BB', beat: 'Streaming technology, OTT platforms, CDN, video delivery, cloud broadcast', styleNotes: 'Cloud-native perspective. Comfortable with CDN architecture, encoding ladders, and OTT business models. Writes for streaming engineers and platform operators. Uses streaming-specific metrics (rebuffering rate, ABR, latency).', toneKeywords: ['cloud-native', 'platform-aware', 'metrics-driven', 'OTT-focused'], exampleLead: 'As sub-second latency becomes table stakes for live streaming, the new delivery architecture...', }, { name: 'Laura Pennington', title: 'Industry News Editor', site: 'BB', beat: 'Company news, acquisitions, appointments, executive moves, industry business coverage', styleNotes: 'Business journalism style. Leads with the news fact, then provides context and industry reaction. Quotes executives accurately. Covers M&A with an understanding of strategic rationale.', toneKeywords: ['business-journalism', 'fact-first', 'executive-focused', 'strategic'], exampleLead: "The broadcast industry's transition to cloud production is accelerating faster than most analysts predicted...", }, { name: 'Thomas Reeves', title: 'Audio Technology Correspondent', site: 'BB', beat: 'Broadcast audio, mixing consoles, audio processing, AES Convention coverage', styleNotes: "Broadcast audio engineer's perspective. Evaluates consoles and processors from a workflow standpoint. Uses AES and SMPTE audio terminology. Covers both technical specifications and operational workflow.", toneKeywords: ['audio-engineering', 'AES-fluent', 'console-focused', 'workflow-aware'], exampleLead: 'Broadcast audio engineers demanding more flexible routing in live production environments...', }, { name: 'Christine Vale', title: 'Business & Industry Reporter', site: 'BB', beat: 'Industry analysis, market trends, opinion, business of broadcast', styleNotes: 'Analytical and opinion-forward. Comfortable with market data and industry forecasts. Writes longer-form analysis pieces. Challenges conventional wisdom when data supports it.', toneKeywords: ['analytical', 'opinion-forward', 'data-driven', 'market-aware'], exampleLead: "The broadcast industry's transition to cloud production is accelerating faster than most analysts predicted...", }, { name: 'Marcus Webb', title: 'Live Production Correspondent', site: 'BB', beat: 'Live events, sports broadcasting, remote production, REMI and IP production workflows', styleNotes: 'Sports and live events specialist. Understands REMI/at-home production economics. Writes for remote production engineers and sports broadcast directors. Covers IP workflows in the context of real production deployments.', toneKeywords: ['sports-broadcast', 'REMI-focused', 'IP-production', 'event-driven'], exampleLead: 'The remote production workflow deployed for last season\'s playoff coverage has now become...', }, { name: 'Ellen Forsythe', title: 'International Markets Editor', site: 'BB', beat: 'IBC Show, BroadcastAsia, CABSAT, international broadcast markets', styleNotes: 'International perspective. Contextualizes technology announcements within regional market dynamics. Covers IBC and BroadcastAsia with an understanding of European and Asian regulatory environments.', toneKeywords: ['international', 'market-contextual', 'regulatory-aware', 'IBC-focused'], exampleLead: 'European broadcasters navigating the DVB-I transition are finding new deployment options...', }, { name: 'Rex Chandler', title: 'AV Integration Senior Correspondent', site: 'AV', beat: 'AV systems integration, integrator news, company announcements, InfoComm coverage', styleNotes: 'Integration-industry insider. Writes for AV integrators and systems designers. Understands the full project lifecycle from design through commissioning. Primary InfoComm correspondent.', toneKeywords: ['integration-focused', 'project-lifecycle', 'integrator-voice', 'InfoComm-primary'], exampleLead: 'AV integrators tackling large-scale corporate campus deployments now have a unified platform...', }, { name: 'Dana Flux', title: 'Digital Signage & Display Editor', site: 'AV', beat: 'Digital signage, LED walls, display technology, CMS platforms', styleNotes: 'Display technology specialist. Evaluates LED walls and CMS platforms from a deployment and content management perspective. Understands pixel pitch, brightness specs, and content scheduling workflows.', toneKeywords: ['display-focused', 'CMS-aware', 'deployment-practical', 'spec-driven'], exampleLead: "The latest generation of fine-pitch LED displays is pushing the boundaries of what's achievable...", }, { name: 'Derek Wainwright', title: 'Unified Communications Correspondent', site: 'AV', beat: 'UC&C, video conferencing, hybrid meeting rooms, Microsoft Teams Rooms, Zoom Rooms', styleNotes: 'UC&C specialist. Writes for IT managers and AV integrators deploying hybrid meeting solutions. Understands the Microsoft and Zoom certification ecosystems. Focuses on user experience and IT manageability.', toneKeywords: ['UC-focused', 'hybrid-work', 'IT-aware', 'certification-fluent'], exampleLead: 'As hybrid work becomes permanent, IT managers are demanding meeting room solutions that...', }, { name: 'Sloane Rigging', title: 'Installed AV & Audio Editor', site: 'AV', beat: 'Installed audio, sound reinforcement, houses of worship AV, DSP, loudspeakers', styleNotes: 'Installed audio specialist. Writes for system designers and audio consultants. Understands DSP configuration, loudspeaker coverage patterns, and the unique requirements of houses of worship.', toneKeywords: ['installed-audio', 'DSP-fluent', 'worship-AV', 'system-design'], exampleLead: 'Houses of worship seeking intelligible speech reinforcement across challenging acoustical spaces...', }, { name: 'Chip Crosspoint', title: 'AV Networking & Technology Correspondent', site: 'AV', beat: 'AV-over-IP, Dante, IPMX, control systems, IT/AV convergence', styleNotes: 'AV networking deep-diver. Comfortable with Dante, IPMX, and AES67 at a technical level. Writes for AV engineers and IT/AV convergence specialists. Explains complex networking concepts clearly.', toneKeywords: ['AV-networking', 'Dante-fluent', 'IPMX-aware', 'IT-AV-convergence'], exampleLead: 'The adoption of IPMX as a unified AV-over-IP standard is accelerating as major manufacturers...', }, { name: 'Blair Presenter', title: 'Education & Corporate AV Editor', site: 'AV', beat: 'Education AV, classroom technology, corporate AV, government AV, ISE coverage', styleNotes: 'Education and corporate AV specialist. Understands the procurement cycles and budget constraints of K-12, higher education, and government AV. ISE correspondent.', toneKeywords: ['education-AV', 'corporate-AV', 'procurement-aware', 'ISE-focused'], exampleLead: 'K-12 districts managing post-pandemic classroom technology refreshes are finding that...', }, { name: 'Jordan Lumen', title: 'Display & Visualization Correspondent', site: 'AV', beat: 'Projectors, large-venue displays, video walls, visualization technology, simulation', styleNotes: 'Large-venue display specialist. Evaluates projectors and video walls for large-venue and simulation applications. Understands lumen output, throw ratios, and blending technology.', toneKeywords: ['large-venue', 'projection-focused', 'simulation-aware', 'visualization'], exampleLead: 'Large-venue integrators specifying projection systems for auditoriums and simulation centers...', }, ]; const QUICK_ACTIONS = [ { label: 'New Story from URL', key: 'url_story' }, { label: 'Write Exhibitor Preview', key: 'exhibitor_preview' }, { label: 'Rewrite Press Release', key: 'press_release' }, { label: 'Generate NAB Story', key: 'nab_story' }, { label: 'Generate InfoComm Story', key: 'infocomm_story' }, { label: 'Social Media Posts', key: 'social_posts' }, { label: 'Story Headline Options', key: 'headlines' }, { label: 'Translate Story', key: 'translate' }, { label: 'Company Bio', key: 'company_bio' }, { label: 'Product Description', key: 'product_desc' }, ]; const QUICK_ACTION_TEMPLATES: Record = { url_story: `Write a news story for [Broadcast Beat / AV Beat] based on this URL: [URL]. Use the byline [pen name]. Target length: [400-600] words. Focus angle: [product launch / company news / industry trend].`, exhibitor_preview: `Write a pre-show exhibitor preview for [company name] at [NAB Show / InfoComm] [year]. They will be showing [product/technology]. Booth: [number if known]. Use [pen name] byline. 400-500 words.`, press_release: `Rewrite the following press release as a real news story for [Broadcast Beat / AV Beat]. Remove marketing language, lead with the news hook, add industry context. Byline: [pen name]. [PASTE PRESS RELEASE HERE]`, nab_story: `Write a [story type: preview / announcement / recap] story about [topic/company] for NAB Show [year]. Include relevant SEO keywords. Byline: James Mercer. [400-800] words.`, infocomm_story: `Write a [story type: preview / announcement / recap] story about [topic/company] for InfoComm [year]. Include relevant SEO keywords. Byline: Rex Chandler. [400-800] words.`, social_posts: `Generate social media posts for the following story. Create versions for: Twitter/X (280 chars max), LinkedIn (professional tone, 150 words max), Facebook (conversational, 100 words max). Story headline: [HEADLINE] Story summary: [SUMMARY]`, headlines: `Generate 8 headline options for this story. Include 2 SEO-optimized versions targeting [keyword], 2 social media-friendly versions, 2 trade publication style versions, and 2 alternatives. Story summary: [SUMMARY]`, translate: `Translate the following story into [language]. Maintain the professional trade publication tone. Keep technical terms in their internationally recognized form. [PASTE STORY HERE]`, company_bio: `Write a 150-word company bio for [company name] suitable for use as a boilerplate paragraph at the end of news stories on [Broadcast Beat / AV Beat]. The company makes [products/services]. Website: [URL].`, product_desc: `Write a 200-word product description for [product name] by [company]. Key features: [features]. Target audience: [integrators / broadcast engineers / etc]. Suitable for use in a product announcement story.`, }; function renderMarkdown(text: string): string { return text .replace(/^### (.+)$/gm, '

$1

') .replace(/^## (.+)$/gm, '

$1

') .replace(/^# (.+)$/gm, '

$1

') .replace(/\*\*(.+?)\*\*/g, '$1') .replace(/\*(.+?)\*/g, '$1') .replace(/`([^`]+)`/g, '$1') .replace(/^- (.+)$/gm, '
  • $1
  • ') .replace(/^\d+\. (.+)$/gm, '
  • $1
  • ') .replace(/\n\n/g, '

    ') .replace(/\n/g, '
    '); } // ─── Draft Preview Modal ─────────────────────────────────────────────────────── interface DraftPreviewModalProps { content: string; title: string; penName: string; siteId: number; onClose: () => void; onSave: (openEditor: boolean) => void; } function DraftPreviewModal({ content, title, penName, siteId, onClose, onSave }: DraftPreviewModalProps) { const wordCount = content.replace(/<[^>]+>/g, '').split(/\s+/).filter(Boolean).length; return (

    e.stopPropagation()} >

    Draft Preview

    Review before saving to {siteId === 1 ? 'Broadcast Beat' : 'AV Beat'}

    Byline: {penName}
    Site: {siteId === 2 ? 'AV Beat' : 'Broadcast Beat'}
    Words: {wordCount}
    Status: Draft

    Title

    {title || 'Untitled Draft'}

    ${renderMarkdown(content)}

    `, }} />
    ); } // ─── Regenerate Modal ────────────────────────────────────────────────────────── interface RegenerateModalProps { onClose: () => void; onRegenerate: (prompt: string) => void; } function RegenerateModal({ onClose, onRegenerate }: RegenerateModalProps) { const [customPrompt, setCustomPrompt] = useState(''); const [selectedVariant, setSelectedVariant] = useState(null); const variants = [ { label: 'Different angle', prompt: 'Regenerate this with a completely different angle and approach.' }, { label: 'More technical', prompt: 'Regenerate this with more technical depth and engineering detail.' }, { label: 'More concise', prompt: 'Regenerate this as a shorter, more concise version (under 300 words).' }, { label: 'More conversational', prompt: 'Regenerate this with a more conversational, accessible tone.' }, { label: 'Lead with data', prompt: 'Regenerate this leading with industry data, statistics, or market context.' }, { label: 'Stronger headline', prompt: 'Keep the same content but rewrite with a stronger, more compelling headline and opening paragraph.' }, { label: 'Add quotes', prompt: 'Regenerate this and add realistic attributed quotes from company executives.' }, { label: 'SEO optimized', prompt: 'Regenerate this with stronger SEO optimization — include keyword-rich subheadings and a meta description.' }, ]; const handleSubmit = () => { const prompt = customPrompt.trim() || selectedVariant || 'Please regenerate the previous response with a different approach.'; onRegenerate(prompt); onClose(); }; return (
    e.stopPropagation()} >

    Regenerate with Different Prompt

    Quick Variants

    {variants.map(v => ( ))}

    Or Write Custom Instructions