/* AI Proposal Assistant — multi-turn needs clarification agent */

const PA_QUESTIONS = [
  {
    id: 'industry',
    zh: '請問客戶是哪個產業？',
    en: 'Which industry is your customer in?',
    type: 'select',
    options: {
      zh: ['金融保險', '零售電商', '製造業', '醫療健康', '教育', '政府機關', '科技 / SaaS', '服務業', '其他'],
      en: ['Finance / Insurance', 'Retail / E-commerce', 'Manufacturing', 'Healthcare', 'Education', 'Government', 'Tech / SaaS', 'Services', 'Other'],
    },
  },
  {
    id: 'size',
    zh: '公司規模大約多少人？',
    en: 'How large is the company?',
    type: 'select',
    options: {
      zh: ['< 50 人', '50–200 人', '200–1,000 人', '1,000+ 人'],
      en: ['< 50 employees', '50–200', '200–1,000', '1,000+'],
    },
  },
  {
    id: 'pains',
    zh: '客戶最主要的痛點是什麼？（可多選）',
    en: "What are the customer's main pain points? (select all that apply)",
    type: 'multi',
    options: {
      zh: ['客服人力不足', '重複詢問耗時', '多語言服務需求', '24/7 全天候服務', '現有系統整合困難', '資料分析不足'],
      en: ['Insufficient support staff', 'Repetitive queries waste time', 'Multi-language needs', '24/7 coverage gaps', 'Integration challenges', 'Limited analytics'],
    },
  },
  {
    id: 'budget',
    zh: '客戶的預算範圍？',
    en: "What is the customer's budget range?",
    type: 'select',
    options: {
      zh: ['< 50 萬 TWD', '50–150 萬 TWD', '150–500 萬 TWD', '500 萬以上 TWD', '尚未確定'],
      en: ['< NT$500K', 'NT$500K–1.5M', 'NT$1.5M–5M', 'NT$5M+', 'Not yet determined'],
    },
  },
  {
    id: 'timeline',
    zh: '期望的上線時程？',
    en: 'Expected go-live timeline?',
    type: 'select',
    options: {
      zh: ['1 個月內', '1–3 個月', '3–6 個月', '6 個月以上', '仍在評估'],
      en: ['Within 1 month', '1–3 months', '3–6 months', '6+ months', 'Still evaluating'],
    },
  },
];

