// PromptsView.jsx — AI Prompts with Premium Presentation Mode
const { useState, useEffect, useRef, useMemo } = React;

function syntaxHighlight(jsonObj) {
  let json = typeof jsonObj !== 'string' ? JSON.stringify(jsonObj, null, 2) : jsonObj;
  if (typeof jsonObj === 'string') {
    try {
      const parsed = JSON.parse(jsonObj);
      json = JSON.stringify(parsed, null, 2);
    } catch (e) {
      return json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }
  }
  json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
    let cls = 'color: var(--accent-strong);';
    if (/^"/.test(match)) {
      if (/:$/.test(match)) cls = 'color: var(--ink); font-weight: 600;';
      else cls = 'color: var(--pos);';
    } else if (/true|false/.test(match)) {
      cls = 'color: #d946ef; font-weight: 600;';
    } else if (/null/.test(match)) {
      cls = 'color: var(--ink-3); font-weight: 600;';
    }
    return '<span style="' + cls + '">' + match + '</span>';
  });
}

// SVG Icons
const IconFile = (p) => <Ico {...p}><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></Ico>;
const IconRocket = (p) => <Ico {...p}><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"/><path d="M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"/><path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"/><path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"/></Ico>;
const IconMonitorPlay = (p) => <Ico {...p}><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/><polygon points="10 7 15 10 10 13 10 7"/></Ico>;
const IconChevronLeft = (p) => <Ico {...p}><polyline points="15 18 9 12 15 6"/></Ico>;
const IconChevronRight = (p) => <Ico {...p}><polyline points="9 18 15 12 9 6"/></Ico>;
const IconX = (p) => <Ico {...p}><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></Ico>;
const IconClock = (p) => <Ico {...p}><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></Ico>;

const PROMPTS_CONFIG = {
  '1': {
    title: '1. เช็กสุขภาพบัญชีด่วน', badge: 'READ', icon: IconActivity,
    instruction: (d) => `เช็กสุขภาพบัญชีใน 5 นาที (read-only)\n\nดึงข้อมูล campaign ในช่วง ${d.timeframe?.start || ''} ถึง ${d.timeframe?.end || ''}\nสรุป 3 อย่าง: 1. ทำงานดี 2. ไม่คุ้ม 3. data น้อยไป`,
    inputs: [{ type: 'daterange', id: 'timeframe', label: 'เลือกช่วงเวลา (Timeframe)' }]
  },
  '2': {
    title: '2. หาเงินรั่ว', badge: 'READ', icon: IconCoins,
    instruction: (d) => `หาเงินรั่วแบบอ่านง่าย (read-only)\n\nหา campaign ที่ใช้เงินสูงแต่ผลลัพธ์อ่อนในช่วง ${d.timeframe?.start || ''} ถึง ${d.timeframe?.end || ''}\nแสดงผลเป็นตาราง และสรุปปัญหา`,
    inputs: [{ type: 'daterange', id: 'timeframe', label: 'เลือกช่วงเวลา (Timeframe)' }]
  },
  '3': {
    title: '3. เช็ก Creative Fatigue', badge: 'READ', icon: IconImage,
    instruction: (d) => `เช็ก creative fatigue (read-only)\nช่วง ${d.timeframe?.start || ''} ถึง ${d.timeframe?.end || ''}\nflag ad ที่ frequency เพิ่ม, CTR ลด, CPA แย่ลง`,
    inputs: [{ type: 'daterange', id: 'timeframe', label: 'เลือกช่วงเวลาหลัก' }]
  },
  '4': {
    title: '4. สรุปให้เจ้าของอ่าน', badge: 'READ', icon: IconFile,
    instruction: (d) => `สรุปให้เจ้าของธุรกิจอ่าน (read-only)\n\nช่วง ${d.timeframe?.start || ''} ถึง ${d.timeframe?.end || ''}\nสรุป 4 ส่วน: อะไรเวิร์ก อะไรไม่คุ้ม อะไรยังพิจารณาไม่ได้ อะไรห้ามแตะ`,
    inputs: [{ type: 'daterange', id: 'timeframe', label: 'เลือกช่วงเวลาที่ต้องการสรุป' }]
  },
  '5': {
    title: '5. สร้าง Draft Campaign', badge: 'DRAFT', icon: IconPen,
    instruction: (d) => `สร้าง campaign draft แบบ PAUSED\nสินค้า: ${d.product_name}\nLanding: ${d.landing_page}\nงบ: ${d.daily_budget}\nพื้นที่: ${d.location}\nอายุ: ${d.age}\nข้อความ: ${d.primary_text}\nหัวข้อ: ${d.headline}`,
    inputs: [
      { type: 'text', id: 'product_name', label: 'สินค้า/บริการ', placeholder: 'เช่น คอร์สเรียนออนไลน์' },
      { type: 'text', id: 'landing_page', label: 'Landing Page URL', placeholder: 'https://...' },
      { type: 'number', id: 'daily_budget', label: 'งบต่อวัน (บาท)', placeholder: '500' },
      { type: 'text', id: 'location', label: 'พื้นที่ยิงโฆษณา', placeholder: 'ทั่วประเทศไทย' },
      { type: 'text', id: 'age', label: 'ช่วงอายุ', placeholder: '25-45' },
      { type: 'textarea', id: 'primary_text', label: 'ข้อความหลัก', placeholder: 'เขียนแคปชันโฆษณา...' },
      { type: 'text', id: 'headline', label: 'หัวข้อโฆษณา', placeholder: 'โปรโมชันพิเศษ...' }
    ]
  },
  '6': {
    title: '6. อนุมัติเปิดยิง', badge: 'ACTION', icon: IconRocket,
    instruction: (d) => `อนุมัติเปิดยิง (status change)\nCampaign ID = ${d.campaign_id}\nตรวจ 5 ข้อก่อนเปลี่ยน status`,
    inputs: [{ type: 'text', id: 'campaign_id', label: 'Campaign ID', placeholder: 'ระบุ ID แคมเปญ' }]
  },
  '7': {
    title: '7. ตรวจหลังยิงวันแรก', badge: 'READ', icon: IconSearch,
    instruction: (d) => `ตรวจหลังเปิดยิงวันแรก (read-only)\nCampaign ID = ${d.campaign_id}\nสรุปผลลัพธ์ว่าปกติไหม ควรหยุดหรือไปต่อ`,
    inputs: [{ type: 'text', id: 'campaign_id', label: 'Campaign ID', placeholder: 'ระบุ ID แคมเปญที่เพิ่งเปิดยิง' }]
  },
  '8': {
    title: '8. สรุปยอดขายจาก Ads', badge: 'READ', icon: IconTrend,
    instruction: (d) => `สรุปยอดขายจาก Ads ช่วง ${d.timeframe?.start || ''} ถึง ${d.timeframe?.end || ''}\nแยกตารางตามหมวดหมู่ แสดง Budget, Spend, ROAS, CPA, ยอดขาย เรียงจากตัวคุ้มสุดขึ้นก่อน`,
    inputs: [{ type: 'daterange', id: 'timeframe', label: 'ช่วงเวลาที่ต้องการดู (Date Range)' }]
  },
  'logs': {
    title: 'ประวัติการทำงาน (Logs)', badge: 'SYSTEM', icon: IconClock,
    instruction: null,
    inputs: [{ type: 'select', id: 'log_limit', label: 'จำนวนรายการ', options: ['10', '20', '50', '100'] }]
  }
};

