/* Product Roadmap page — data sourced from maiagent-builder-brain/product/roadmap */

const ROADMAP = [
  {
    quarter: 'Q2 2026',
    status: 'current',
    labelZh: '進行中',
    labelEn: 'In Progress',
    features: [
      { id: 'f01', cat: 'Enterprise', status: 'in_progress', releaseDate: '2026-06-02',
        zh: { title: 'Credit 統一計費體系', desc: '以 Credit 統一計費，附件儲存與 API 呼叫透明查閱；餘額不足自動預警，可推送至外部監控平台；免費版與付費版功能邊界明確化。' },
        en: { title: 'Unified Credit Billing', desc: 'Credit-based billing for attachments and API calls with transparent usage logs; low-balance auto-alert with external monitoring push; clear free vs. paid feature boundaries.' } },
      { id: 'f02', cat: 'Product', status: 'in_progress',
        zh: { title: 'MaiGPT 平台', desc: 'Functions、Skills、Code Interpreter 整合到同一對話介面，開箱即用；IQ-GPT SDK 支援視窗嵌入模式，可嵌入企業現有系統（白板、工作台、內部平台）。' },
        en: { title: 'MaiGPT Platform', desc: 'Functions, Skills, and Code Interpreter unified in one chat interface, ready to use; IQ-GPT SDK supports embedded window mode for integration into whiteboards, workbenches, and internal platforms.' } },
      { id: 'f03', cat: 'Product', status: 'in_progress',
        zh: { title: '語音平台升級', desc: '支援 Gemini 2.5 / GPT-realtime 最新語音模型；地端 TTS 方案，語音資料不出境；Realtime 模式下 Agent 可在說話的同時執行工具呼叫。' },
        en: { title: 'Voice Platform Upgrade', desc: 'Multi-model support for Gemini 2.5 and GPT-realtime; on-premise TTS keeps voice data local; Agent tool calling works during real-time voice conversations.' } },
      { id: 'f04', cat: 'Product', status: 'in_progress',
        zh: { title: 'Desktop App', desc: 'Mac / Windows 跨平台安裝包；自動偵測 Google Meet / Microsoft Teams 會議並提示錄音；語者辨識整合，會議結束即產出誰說了什麼。' },
        en: { title: 'Desktop App', desc: 'Mac and Windows cross-platform installers; auto-detects Google Meet / Teams meetings and prompts recording; speaker diarization generates who-said-what summaries after the meeting.' } },
      { id: 'f05', cat: 'Product', status: 'in_progress',
        zh: { title: 'AI 會議記錄', desc: 'AiLabs ASR 後端整合；Mini 錄音 widget；Google Meet 插件；國語 / 台語 / 英語三語識別；支援離線轉錄，會議內容不依賴雲端。' },
        en: { title: 'AI Meeting Notes', desc: 'AiLabs ASR backend; mini recording widget; Google Meet plugin; three-language support (Mandarin, Taiwanese, English); offline transcription option for data-sensitive meetings.' } },
      { id: 'f06', cat: 'Platform', status: 'in_progress',
        zh: { title: 'MCP 工具生態', desc: 'Agent 可呼叫任何支援 MCP 協議的外部工具；OAuth 標準授權（RFC 9728）；Draw.io、影片生成等已示範整合；HappyHorse 影片生成通路。' },
        en: { title: 'MCP Tool Ecosystem', desc: 'Agents can call any MCP-compatible external tool; OAuth standard authorization (RFC 9728); example integrations with Draw.io and video generation available.' } },
      { id: 'f07', cat: 'Platform', status: 'in_progress',
        zh: { title: 'MaiAgent Hooks 自動化', desc: '定義觸發條件讓 Agent 工作流可程式化；Hook System 啟動；整合 Anthropic Skills 格式，可共用社群工具庫。' },
        en: { title: 'MaiAgent Hooks Automation', desc: 'Define trigger conditions to make Agent workflows programmable; Hook System launch; integrates Anthropic Skills format for shared community tool libraries.' } },
      { id: 'f08', cat: 'Platform', status: 'in_progress',
        zh: { title: '多模態 RAG', desc: 'Attachment 改由 Agent 智慧判別是否需要做 RAG，避免雜訊干擾；多模態預設開啟，支援圖片與文件混合查詢；爬蟲深度爬取 + 排程 + 自動匯入知識庫。' },
        en: { title: 'Multimodal RAG', desc: 'Agent intelligently decides whether attachments need RAG to reduce noise; multimodal enabled by default for mixed image/document queries; deep crawl with scheduling and auto-import to Knowledge Base.' } },
    ],
  },
  {
    quarter: 'Q3 2026',
    status: 'upcoming',
    labelZh: '即將發布',
    labelEn: 'Coming Soon',
    features: [
      { id: 'f09', cat: 'Platform', status: 'planned',
        zh: { title: 'LLM Gateway', desc: '企業統一管理所有 AI 模型呼叫；相容 OpenAI API 格式，現有程式不用修改；集中控管 quota、cost、logging，多模型費用一目了然。' },
        en: { title: 'LLM Gateway', desc: 'Centralize all AI model calls across your organization; OpenAI-compatible API so existing code needs no changes; unified quota, cost, and logging across all models.' } },
      { id: 'f10', cat: 'Product', status: 'planned',
        zh: { title: 'AI 會議助手全平台', desc: '涵蓋 Web、Desktop、Microsoft Teams、Google Meet 全通路；國語 / 台語 / 英語三語轉錄；離線轉錄不依賴網路；會議結束自動生成摘要與行動項目。' },
        en: { title: 'AI Meeting Assistant (All Platforms)', desc: 'Full coverage across Web, Desktop, Microsoft Teams, and Google Meet; three-language transcription (Mandarin, Taiwanese, English); offline mode; auto-generates summary and action items.' } },
      { id: 'f11', cat: 'Product', status: 'planned',
        zh: { title: 'AI Customer Service Copilot', desc: '前線客服在對話視窗內即時獲得 AI 建議；AI 自動判斷何時介入或轉接人工；對話結束自動送出滿意度問卷；支援 Genesys Cloud、WABA、LINE 等主流客服通路。' },
        en: { title: 'AI Customer Service Copilot', desc: 'Front-line agents get real-time AI suggestions in-window; AI auto-detects when to intervene or escalate; satisfaction surveys sent automatically; supports Genesys Cloud, WABA, and LINE.' } },
      { id: 'f12', cat: 'Platform', status: 'planned',
        zh: { title: 'RAG 再進化', desc: '支援自訂 Metadata 硬篩選條件（如客戶、產品、時間範圍）；Metadata 標籤可視化；搜尋命中率儀表板，精準度可量化追蹤。' },
        en: { title: 'RAG Precision Upgrade', desc: 'Custom Metadata hard-filtering (by customer, product, date range); Metadata tag visualization; search hit-rate dashboard for quantifiable precision tracking.' } },
      { id: 'f13', cat: 'Enterprise', status: 'planned',
        zh: { title: 'AWS Marketplace 正式上架', desc: '在 AWS 生態直接訂閱 MaiAgent；支援 AWS 合約金額抵用，加速企業採購流程；SaaS 訂閱方案完整上架。' },
        en: { title: 'AWS Marketplace GA', desc: 'Subscribe to MaiAgent directly within the AWS ecosystem; AWS credits accepted; accelerates enterprise procurement with full SaaS subscription listing.' } },
    ],
  },
  {
    quarter: 'Q4 2026',
    status: 'upcoming',
    labelZh: '規劃確認',
    labelEn: 'Confirmed',
    features: [
      { id: 'f14', cat: 'Analytics', status: 'planned',
        zh: { title: 'Agent 可觀測性（AgentOps）', desc: 'Agent 效能監控儀表板；建立評測資料集並追蹤回答品質隨時間變化；DeepEval Dataset Builder 整合，AI 回答品質可被量化與持續優化。' },
        en: { title: 'Agent Observability (AgentOps)', desc: 'Agent performance monitoring dashboard; evaluation dataset builder to track answer quality over time; DeepEval integration for quantified and continuously improving AI quality.' } },
      { id: 'f15', cat: 'Enterprise', status: 'planned',
        zh: { title: '地端部署全面升級', desc: 'Ask AI 功能納入地端標配；Site-to-Site VPN 企業安全強化；資料主權完整支援，滿足金融業、醫療業合規要求。' },
        en: { title: 'On-Premise Deployment Upgrade', desc: 'Ask AI included in on-premise default package; Site-to-Site VPN enterprise security hardening; full data sovereignty to meet financial and healthcare compliance requirements.' } },
      { id: 'f16', cat: 'Platform', status: 'planned',
        zh: { title: 'Agent UI / Flex Message', desc: 'Quick Reply 等互動元件支援；Agent 對話中可呈現結構化卡片、按鈕、表單等 Flex Message 元件，提升對話互動體驗。' },
        en: { title: 'Agent UI / Flex Message', desc: 'Interactive component support including Quick Reply; structured cards, buttons, and forms rendered in Agent conversations via Flex Message for richer interaction.' } },
    ],
  },
  {
    quarter: 'Q1 2027',
    status: 'future',
    labelZh: '中期規劃',
    labelEn: 'Roadmap',
    features: [
      { id: 'f17', cat: 'Product', status: 'exploring',
        zh: { title: 'Generative UI', desc: 'Agent 根據任務情境動態生成互動元件（表單、資料卡、操作選單）；用戶直接在對話中完成操作（填單、確認、選擇），不再只收到文字。適用場景：報價審核、訂單確認、多步驟流程引導。' },
        en: { title: 'Generative UI', desc: 'Agents dynamically generate interactive components (forms, data cards, action menus) based on context; users complete actions — fill, confirm, select — directly in the chat. Use cases: quote approval, order confirmation, guided multi-step flows.' } },
      { id: 'f18', cat: 'Product', status: 'exploring',
        zh: { title: 'Agent Teams 正式版', desc: '多個 AI Agent 分工協作，各自持有專屬工具與知識；PM Agent、執行 Agent、審核 Agent 各司其職。適用場景：複雜研究任務、多步驟業務流程自動化。' },
        en: { title: 'Agent Teams GA', desc: 'Multiple AI agents working in concert, each with specialized tools and knowledge — PM, execution, and review agents each playing their role. Use cases: complex research tasks, multi-step business workflow automation.' } },
      { id: 'f19', cat: 'Product', status: 'exploring',
        zh: { title: 'AI 簡報生成', desc: '對話直接輸出可編輯簡報；支援品牌模板套用；適用於產品提案、客戶報告、季度回顧。' },
        en: { title: 'AI Presentation Generator', desc: 'Generate editable presentations directly from a conversation; supports brand template application; ideal for product pitches, customer reports, and quarterly reviews.' } },
    ],
  },
];