function generateProposal(answers, lang) {
  const isZh = lang === 'zh';
  const pains = answers.pains || [];
  const industry = answers.industry || (isZh ? '企業' : 'enterprise');

  if (isZh) {
    return {
      title: `MaiAgent AI 客服解決方案 — ${industry}客戶提案草稿`,
      date: new Date().toLocaleDateString('zh-TW'),
      sections: [
        {
          heading: '執行摘要',
          body: `本提案針對 ${answers.size} 規模的${industry}企業，提供 MaiAgent AI 客服平台導入方案。透過自然語言理解與知識庫深度整合，協助客戶大幅降低人工客服負擔、提升首次解決率，並實現 24/7 全天候服務能力。`,
        },
        {
          heading: '客戶痛點分析',
          body: pains.length > 0
            ? pains.map(p => `• ${p}`).join('\n')
            : '• 客服效率提升需求\n• 全天候服務能力缺口\n• 人力成本控管壓力',
        },
        {
          heading: 'MaiAgent 解決方案',
          body: `MaiAgent 企業版提供：\n• AI 多輪對話機器人（支援繁中 / 簡中 / 英文）\n• 知識庫自動學習與持續更新\n• 多平台整合（LINE、WhatsApp、Web Chat、API）\n• 即時情緒偵測與轉人工機制\n• 企業級 SLA 99.9% 服務保證\n• SOC 2 Type II、ISO 27001 資安認證`,
        },
        {
          heading: '預算與時程規劃',
          body: `預估預算：${answers.budget}\n預計上線：${answers.timeline}\n\n建議導入階段：\n① 需求訪談與系統設計（1–2 週）\n② 知識庫建置與機器人訓練（3–4 週）\n③ 測試、調校與上線（1–2 週）\n④ 正式營運與持續優化（上線後 90 天）`,
        },
        {
          heading: '下一步行動',
          body: '① 安排 MaiAgent 工程師 Demo（90 分鐘，可遠端或現場）\n② 提供客戶現有系統規格，評估整合複雜度\n③ 完成 NDA 簽署後提供完整報價與 SLA 條款\n\n如需進一步協助，請透過 Partner Portal 聯繫你的 MaiAgent 夥伴經理。',
        },
      ],
    };
  } else {
    return {
      title: `MaiAgent AI Customer Service Solution — ${industry} Proposal Draft`,
      date: new Date().toLocaleDateString('en-US'),
      sections: [
        {
          heading: 'Executive Summary',
          body: `This proposal presents a MaiAgent AI customer service platform for a ${answers.size} company in the ${industry} sector. By combining natural language understanding with deep knowledge base integration, MaiAgent significantly reduces manual support workload, improves first-contact resolution, and delivers 24/7 service coverage.`,
        },
        {
          heading: 'Pain Point Analysis',
          body: pains.length > 0
            ? pains.map(p => `• ${p}`).join('\n')
            : '• Customer service efficiency gaps\n• 24/7 coverage limitations\n• Rising support staffing costs',
        },
        {
          heading: 'MaiAgent Solution',
          body: `MaiAgent Enterprise offers:\n• AI multi-turn chatbot (Traditional Chinese, Simplified Chinese, English)\n• Automatic knowledge base learning & updates\n• Multi-channel integration (LINE, WhatsApp, Web Chat, API)\n• Real-time sentiment detection with human escalation\n• Enterprise SLA 99.9% uptime guarantee\n• SOC 2 Type II and ISO 27001 certified`,
        },
        {
          heading: 'Budget & Timeline',
          body: `Estimated budget: ${answers.budget}\nExpected go-live: ${answers.timeline}\n\nSuggested phases:\n① Requirements & system design (1–2 weeks)\n② Knowledge base build & bot training (3–4 weeks)\n③ Testing, tuning & launch (1–2 weeks)\n④ Live operations & continuous improvement (90 days post-launch)`,
        },
        {
          heading: 'Next Steps',
          body: '① Schedule a MaiAgent engineer demo (90 min, remote or on-site)\n② Share customer system specs for integration scoping\n③ Sign NDA to receive full pricing and SLA terms\n\nFor further assistance, contact your MaiAgent Partner Manager via the Portal.',
        },
      ],
    };
  }
}