// ═══════════════════════════════════════════════════════════════
// Smart AI Text Parser for Slides
// ═══════════════════════════════════════════════════════════════
function parseAItoSlides(raw, title, dateRange) {
  if (!raw) return [];
  let text = typeof raw !== 'string' ? JSON.stringify(raw, null, 2) : raw;

  try {
    const parsed = JSON.parse(text);
    if (typeof parsed === 'string') text = parsed;
    else if (parsed.output) text = parsed.output;
  } catch(e) {}

  // Clean code blocks
  text = text.replace(/```[a-z]*/gi, '').replace(/```/g, '');

  // Detect if text has markdown tables
  const hasTable = text.includes('|') && text.split('\n').some(l => l.trim().startsWith('|'));

  // Parse tables into structured data
  const parseTable = (lines) => {
    const rows = [];
    lines.forEach(l => {
      const trimmed = l.trim();
      if (!trimmed.startsWith('|') || trimmed.match(/^\|[-:\s|]+\|$/)) return; // skip separator
      const cells = trimmed.split('|').filter(c => c.trim()).map(c => c.trim().replace(/\*\*/g, ''));
      if (cells.length > 0) rows.push(cells);
    });
    return rows.length > 1 ? { headers: rows[0], data: rows.slice(1) } : null;
  };

  // Detect sentiment/status of a bullet
  const getStatus = (text) => {
    const lower = text.toLowerCase();
    if (lower.match(/(good|positive|increase|growth|strong|high|success|profit|improve|effective|recommend|\u0e14\u0e35|\u0e40\u0e27\u0e34\u0e23\u0e4c\u0e01|\u0e01\u0e33\u0e44\u0e23|\u0e40\u0e1e\u0e34\u0e48\u0e21|\u0e2a\u0e39\u0e07|\u0e41\u0e19\u0e30\u0e19\u0e33|\u0e04\u0e38\u0e49\u0e21)/)) return 'good';
    if (lower.match(/(bad|negative|decrease|decline|weak|low|fail|loss|poor|expensive|problem|issue|\u0e44\u0e21\u0e48\u0e04\u0e38\u0e49\u0e21|\u0e41\u0e1e\u0e07|\u0e25\u0e14|\u0e2b\u0e22\u0e38\u0e14|\u0e1b\u0e34\u0e14|\u0e2d\u0e31\u0e19\u0e15\u0e23\u0e32\u0e22|\u0e40\u0e07\u0e34\u0e19\u0e23\u0e31\u0e48\u0e27)/)) return 'bad';
    if (lower.match(/(warning|caution|monitor|watch|uncertain|risk|\u0e23\u0e30\u0e27\u0e31\u0e07|\u0e15\u0e34\u0e14\u0e15\u0e32\u0e21|\u0e2a\u0e31\u0e07\u0e40\u0e01\u0e15|\u0e1e\u0e34\u0e08\u0e32\u0e23\u0e13\u0e32)/)) return 'warn';
    return 'info';
  };

  const statusIcons = { good: '\u2705', bad: '\u274c', warn: '\u26a0\ufe0f', info: '\u2139\ufe0f' };
  const statusColors = { good: '#34d399', bad: '#f87171', warn: '#fbbf24', info: '#60a5fa' };

  // Parse into sections
  const sections = [];
  let current = { title: '', items: [], table: null };
  let tableLines = [];
  let inTable = false;

  text.split('\n').forEach(line => {
    const trimmed = line.trim();
    if (!trimmed) {
      if (inTable && tableLines.length > 0) {
        current.table = parseTable(tableLines);
        tableLines = [];
        inTable = false;
      }
      return;
    }

    // Table line
    if (trimmed.startsWith('|')) {
      inTable = true;
      tableLines.push(trimmed);
      return;
    } else if (inTable) {
      current.table = parseTable(tableLines);
      tableLines = [];
      inTable = false;
    }

    const heading = trimmed.match(/^#{1,3}\s+(.+)/);
    const numbered = trimmed.match(/^(\d+)\.\s+\*?\*?(.+?)\*?\*?\s*$/);

    if (heading || numbered) {
      if (current.title || current.items.length > 0 || current.table) sections.push({ ...current });
      current = { title: (heading ? heading[1] : numbered[2]).replace(/\*\*/g, ''), items: [], table: null };
    } else {
      let clean = trimmed.replace(/^[-\u2022*]\s*/, '');
      // Parse bold text: **text** -> keep but mark
      let label = '';
      let detail = clean;
      const boldMatch = clean.match(/^\*\*(.+?)\*\*[:\s]*(.*)$/);
      if (boldMatch) { label = boldMatch[1]; detail = boldMatch[2] || ''; }
      else { detail = clean.replace(/\*\*/g, ''); }

      // Extract numbers/currency
      const numMatch = detail.match(/([\d,]+\.?\d*)\s*(THB|USD|\u0e1a\u0e32\u0e17|%|x)?/i);

      if (clean) {
        current.items.push({
          label: label,
          detail: detail,
          status: getStatus(clean),
          metric: numMatch ? numMatch[0] : null
        });
      }
    }
  });
  if (inTable) current.table = parseTable(tableLines);
  if (current.title || current.items.length > 0 || current.table) sections.push(current);

  // Fallback
  if (sections.length === 0) {
    const lines = text.split('\n').filter(l => l.trim());
    for (let i = 0; i < lines.length; i += 3) {
      sections.push({ title: '', items: lines.slice(i, i + 3).map(l => ({ label: '', detail: l.replace(/^[-\u2022*]\s*/, '').replace(/\*\*/g, ''), status: 'info', metric: null })), table: null });
    }
  }

  const bgs = [
    'linear-gradient(135deg, #0f172a 0%, #1e3a5f 100%)',
    'linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%)',
    'linear-gradient(135deg, #0d1117 0%, #161b22 50%, #21262d 100%)',
    'linear-gradient(135deg, #1b2838 0%, #2a475e 100%)',
    'linear-gradient(135deg, #0c0e1a 0%, #1a1f3a 50%, #2d1b69 100%)',
    'linear-gradient(135deg, #0a192f 0%, #112240 100%)',
  ];

  const slides = [{ type: 'title', title, dateRange, bg: bgs[0] }];

  sections.forEach((sec, idx) => {
    // Table slide
    if (sec.table) {
      slides.push({ type: 'table', title: sec.title, table: sec.table, bg: bgs[(idx + 1) % bgs.length] });
    }
    // Content slides (max 4 per slide for readability)
    const max = 4;
    if (sec.items.length > 0) {
      if (sec.items.length <= max) {
        slides.push({ type: 'content', title: sec.title, items: sec.items, bg: bgs[(idx + 1) % bgs.length] });
      } else {
        for (let i = 0; i < sec.items.length; i += max) {
          slides.push({
            type: 'content',
            title: sec.title + (i > 0 ? ' (\u0e15\u0e48\u0e2d)' : ''),
            items: sec.items.slice(i, i + max),
            bg: bgs[(idx + 1 + i) % bgs.length]
          });
        }
      }
    }
  });

  slides.push({ type: 'end', bg: bgs[0] });
  return slides;
}

// ═══════════════════════════════════════════════════════════════
// Main Component
// ═══════════════════════════════════════════════════════════════
function PromptsView({ onNavigate }) {
  const [activeTab, setActiveTab] = useState('1');
  const [formData, setFormData] = useState({});
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState({});
  const [errorMsg, setErrorMsg] = useState('');
  const [slideMode, setSlideMode] = useState(false);
  const [currentSlide, setCurrentSlide] = useState(0);

  const config = PROMPTS_CONFIG[activeTab];
  const n8nUrl = typeof getN8nSettings === 'function' ? getN8nSettings().hookPrompts : localStorage.getItem('n8nWebhookUrl');
  const hasWebhook = Boolean(n8nUrl);

  useEffect(() => {
    const defaultData = {};
    if (config?.inputs) {
      config.inputs.forEach(inp => {
        if (inp.type === 'daterange') defaultData[inp.id] = { start:'', end:'' };
        else if (inp.type === 'select') defaultData[inp.id] = inp.options[0];
        else defaultData[inp.id] = '';
      });
    }
    setFormData(defaultData);
    setErrorMsg('');
  }, [activeTab]);

  const handleInputChange = (id, value, isStart) => {
    setFormData(prev => {
      const updated = { ...prev };
      if (isStart !== undefined) {
        updated[id] = { ...updated[id], [isStart ? 'start' : 'end']: value };
      } else {
        updated[id] = value;
      }
      return updated;
    });
  };

  const handleExportPdf = () => window.print();
  const presRef = useRef(null);
  const handleViewSlides = () => {
    setCurrentSlide(0);
    setSlideMode(true);
    // Request real browser fullscreen after a tick (element needs to mount first)
    setTimeout(() => {
      const el = presRef.current || document.documentElement;
      if (el.requestFullscreen) el.requestFullscreen().catch(() => {});
      else if (el.webkitRequestFullscreen) el.webkitRequestFullscreen();
    }, 50);
  };
  const closeSlides = () => {
    setSlideMode(false);
    if (document.fullscreenElement || document.webkitFullscreenElement) {
      if (document.exitFullscreen) document.exitFullscreen().catch(() => {});
      else if (document.webkitExitFullscreen) document.webkitExitFullscreen();
    }
  };
  // Sync state when user exits fullscreen via browser ESC
  useEffect(() => {
    const onFsChange = () => {
      if (!document.fullscreenElement && !document.webkitFullscreenElement) {
        setSlideMode(false);
      }
    };
    document.addEventListener('fullscreenchange', onFsChange);
    document.addEventListener('webkitfullscreenchange', onFsChange);
    return () => {
      document.removeEventListener('fullscreenchange', onFsChange);
      document.removeEventListener('webkitfullscreenchange', onFsChange);
    };
  }, []);
  const handleClear = () => setResults(prev => ({...prev, [activeTab]: null}));

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!hasWebhook) { setErrorMsg('ยังไม่ได้ตั้งค่า Webhook (ไปที่หน้า Settings)'); return; }
    setLoading(true);
    setErrorMsg('');
    try {
      if (activeTab === 'logs') {
        const limit = formData.log_limit || 50;
        const res = await fetch(`api.php?limit=${limit}`);
        const data = await res.json();
        setResults(prev => ({...prev, [activeTab]: (data.status === 'success' && data.data) ? data.data : []}));
      } else {
        const payload = {
          promptId: activeTab,
          instruction: typeof config.instruction === 'function' ? config.instruction(formData) : config.instruction,
          formData,
          timestamp: new Date().toISOString()
        };
        const response = await fetch('api.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ action: 'proxy', webhookUrl: n8nUrl, payload })
        });
        const data = await response.json();
        let output = data;
        if (Array.isArray(data) && data.length > 0 && data[0].output) output = data[0].output;
        else if (data.output) output = data.output;
        setResults(prev => ({...prev, [activeTab]: output}));
      }
    } catch (err) { setErrorMsg(err.message); }
    setLoading(false);
  };

  // Slides data
  const slides = slideMode ? parseAItoSlides(results[activeTab], config.title, formData.timeframe ? formData.timeframe.start + ' \u2014 ' + formData.timeframe.end : null) : [];
  const accentColors = ['#60a5fa', '#34d399', '#f472b6', '#a78bfa', '#fbbf24', '#fb923c'];

  // Keyboard nav for slides
  useEffect(() => {
    if (!slideMode) return;
    const handleKey = (e) => {
      if (e.key === 'ArrowRight' || e.key === ' ') { e.preventDefault(); setCurrentSlide(s => Math.min(s + 1, slides.length - 1)); }
      if (e.key === 'ArrowLeft') { e.preventDefault(); setCurrentSlide(s => Math.max(s - 1, 0)); }
      if (e.key === 'Escape') closeSlides();
    };
    window.addEventListener('keydown', handleKey);
    return () => window.removeEventListener('keydown', handleKey);
  }, [slideMode, slides.length]);

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:'var(--section-gap)' }} className="fade-up">
      {/* Header */}
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-end', gap:16, flexWrap:'wrap' }}>
        <ViewHeader title={"\u0e04\u0e33\u0e2a\u0e31\u0e48\u0e07 AI (Prompts)"} en="AI Prompts Engine"
          sub={"\u0e40\u0e0a\u0e37\u0e48\u0e2d\u0e21\u0e15\u0e48\u0e2d\u0e01\u0e31\u0e1a n8n \u0e40\u0e1e\u0e37\u0e48\u0e2d\u0e2a\u0e31\u0e48\u0e07\u0e01\u0e32\u0e23 Meta Ads \u0e2d\u0e31\u0e15\u0e42\u0e19\u0e21\u0e31\u0e15\u0e34"} />
        <button className="btn btn-ghost" onClick={() => onNavigate('settings')}>
          <IconSettings size={16} style={{ color:'var(--ink-3)' }} /> {"\u0e15\u0e31\u0e49\u0e07\u0e04\u0e48\u0e32 Webhook"}
        </button>
      </div>

      <div style={{ display:'flex', gap:20, alignItems:'flex-start', flexWrap:'wrap' }}>
        {/* Navigation Sidebar */}
        <div className="card" style={{ padding: '16px 12px', minWidth: 260, flexShrink: 0 }}>
          <div className="eyebrow" style={{ padding: '0 12px 10px' }}>PROMPT COMMANDS</div>
          <div style={{ display:'flex', flexDirection:'column', gap:4 }}>
            {Object.keys(PROMPTS_CONFIG).map(key => {
              const p = PROMPTS_CONFIG[key];
              const active = activeTab === key;
              const badgeColors = { 'READ': 'var(--info)', 'DRAFT': 'var(--accent-strong)', 'ACTION': 'var(--neg)', 'SYSTEM': 'var(--ink-2)' };
              return (
                <button key={key} onClick={() => setActiveTab(key)} style={{
                  display:'flex', alignItems:'center', justifyContent:'space-between', padding:'10px 12px', borderRadius:'var(--radius-sm)',
                  border:'none', background: active ? 'var(--surface-2)' : 'transparent', color: active ? 'var(--ink)' : 'var(--ink-2)',
                  cursor:'pointer', textAlign:'left', fontWeight: active ? 600 : 500, transition:'all 0.15s'
                }}>
                  <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                    <p.icon size={16} style={{ color: active ? 'var(--accent)' : 'var(--ink-3)' }} />
                    <span style={{ fontSize: 13.5 }}>{p.title}</span>
                  </div>
                  {p.badge && (
                    <span style={{ fontSize:10, fontWeight:700, background: active ? badgeColors[p.badge]+'1A' : 'var(--surface-3)', color: active ? badgeColors[p.badge] : 'var(--ink-3)', padding:'2px 6px', borderRadius:4 }}>
                      {p.badge}
                    </span>
                  )}
                </button>
              );
            })}
          </div>
        </div>

        {/* Main Panel */}
        <div style={{ flex: 1, minWidth: 0, display:'flex', flexDirection:'column', gap:20 }}>
          {/* Configuration Form */}
          <div className="card">
            <div className="card-head">
              <h3 className="card-title" style={{ display:'flex', alignItems:'center', gap:8 }}>
                <IconSliders size={18} /> Configuration
              </h3>
            </div>
            <form onSubmit={handleSubmit} style={{ display:'flex', flexDirection:'column', gap:16, padding:'var(--pad-card)' }}>
              {!hasWebhook && (
                <div style={{ display:'flex', gap:12, padding:'14px 18px', borderRadius:'var(--radius-sm)', background:'var(--neg-soft)', border:'1px solid var(--neg)' }}>
                  <IconWarn size={18} style={{ color:'var(--neg)', flexShrink:0 }} />
                  <div>
                    <div style={{ fontSize:13.5, fontWeight:700, color:'var(--neg)', marginBottom:3 }}>{"\u0e22\u0e31\u0e07\u0e44\u0e21\u0e48\u0e44\u0e14\u0e49\u0e15\u0e31\u0e49\u0e07\u0e04\u0e48\u0e32 Webhook"}</div>
                    <div style={{ fontSize:12.5, color:'var(--neg)' }}>{"\u0e23\u0e30\u0e1a\u0e1a\u0e44\u0e21\u0e48\u0e2a\u0e32\u0e21\u0e32\u0e23\u0e16\u0e2a\u0e48\u0e07\u0e04\u0e33\u0e2a\u0e31\u0e48\u0e07\u0e44\u0e14\u0e49 \u0e42\u0e1b\u0e23\u0e14\u0e44\u0e1b\u0e17\u0e35\u0e48\u0e2b\u0e19\u0e49\u0e32 Settings \u0e40\u0e1e\u0e37\u0e48\u0e2d\u0e43\u0e2a\u0e48 URL"}</div>
                  </div>
                </div>
              )}
              {config.inputs?.map(inp => (
                <div key={inp.id} style={{ display:'flex', flexDirection:'column', gap:6 }}>
                  <label style={{ fontSize:13, fontWeight:600, color:'var(--ink)' }}>{inp.label}</label>
                  {inp.type === 'daterange' ? (
                    <div style={{ display:'flex', gap:10, alignItems:'center' }}>
                      <input type="date" required value={formData[inp.id]?.start || ''} onChange={e => handleInputChange(inp.id, e.target.value, true)} style={{ flex:1, padding:'10px 14px', borderRadius:8, border:'1px solid var(--border-strong)', fontSize:13, background:'var(--surface)' }} />
                      <span style={{ color:'var(--ink-3)', fontSize:13, fontWeight:600 }}>{"\u0e16\u0e36\u0e07"}</span>
                      <input type="date" required value={formData[inp.id]?.end || ''} onChange={e => handleInputChange(inp.id, e.target.value, false)} style={{ flex:1, padding:'10px 14px', borderRadius:8, border:'1px solid var(--border-strong)', fontSize:13, background:'var(--surface)' }} />
                    </div>
                  ) : inp.type === 'select' ? (
                    <select required value={formData[inp.id] || ''} onChange={e => handleInputChange(inp.id, e.target.value)} style={{ padding:'10px 14px', borderRadius:8, border:'1px solid var(--border-strong)', fontSize:13, background:'var(--surface)' }}>
                      {inp.options.map(opt => <option key={opt} value={opt}>{opt}</option>)}
                    </select>
                  ) : inp.type === 'textarea' ? (
                    <textarea required placeholder={inp.placeholder} value={formData[inp.id] || ''} onChange={e => handleInputChange(inp.id, e.target.value)} style={{ padding:'10px 14px', borderRadius:8, border:'1px solid var(--border-strong)', fontSize:13, background:'var(--surface)', minHeight:80, resize:'vertical' }} />
                  ) : (
                    <input type={inp.type} required placeholder={inp.placeholder} value={formData[inp.id] || ''} onChange={e => handleInputChange(inp.id, e.target.value)} style={{ padding:'10px 14px', borderRadius:8, border:'1px solid var(--border-strong)', fontSize:13, background:'var(--surface)' }} />
                  )}
                </div>
              ))}
              <div style={{ marginTop: 8 }}>
                <button type="submit" disabled={loading || !hasWebhook} className="btn btn-primary" style={{ width: 160, display:'flex', justifyContent:'center' }}>
                  {loading ? <IconRefresh size={16} className="spin" /> : <><IconPlay size={15} /> {"\u0e23\u0e31\u0e19\u0e04\u0e33\u0e2a\u0e31\u0e48\u0e07\u0e19\u0e35\u0e49"}</>}
                </button>
              </div>
              {errorMsg && <div style={{ marginTop:10, fontSize:13, color:'var(--neg)', fontWeight:600 }}>Error: {errorMsg}</div>}
            </form>
          </div>

          {/* AI Analysis Result */}
          <div className="card" style={{ flex: 1 }}>
            <div className="card-head">
              <h3 className="card-title" style={{ display:'flex', alignItems:'center', gap:8 }}>
                <IconSpark size={18} style={{ color:'var(--accent)' }} /> AI Analysis Result
              </h3>
              <div style={{ display:'flex', gap:8 }}>
                {results[activeTab] && activeTab !== 'logs' && (
                  <button className="btn btn-primary" onClick={handleViewSlides} style={{ fontSize:12, padding:'4px 12px' }}><IconMonitorPlay size={13} style={{marginRight:4}} /> Presentation Mode</button>
                )}
                <button className="btn btn-ghost" onClick={handleExportPdf} style={{ fontSize:12, padding:'4px 10px' }}><IconFile size={13} /> Export PDF</button>
                <button className="btn btn-ghost" onClick={handleClear} style={{ fontSize:12, padding:'4px 10px' }}>Clear</button>
              </div>
            </div>
            <div style={{ padding:'var(--pad-card)' }}>
              {!results[activeTab] && !loading && (
                <div style={{ padding:'40px 0', textAlign:'center', color:'var(--ink-3)' }}>
                  <IconBot size={40} style={{ opacity:0.3, marginBottom:16 }} />
                  <p style={{ fontSize:14, margin:0 }}>{"\u0e40\u0e25\u0e37\u0e2d\u0e01\u0e04\u0e33\u0e2a\u0e31\u0e48\u0e07 \u0e01\u0e23\u0e2d\u0e01\u0e02\u0e49\u0e2d\u0e21\u0e39\u0e25 \u0e41\u0e25\u0e49\u0e27\u0e01\u0e14 \"\u0e23\u0e31\u0e19\u0e04\u0e33\u0e2a\u0e31\u0e48\u0e07\" \u0e40\u0e1e\u0e37\u0e48\u0e2d\u0e14\u0e39\u0e1c\u0e25\u0e27\u0e34\u0e40\u0e04\u0e23\u0e32\u0e30\u0e2b\u0e4c"}</p>
                </div>
              )}
              {loading && (
                <div style={{ padding:'40px 0', textAlign:'center', color:'var(--ink-2)', display:'flex', flexDirection:'column', alignItems:'center', gap:16 }}>
                  <IconRefresh size={32} className="spin" style={{ color:'var(--accent)' }} />
                  <p style={{ fontSize:14, margin:0 }}>{"\u0e01\u0e33\u0e25\u0e31\u0e07\u0e1b\u0e23\u0e30\u0e21\u0e27\u0e25\u0e1c\u0e25\u0e02\u0e49\u0e2d\u0e21\u0e39\u0e25\u0e1c\u0e48\u0e32\u0e19 n8n..."}</p>
                </div>
              )}
              {results[activeTab] && !loading && activeTab !== 'logs' && (
                <div style={{ background:'var(--surface-2)', padding:20, borderRadius:8, border:'1px solid var(--border)', fontSize:13.5, lineHeight:1.6, overflowX:'auto', whiteSpace:'pre-wrap' }} dangerouslySetInnerHTML={{ __html: syntaxHighlight(results[activeTab]) }} />
              )}
              {results[activeTab] && !loading && activeTab === 'logs' && (
                <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
                  {results['logs'].length === 0 && <p style={{ fontSize:13, color:'var(--ink-2)' }}>{"\u0e44\u0e21\u0e48\u0e1e\u0e1a\u0e1b\u0e23\u0e30\u0e27\u0e31\u0e15\u0e34\u0e01\u0e32\u0e23\u0e23\u0e31\u0e19"}</p>}
                  {results['logs'].map((log, idx) => (
                    <div key={idx} style={{ background:'var(--surface-2)', padding:16, borderRadius:8, border:'1px solid var(--border)' }}>
                      <div style={{ display:'flex', justifyContent:'space-between', marginBottom:10, alignItems:'center' }}>
                        <div style={{ fontWeight:600, fontSize:13.5, color:'var(--ink)' }}>Prompt {log.prompt_type}</div>
                        <div style={{ fontSize:12, color:'var(--ink-3)' }}>{new Date(log.created_at).toLocaleString()}</div>
                      </div>
                      <div style={{ fontSize:12.5, whiteSpace:'pre-wrap', maxHeight:200, overflowY:'auto' }} dangerouslySetInnerHTML={{ __html: syntaxHighlight(log.ai_response) }} />
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* ═══════ PREMIUM PRESENTATION MODE (LANDSCAPE) ═══════ */}
      {slideMode && slides.length > 0 && (
        <div ref={presRef} style={{
          position: 'fixed', top: 0, left: 0, width: '100vw', height: '100vh', zIndex: 99999,
          background: slides[currentSlide]?.bg || 'linear-gradient(135deg, #0f172a, #1e3a5f)',
          color: '#fff', display: 'flex', flexDirection: 'column',
          fontFamily: "'Inter', 'Sarabun', system-ui, sans-serif", overflow: 'hidden',
          transition: 'background 0.6s ease'
        }}>
          <style>{`
            @media screen and (orientation: portrait) { .pres-rotate-hint { display: flex !important; } }
            @media screen and (orientation: landscape) { .pres-rotate-hint { display: none !important; } }
            .slide-enter { animation: slideEnter 0.45s cubic-bezier(0.16, 1, 0.3, 1) forwards; }
            @keyframes slideEnter { from { opacity: 0; transform: translateX(40px); } to { opacity: 1; transform: translateX(0); } }
            .bullet-card { animation: bulletFade 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards; opacity: 0; transform: translateY(12px); }
            @keyframes bulletFade { to { opacity: 1; transform: translateY(0); } }
          `}</style>

          {/* Landscape rotation hint (mobile portrait) */}
          <div className="pres-rotate-hint" style={{ display:'none', position:'absolute', inset:0, background:'rgba(0,0,0,0.88)', zIndex:10, alignItems:'center', justifyContent:'center', flexDirection:'column', gap:16 }}>
            <div style={{ fontSize:56 }}>{"\ud83d\udcf1\u21d4"}</div>
            <p style={{ fontSize:18, opacity:0.8 }}>{"\u0e01\u0e23\u0e38\u0e13\u0e32\u0e2b\u0e21\u0e38\u0e19\u0e08\u0e2d\u0e40\u0e1b\u0e47\u0e19\u0e41\u0e19\u0e27\u0e19\u0e2d\u0e19\u0e40\u0e1e\u0e37\u0e48\u0e2d\u0e14\u0e39 Presentation"}</p>
          </div>

          {/* Progress bar */}
          <div style={{ height: 3, background: 'rgba(255,255,255,0.06)', flexShrink: 0 }}>
            <div style={{ height:'100%', width: ((currentSlide + 1) / slides.length * 100) + '%', background: 'linear-gradient(90deg, #60a5fa, #a78bfa)', transition: 'width 0.4s ease', borderRadius: '0 2px 2px 0' }} />
          </div>

          {/* Close button — fixed top-right corner */}
          <button onClick={closeSlides} style={{
            position:'absolute', top:20, right:20, zIndex:10,
            width:48, height:48, borderRadius:'50%',
            background:'rgba(255,255,255,0.1)', backdropFilter:'blur(8px)',
            border:'1px solid rgba(255,255,255,0.15)',
            color:'#fff', cursor:'pointer',
            display:'flex', alignItems:'center', justifyContent:'center',
            transition:'all 0.2s ease', boxShadow:'0 4px 20px rgba(0,0,0,0.3)'
          }}
            onMouseEnter={e => { e.currentTarget.style.background = 'rgba(255,80,80,0.7)'; e.currentTarget.style.transform = 'scale(1.1)'; }}
            onMouseLeave={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.1)'; e.currentTarget.style.transform = 'scale(1)'; }}
          >
            <IconX size={22} />
          </button>

          {/* Top info bar */}
          <div style={{ display:'flex', justifyContent:'center', alignItems:'center', padding:'14px 32px', flexShrink:0 }}>
            <div style={{ display:'flex', alignItems:'center', gap:10, opacity:0.4, fontSize:13 }}>
              <IconSpark size={14} />
              <span>AI Report</span>
              <span>{"\u2022"}</span>
              <span>{currentSlide + 1} / {slides.length}</span>
            </div>
          </div>

          {/* Slide content area */}
          <div style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center', padding:'0 8%', minHeight:0 }}>
            <div key={currentSlide} className="slide-enter" style={{ width:'100%', maxWidth:1100 }}>

              {/* TITLE SLIDE */}
              {slides[currentSlide]?.type === 'title' && (
                <div style={{ textAlign:'center' }}>
                  <div style={{ width:64, height:64, borderRadius:16, background:'linear-gradient(135deg, #60a5fa, #a78bfa)', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 28px', boxShadow:'0 8px 32px rgba(96,165,250,0.3)' }}>
                    <IconSpark size={28} />
                  </div>
                  <h1 style={{ fontSize:'clamp(28px, 4vw, 52px)', fontWeight:800, letterSpacing:'-0.02em', lineHeight:1.2, margin:'0 0 16px' }}>
                    {slides[currentSlide].title}
                  </h1>
                  {slides[currentSlide].dateRange && (
                    <div style={{ display:'inline-flex', alignItems:'center', gap:8, background:'rgba(255,255,255,0.08)', padding:'8px 20px', borderRadius:24, fontSize:16, opacity:0.7 }}>
                      <IconClock size={16} /> {slides[currentSlide].dateRange}
                    </div>
                  )}
                  <p style={{ marginTop:28, fontSize:16, opacity:0.35 }}>{"\u0e43\u0e0a\u0e49 \u2190 \u2192 \u0e2b\u0e23\u0e37\u0e2d\u0e04\u0e25\u0e34\u0e01\u0e1b\u0e38\u0e48\u0e21\u0e40\u0e1e\u0e37\u0e48\u0e2d\u0e40\u0e25\u0e37\u0e48\u0e2d\u0e19\u0e2a\u0e44\u0e25\u0e14\u0e4c"}</p>
                </div>
              )}

              {/* CONTENT SLIDE */}
              {slides[currentSlide]?.type === 'content' && (() => {
                const sColors = { good: '#34d399', bad: '#f87171', warn: '#fbbf24', info: '#60a5fa' };
                const sIcons = { good: '✅', bad: '❌', warn: '⚠️', info: 'ℹ️' };
                return (
                <div style={{ display:'flex', gap:48, alignItems:'flex-start' }}>
                  <div style={{ flex:'0 0 auto', maxWidth:320, minWidth:180 }}>
                    {slides[currentSlide].title && (
                      <h2 style={{ fontSize:'clamp(20px, 2.5vw, 36px)', fontWeight:700, lineHeight:1.3, borderLeft:'4px solid ' + accentColors[currentSlide % accentColors.length], paddingLeft:20 }}>
                        {slides[currentSlide].title}
                      </h2>
                    )}
                  </div>
                  <div style={{ flex:1, display:'flex', flexDirection:'column', gap:12 }}>
                    {(slides[currentSlide].items || []).map((item, i) => {
                      const sc = sColors[item.status] || sColors.info;
                      return (
                        <div key={i} className="bullet-card" style={{
                          display:'flex', alignItems:'flex-start', gap:16,
                          background:'rgba(255,255,255,0.05)', backdropFilter:'blur(8px)',
                          borderRadius:14, padding:'16px 22px',
                          borderLeft: '3px solid ' + sc,
                          animationDelay: (i * 0.1) + 's',
                          transition:'background 0.2s'
                        }}
                          onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.09)'}
                          onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.05)'}
                        >
                          <div style={{ fontSize:22, flexShrink:0, marginTop:2 }}>{sIcons[item.status]}</div>
                          <div style={{ flex:1 }}>
                            {item.label && <div style={{ fontWeight:700, fontSize:'clamp(15px, 1.4vw, 20px)', marginBottom:4, color: sc }}>{item.label}</div>}
                            <div style={{ fontSize:'clamp(13px, 1.2vw, 17px)', lineHeight:1.7, opacity:0.85 }}>{item.detail}</div>
                          </div>
                          {item.metric && (
                            <div style={{ flexShrink:0, textAlign:'right', background:'rgba(255,255,255,0.08)', padding:'6px 14px', borderRadius:10, fontWeight:700, fontSize:'clamp(14px, 1.3vw, 18px)', color: sc, whiteSpace:'nowrap' }}>{item.metric}</div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>
                );
              })()}

              {/* TABLE SLIDE */}
              {slides[currentSlide]?.type === 'table' && (
                <div>
                  {slides[currentSlide].title && (
                    <h2 style={{ fontSize:'clamp(20px, 2.5vw, 32px)', fontWeight:700, marginBottom:24, borderLeft:'4px solid #60a5fa', paddingLeft:20 }}>{slides[currentSlide].title}</h2>
                  )}
                  <div style={{ overflowX:'auto', borderRadius:12, border:'1px solid rgba(255,255,255,0.1)' }}>
                    <table style={{ width:'100%', borderCollapse:'collapse', fontSize:'clamp(13px, 1.1vw, 16px)' }}>
                      <thead>
                        <tr>
                          {slides[currentSlide].table.headers.map((h, i) => (
                            <th key={i} style={{ padding:'12px 16px', textAlign:'left', background:'rgba(96,165,250,0.15)', color:'#60a5fa', fontWeight:700, borderBottom:'2px solid rgba(96,165,250,0.3)', whiteSpace:'nowrap' }}>{h}</th>
                          ))}
                        </tr>
                      </thead>
                      <tbody>
                        {slides[currentSlide].table.data.map((row, ri) => (
                          <tr key={ri} style={{ background: ri % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent' }}>
                            {row.map((cell, ci) => (
                              <td key={ci} style={{ padding:'10px 16px', borderBottom:'1px solid rgba(255,255,255,0.06)', opacity:0.9 }}>{cell}</td>
                            ))}
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              )}

              {/* END SLIDE */}
              {slides[currentSlide]?.type === 'end' && (
                <div style={{ textAlign:'center' }}>
                  <div style={{ fontSize:56, marginBottom:20 }}>{"\u2705"}</div>
                  <h2 style={{ fontSize:'clamp(28px, 3.5vw, 44px)', fontWeight:800, marginBottom:12 }}>{"\u0e08\u0e1a\u0e01\u0e32\u0e23\u0e19\u0e33\u0e40\u0e2a\u0e19\u0e2d"}</h2>
                  <p style={{ fontSize:18, opacity:0.5, marginBottom:32 }}>Powered by AI {"\u00d7"} Meta Ads Dashboard</p>
                  <button onClick={closeSlides} style={{ background:'rgba(255,255,255,0.1)', border:'1px solid rgba(255,255,255,0.15)', color:'#fff', padding:'12px 32px', borderRadius:28, fontSize:16, cursor:'pointer', transition:'0.2s' }}
                    onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.18)'}
                    onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.1)'}
                  >
                    {"\u0e1b\u0e34\u0e14 Presentation"}
                  </button>
                </div>
              )}
            </div>
          </div>

          {/* Bottom controls */}
          <div style={{ display:'flex', justifyContent:'center', alignItems:'center', gap:12, padding:'16px 32px', flexShrink:0 }}>
            <div style={{ display:'flex', gap:6, marginRight:16 }}>
              {slides.map((_, i) => (
                <button key={i} onClick={() => setCurrentSlide(i)} style={{
                  width: i === currentSlide ? 24 : 8, height:8, borderRadius:4,
                  background: i === currentSlide ? '#60a5fa' : 'rgba(255,255,255,0.15)',
                  border:'none', cursor:'pointer', transition:'all 0.3s ease', padding:0
                }} />
              ))}
            </div>
            <button disabled={currentSlide === 0} onClick={() => setCurrentSlide(s => s - 1)}
              style={{ background: currentSlide === 0 ? 'rgba(255,255,255,0.04)' : 'rgba(255,255,255,0.1)', color: currentSlide === 0 ? 'rgba(255,255,255,0.2)' : '#fff', border:'none', padding:'10px 20px', borderRadius:24, cursor: currentSlide === 0 ? 'not-allowed' : 'pointer', display:'flex', alignItems:'center', gap:6, fontSize:14, fontWeight:600, transition:'0.2s' }}
            >
              <IconChevronLeft size={16} /> {"\u0e01\u0e48\u0e2d\u0e19\u0e2b\u0e19\u0e49\u0e32"}
            </button>
            <button disabled={currentSlide === slides.length - 1} onClick={() => setCurrentSlide(s => s + 1)}
              style={{ background: currentSlide === slides.length - 1 ? 'rgba(255,255,255,0.04)' : 'linear-gradient(135deg, #60a5fa, #a78bfa)', color: currentSlide === slides.length - 1 ? 'rgba(255,255,255,0.2)' : '#fff', border:'none', padding:'10px 20px', borderRadius:24, cursor: currentSlide === slides.length - 1 ? 'not-allowed' : 'pointer', display:'flex', alignItems:'center', gap:6, fontSize:14, fontWeight:600, transition:'0.2s', boxShadow: currentSlide === slides.length - 1 ? 'none' : '0 4px 16px rgba(96,165,250,0.3)' }}
            >
              {"\u0e16\u0e31\u0e14\u0e44\u0e1b"} <IconChevronRight size={16} />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// Ensure IconBot exists
const IconBot = (p) => <Ico {...p}><rect x="3" y="11" width="18" height="10" rx="2"/><circle cx="12" cy="5" r="2"/><path d="M12 7v4"/><line x1="8" y1="16" x2="8" y2="16"/><line x1="16" y1="16" x2="16" y2="16"/></Ico>;

Object.assign(window, { PromptsView });