const CAT_COLOR = {
  'Product':      { bg: '#eff6ff', text: '#1d4ed8', dot: '#3b82f6' },
  'Platform':     { bg: '#f0fdf4', text: '#15803d', dot: '#22c55e' },
  'Enterprise':   { bg: '#fff7ed', text: '#c2410c', dot: '#f97316' },
  'Analytics':    { bg: '#faf5ff', text: '#7e22ce', dot: '#a855f7' },
};

const STATUS_META = {
  shipped:     { zh: '已發布', en: 'Shipped',     color: '#059669', bg: '#ecfdf5' },
  in_progress: { zh: '開發中', en: 'In Progress', color: '#d97706', bg: '#fffbeb' },
  planned:     { zh: '規劃中', en: 'Planned',     color: '#2563eb', bg: '#eff6ff' },
  exploring:   { zh: '探索中', en: 'Exploring',   color: '#7c3aed', bg: '#f5f3ff' },
};

const FEEDBACK_CATS = {
  zh: ['功能建議', '整合需求', '效能改善', '使用介面', '其他'],
  en: ['Feature Request', 'Integration Need', 'Performance', 'UI/UX', 'Other'],
};

const RoadmapPage = ({ t, lang }) => {
  const isZh = lang === 'zh';
  const [activeQ, setActiveQ] = React.useState(0);
  const [fbCat, setFbCat] = React.useState('');
  const [fbText, setFbText] = React.useState('');
  const [fbSubmitted, setFbSubmitted] = React.useState(false);

  const qData = ROADMAP[activeQ];
  const inProgressCount = qData.features.filter(f => f.status === 'in_progress').length;
  const shippedCount = qData.features.filter(f => f.status === 'shipped').length;
  const plannedCount = qData.features.filter(f => f.status === 'planned').length;
  const exploringCount = qData.features.filter(f => f.status === 'exploring').length;
  const cats = FEEDBACK_CATS[isZh ? 'zh' : 'en'];

  function handleFbSubmit(e) {
    e.preventDefault();
    if (!fbText.trim()) return;
    setFbSubmitted(true);
  }

  function handleFbReset() {
    setFbText('');
    setFbCat('');
    setFbSubmitted(false);
  }

  return (
    <div style={{ padding: '24px', maxWidth: 1000, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ marginBottom: 22 }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, color: 'var(--mai-fg)', margin: '0 0 4px' }}>{t('rm.title')}</h1>
        <p style={{ margin: 0, color: 'var(--mai-fg-2)', fontSize: 14 }}>{t('rm.sub')}</p>
      </div>

      {/* Quarter tabs */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 20, flexWrap: 'wrap' }}>
        {ROADMAP.map((q, i) => {
          const active = activeQ === i;
          return (
            <button
              key={q.quarter}
              onClick={() => setActiveQ(i)}
              style={{
                padding: '7px 18px', borderRadius: 20,
                border: active ? 'none' : '1px solid var(--mai-border)',
                background: active ? 'var(--mai-blue)' : 'white',
                color: active ? 'white' : 'var(--mai-fg-2)',
                fontSize: 13, fontWeight: active ? 600 : 400, cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 6,
              }}
            >
              {q.quarter}
              <span style={{
                fontSize: 11, fontWeight: 500,
                color: active ? 'rgba(255,255,255,0.8)' : 'var(--mai-fg-3)',
                background: active ? 'rgba(255,255,255,0.15)' : '#f3f4f6',
                padding: '1px 7px', borderRadius: 10,
              }}>
                {isZh ? q.labelZh : q.labelEn}
              </span>
              {q.status === 'current' && (
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: active ? 'rgba(255,255,255,.75)' : '#10b981', display: 'inline-block', flexShrink: 0 }} />
              )}
            </button>
          );
        })}
      </div>

      {/* Stats bar */}
      {(shippedCount + inProgressCount + plannedCount + exploringCount > 0) && (
        <div style={{ display: 'flex', gap: 10, marginBottom: 18 }}>
          {shippedCount > 0 && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 13, color: '#059669', background: '#ecfdf5', padding: '4px 12px', borderRadius: 20 }}>
              <Icon name="check-circle" size={13} />
              {shippedCount} {isZh ? '已發布' : 'shipped'}
            </div>
          )}
          {inProgressCount > 0 && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 13, color: '#d97706', background: '#fffbeb', padding: '4px 12px', borderRadius: 20 }}>
              <Icon name="loader" size={13} />
              {inProgressCount} {isZh ? '開發中' : 'in progress'}
            </div>
          )}
          {plannedCount > 0 && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 13, color: '#2563eb', background: '#eff6ff', padding: '4px 12px', borderRadius: 20 }}>
              <Icon name="clock" size={13} />
              {plannedCount} {isZh ? '規劃中' : 'planned'}
            </div>
          )}
          {exploringCount > 0 && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 13, color: '#7c3aed', background: '#f5f3ff', padding: '4px 12px', borderRadius: 20 }}>
              <Icon name="star" size={13} />
              {exploringCount} {isZh ? '探索中' : 'exploring'}
            </div>
          )}
        </div>
      )}

      {/* Feature cards */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {qData.features.map(f => {
          const info = isZh ? f.zh : f.en;
          const catStyle = CAT_COLOR[f.cat] || CAT_COLOR['Product'];
          const sm = STATUS_META[f.status] || STATUS_META.planned;

          return (
            <div key={f.id} style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 12, padding: '14px 18px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 6, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 14.5, fontWeight: 700, color: '#1f2937' }}>{info.title}</span>
                <span style={{ fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 10, background: sm.bg, color: sm.color }}>
                  {sm[isZh ? 'zh' : 'en']}
                </span>
                <span style={{ fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 10, background: catStyle.bg, color: catStyle.text, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                  <span style={{ width: 5, height: 5, borderRadius: '50%', background: catStyle.dot, display: 'inline-block' }} />
                  {f.cat}
                </span>
                {f.releaseDate && (
                  <span style={{ fontSize: 11, fontWeight: 500, color: '#6b7280', display: 'flex', alignItems: 'center', gap: 3 }}>
                    <Icon name="calendar" size={11} />
                    {isZh ? '預計' : 'ETA'} {f.releaseDate}
                  </span>
                )}
              </div>
              <p style={{ margin: 0, fontSize: 13, color: 'var(--mai-fg-2)', lineHeight: 1.65 }}>{info.desc}</p>
            </div>
          );
        })}
      </div>

      {/* ── Product Feedback ── */}
      <div style={{ marginTop: 28, background: 'white', border: '1px solid var(--mai-border)', borderRadius: 12, overflow: 'hidden' }}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--mai-border)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <Icon name="message-circle" size={16} style={{ color: 'var(--mai-blue)' }} />
          <div>
            <div style={{ fontSize: 15, fontWeight: 700, color: '#1f2937' }}>
              {isZh ? '產品回饋' : 'Product Feedback'}
            </div>
            <div style={{ fontSize: 12.5, color: 'var(--mai-fg-2)', marginTop: 1 }}>
              {isZh
                ? '有功能需求或改進建議？告訴我們，產品團隊每月檢閱夥伴回饋。'
                : 'Have a feature request or improvement idea? Share it — our product team reviews partner feedback monthly.'}
            </div>
          </div>
        </div>

        <div style={{ padding: '20px' }}>
          {fbSubmitted ? (
            <div style={{ textAlign: 'center', padding: '28px 0' }}>
              <div style={{ fontSize: 36, marginBottom: 12 }}>🙌</div>
              <div style={{ fontSize: 15, fontWeight: 600, color: '#1f2937', marginBottom: 6 }}>
                {isZh ? '感謝你的回饋！' : 'Thanks for your feedback!'}
              </div>
              <p style={{ fontSize: 13, color: 'var(--mai-fg-2)', margin: '0 0 16px' }}>
                {isZh
                  ? '我們的產品團隊將於下次月會檢閱所有夥伴回饋，並在路線圖更新時通知你。'
                  : "Our product team will review all partner feedback at the next monthly review and notify you on roadmap updates."}
              </p>
              <button
                onClick={handleFbReset}
                style={{ padding: '6px 16px', border: '1px solid var(--mai-border)', borderRadius: 8, background: 'white', fontSize: 13, cursor: 'pointer', color: 'var(--mai-fg-2)' }}
              >
                {isZh ? '再送一則' : 'Submit another'}
              </button>
            </div>
          ) : (
            <form onSubmit={handleFbSubmit}>
              <div style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: '#374151', marginBottom: 8 }}>
                  {isZh ? '回饋類型（選填）' : 'Feedback type (optional)'}
                </div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {cats.map(c => (
                    <button
                      key={c}
                      type="button"
                      onClick={() => setFbCat(fbCat === c ? '' : c)}
                      style={{
                        padding: '5px 12px', borderRadius: 16, fontSize: 12.5, cursor: 'pointer', transition: 'all .12s',
                        border: fbCat === c ? 'none' : '1px solid var(--mai-border)',
                        background: fbCat === c ? 'var(--mai-blue)' : 'white',
                        color: fbCat === c ? 'white' : 'var(--mai-fg-2)',
                      }}
                    >
                      {c}
                    </button>
                  ))}
                </div>
              </div>

              <div style={{ marginBottom: 14 }}>
                <textarea
                  value={fbText}
                  onChange={e => setFbText(e.target.value)}
                  placeholder={isZh
                    ? '請描述你的功能需求或改進建議，包含使用情境會更有幫助…'
                    : 'Describe your feature request or suggestion — including your use case helps us prioritize…'}
                  rows={4}
                  style={{
                    width: '100%', boxSizing: 'border-box', padding: '10px 12px',
                    border: '1px solid var(--mai-border)', borderRadius: 8,
                    fontSize: 13.5, lineHeight: 1.6, resize: 'vertical',
                    outline: 'none', fontFamily: 'inherit', color: '#1f2937',
                  }}
                  onFocus={e => { e.currentTarget.style.borderColor = 'var(--mai-blue)'; e.currentTarget.style.boxShadow = '0 0 0 3px rgba(31,79,255,.1)'; }}
                  onBlur={e => { e.currentTarget.style.borderColor = 'var(--mai-border)'; e.currentTarget.style.boxShadow = 'none'; }}
                />
              </div>

              <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <button
                  type="submit"
                  disabled={!fbText.trim()}
                  style={{
                    padding: '8px 22px', borderRadius: 8, border: 'none', fontSize: 13.5, fontWeight: 600,
                    cursor: fbText.trim() ? 'pointer' : 'not-allowed',
                    background: fbText.trim() ? 'var(--mai-blue)' : '#e5e7eb',
                    color: fbText.trim() ? 'white' : '#9ca3af',
                    transition: 'background .15s',
                  }}
                >
                  {isZh ? '送出回饋' : 'Submit Feedback'}
                </button>
              </div>
            </form>
          )}
        </div>
      </div>

      {/* Footer note */}
      <div style={{ marginTop: 16, padding: '11px 16px', background: '#f9fafb', borderRadius: 8, fontSize: 12.5, color: 'var(--mai-fg-2)', display: 'flex', alignItems: 'center', gap: 8 }}>
        <Icon name="info" size={13} />
        {isZh
          ? '路線圖功能與時程可能因市場需求或技術因素調整。如有特定需求，請聯繫你的 MaiAgent 夥伴經理。'
          : 'Roadmap features and timelines may change. Contact your MaiAgent Partner Manager for specific requirements.'}
      </div>
    </div>
  );
};

Object.assign(window, { RoadmapPage });