const ProposalAssistantPage = ({ t, lang }) => {
  const isZh = lang === 'zh';
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const [multiSel, setMultiSel] = React.useState([]);
  const [proposal, setProposal] = React.useState(null);
  const [generating, setGenerating] = React.useState(false);
  const [copied, setCopied] = React.useState(false);
  const chatRef = React.useRef(null);

  const q = PA_QUESTIONS[step];
  const done = step >= PA_QUESTIONS.length;

  React.useEffect(() => {
    if (chatRef.current) chatRef.current.scrollTop = chatRef.current.scrollHeight;
  }, [step, proposal]);

  function handleAnswer(val) {
    const newAnswers = { ...answers, [q.id]: val };
    setAnswers(newAnswers);
    if (step + 1 >= PA_QUESTIONS.length) {
      setGenerating(true);
      setTimeout(() => {
        setProposal(generateProposal(newAnswers, lang));
        setGenerating(false);
      }, 1800);
    }
    setStep(step + 1);
    setMultiSel([]);
  }

  function handleReset() {
    setStep(0);
    setAnswers({});
    setMultiSel([]);
    setProposal(null);
    setGenerating(false);
  }

  function handleCopy() {
    if (!proposal) return;
    const text = `${proposal.title}\n${proposal.date}\n\n${proposal.sections.map(s => `## ${s.heading}\n${s.body}`).join('\n\n')}`;
    navigator.clipboard.writeText(text).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  }

  // Build visible chat messages
  const messages = [];
  messages.push({
    role: 'agent',
    text: isZh
      ? '你好！我是 MaiAgent 提案助理。請依序回答以下問題，完成後我將自動生成一份客製化提案草稿。'
      : "Hello! I'm the MaiAgent Proposal Agent. Answer a few questions and I'll generate a customised proposal draft for you.",
  });
  PA_QUESTIONS.forEach((qq, i) => {
    if (i < step) {
      messages.push({ role: 'agent', text: qq[isZh ? 'zh' : 'en'] });
      const ans = answers[qq.id];
      const ansText = Array.isArray(ans) ? ans.join('、') : ans;
      if (ansText) messages.push({ role: 'user', text: ansText });
    } else if (i === step && !done) {
      messages.push({ role: 'agent', text: qq[isZh ? 'zh' : 'en'] });
    }
  });
  if (done && !generating) {
    messages.push({ role: 'agent', text: isZh ? '提案草稿已生成，請在右側查看並調整後發送給客戶。' : 'Your proposal draft is ready — review and adjust it on the right before sending to your customer.' });
  }

  const progressPct = Math.round((step / PA_QUESTIONS.length) * 100);

  return (
    <div style={{ padding: '24px', maxWidth: 1100, margin: '0 auto' }}>
      <style>{`@keyframes pa-spin { to { transform: rotate(360deg); } } @keyframes pa-pulse { 0%,100%{opacity:1} 50%{opacity:.4} }`}</style>

      {/* Header */}
      <div style={{ marginBottom: 20 }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, color: 'var(--mai-fg)', margin: '0 0 4px' }}>{t('pa.title')}</h1>
        <p style={{ margin: 0, color: 'var(--mai-fg-sub)', fontSize: 14 }}>{t('pa.sub')}</p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '400px 1fr', gap: 20, alignItems: 'start' }}>

        {/* ── Chat panel ── */}
        <div style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 12, display: 'flex', flexDirection: 'column', height: 620 }}>

          {/* Progress bar */}
          <div style={{ padding: '10px 14px 8px', borderBottom: '1px solid var(--mai-border)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
              <span style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--mai-fg-sub)' }}>
                {isZh ? `問題 ${Math.min(step + 1, PA_QUESTIONS.length)} / ${PA_QUESTIONS.length}` : `Question ${Math.min(step + 1, PA_QUESTIONS.length)} of ${PA_QUESTIONS.length}`}
              </span>
              <span style={{ fontSize: 11, color: 'var(--mai-primary)', fontWeight: 600 }}>{progressPct}%</span>
            </div>
            <div style={{ height: 4, background: '#e5e7eb', borderRadius: 4 }}>
              <div style={{ height: 4, background: 'var(--mai-primary)', borderRadius: 4, width: `${progressPct}%`, transition: 'width .4s ease' }} />
            </div>
          </div>

          {/* Messages */}
          <div ref={chatRef} style={{ flex: 1, overflowY: 'auto', padding: '14px 14px 8px', display: 'flex', flexDirection: 'column', gap: 10 }}>
            {messages.map((m, i) => (
              <div key={i} style={{ display: 'flex', justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start', gap: 8 }}>
                {m.role === 'agent' && (
                  <div style={{ width: 26, height: 26, borderRadius: 7, background: 'var(--mai-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, alignSelf: 'flex-end' }}>
                    <svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="white" strokeWidth="1.8" strokeLinecap="round"><path d="M2 6h12M6 10h4M4 2h8a2 2 0 012 2v6a2 2 0 01-2 2H9l-2 2-1-2H4a2 2 0 01-2-2V4a2 2 0 012-2z"/></svg>
                  </div>
                )}
                <div style={{
                  maxWidth: '78%',
                  padding: '8px 11px',
                  borderRadius: m.role === 'user' ? '12px 12px 4px 12px' : '4px 12px 12px 12px',
                  background: m.role === 'user' ? 'var(--mai-primary)' : '#f3f4f6',
                  color: m.role === 'user' ? 'white' : '#1f2937',
                  fontSize: 13,
                  lineHeight: 1.55,
                }}>
                  {m.text}
                </div>
              </div>
            ))}

            {generating && (
              <div style={{ display: 'flex', gap: 8 }}>
                <div style={{ width: 26, height: 26, borderRadius: 7, background: 'var(--mai-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="white" strokeWidth="1.8" strokeLinecap="round"><path d="M2 6h12M6 10h4M4 2h8a2 2 0 012 2v6a2 2 0 01-2 2H9l-2 2-1-2H4a2 2 0 01-2-2V4a2 2 0 012-2z"/></svg>
                </div>
                <div style={{ padding: '10px 14px', background: '#f3f4f6', borderRadius: '4px 12px 12px 12px', display: 'flex', gap: 5, alignItems: 'center' }}>
                  {[0,1,2].map(j => (
                    <div key={j} style={{ width: 7, height: 7, borderRadius: '50%', background: '#9ca3af', animation: `pa-pulse 1.2s ease-in-out ${j * 0.2}s infinite` }} />
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Input area */}
          <div style={{ borderTop: '1px solid var(--mai-border)', padding: 12 }}>
            {!done && q && q.type === 'select' && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {q.options[isZh ? 'zh' : 'en'].map(opt => (
                  <button
                    key={opt}
                    onClick={() => handleAnswer(opt)}
                    style={{ padding: '5px 11px', border: '1.5px solid var(--mai-primary)', borderRadius: 20, background: 'white', color: 'var(--mai-primary)', fontSize: 12.5, cursor: 'pointer', transition: 'all .12s' }}
                    onMouseEnter={e => { e.currentTarget.style.background = 'var(--mai-primary)'; e.currentTarget.style.color = 'white'; }}
                    onMouseLeave={e => { e.currentTarget.style.background = 'white'; e.currentTarget.style.color = 'var(--mai-primary)'; }}
                  >
                    {opt}
                  </button>
                ))}
              </div>
            )}

            {!done && q && q.type === 'multi' && (
              <div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 8 }}>
                  {q.options[isZh ? 'zh' : 'en'].map(opt => {
                    const sel = multiSel.includes(opt);
                    return (
                      <button
                        key={opt}
                        onClick={() => setMultiSel(sel ? multiSel.filter(x => x !== opt) : [...multiSel, opt])}
                        style={{ padding: '5px 11px', border: `1.5px solid ${sel ? 'transparent' : 'var(--mai-primary)'}`, borderRadius: 20, background: sel ? 'var(--mai-primary)' : 'white', color: sel ? 'white' : 'var(--mai-primary)', fontSize: 12.5, cursor: 'pointer', transition: 'all .12s' }}
                      >
                        {sel ? '✓ ' : ''}{opt}
                      </button>
                    );
                  })}
                </div>
                <button
                  onClick={() => handleAnswer(multiSel.length ? multiSel : [isZh ? '其他' : 'Other'])}
                  style={{ width: '100%', padding: '7px 0', background: 'var(--mai-primary)', color: 'white', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: 'pointer' }}
                >
                  {isZh ? '確認選擇' : 'Confirm selection'}
                </button>
              </div>
            )}

            {done && !generating && (
              <button
                onClick={handleReset}
                style={{ width: '100%', padding: '7px 0', border: '1px solid var(--mai-border)', borderRadius: 8, background: 'white', fontSize: 13, cursor: 'pointer', color: 'var(--mai-fg-sub)' }}
              >
                {isZh ? '重新開始 →' : 'Start over →'}
              </button>
            )}
          </div>
        </div>

        {/* ── Proposal panel ── */}
        <div style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 12, minHeight: 620 }}>
          {!proposal && !generating && (
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: 620, color: 'var(--mai-fg-sub)', textAlign: 'center', padding: 32 }}>
              <div style={{ fontSize: 52, marginBottom: 14 }}>📋</div>
              <p style={{ fontSize: 15, fontWeight: 600, color: '#374151', marginBottom: 8 }}>
                {isZh ? '提案草稿將在這裡生成' : 'Your proposal draft will appear here'}
              </p>
              <p style={{ fontSize: 13, lineHeight: 1.7, maxWidth: 280 }}>
                {isZh ? '依序回答左側的 5 個問題，完成後 AI 將自動產生一份客製化提案，可直接複製或匯出使用。' : 'Answer the 5 questions on the left — AI will generate a customised, copy-ready proposal.'}
              </p>
            </div>
          )}

          {generating && (
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: 620, gap: 16, color: 'var(--mai-fg-sub)' }}>
              <div style={{ width: 40, height: 40, border: '3px solid #e5e7eb', borderTopColor: 'var(--mai-primary)', borderRadius: '50%', animation: 'pa-spin 0.8s linear infinite' }} />
              <p style={{ fontSize: 14, margin: 0 }}>{isZh ? '正在生成提案草稿…' : 'Generating proposal draft…'}</p>
            </div>
          )}

          {proposal && !generating && (
            <div style={{ padding: '24px 28px' }}>
              {/* Proposal header */}
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 20, gap: 16 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                    <span style={{ fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 10, background: '#ecfdf5', color: '#059669', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                      {isZh ? '草稿' : 'Draft'}
                    </span>
                    <span style={{ fontSize: 11.5, color: 'var(--mai-fg-sub)' }}>{proposal.date}</span>
                  </div>
                  <h2 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: '#1f2937', lineHeight: 1.4 }}>{proposal.title}</h2>
                </div>
                <div style={{ display: 'flex', gap: 7, flexShrink: 0 }}>
                  <button
                    onClick={handleCopy}
                    style={{ padding: '6px 13px', border: '1px solid var(--mai-border)', borderRadius: 7, background: 'white', fontSize: 12.5, cursor: 'pointer', color: '#374151', display: 'flex', alignItems: 'center', gap: 5 }}
                  >
                    <Icon name="copy" size={12} />
                    {copied ? (isZh ? '已複製！' : 'Copied!') : (isZh ? '複製文字' : 'Copy text')}
                  </button>
                  <button
                    style={{ padding: '6px 13px', border: 'none', borderRadius: 7, background: 'var(--mai-primary)', color: 'white', fontSize: 12.5, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 5 }}
                  >
                    <Icon name="download" size={12} />
                    {isZh ? '匯出 PDF' : 'Export PDF'}
                  </button>
                </div>
              </div>

              {/* Proposal sections */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                {proposal.sections.map((s, i) => (
                  <div key={i} style={{ borderLeft: '3px solid var(--mai-primary)', paddingLeft: 14 }}>
                    <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--mai-primary)', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 6 }}>{s.heading}</div>
                    <p style={{ margin: 0, fontSize: 13.5, color: '#374151', lineHeight: 1.75, whiteSpace: 'pre-wrap' }}>{s.body}</p>
                  </div>
                ))}
              </div>

              {/* Disclaimer */}
              <div style={{ marginTop: 22, padding: '10px 14px', background: '#fffbeb', borderRadius: 8, fontSize: 12, color: '#92400e', border: '1px solid #fde68a' }}>
                ⚠️ {isZh ? '此為 AI 自動生成草稿，發送前請由業務人員審閱並依實際情況調整。' : 'AI-generated draft — please have a sales representative review and adjust before sending.'}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ProposalAssistantPage });
