const { useState: useWLState } = React;

/*
  GOOGLE SHEETS 串接說明：
  1. 開啟 Google Sheets > 擴充功能 > Apps Script
  2. 貼入以下程式碼並儲存：

  const SHEET_ID = '1SGB35gGCU6MgFR0ZtlJVeGhQxdfbuhBF2Qmz6x5PIb8';

  function doPost(e) {
    const data = JSON.parse(e.postData.contents);
    const sheet = SpreadsheetApp.openById(SHEET_ID).getSheets()[0];
    if (sheet.getLastRow() === 0) {
      sheet.appendRow(['時間戳記', 'Email', 'AI Agent', '希望解決的問題', 'Interview 時段', '語言']);
    }
    sheet.appendRow([data.timestamp, data.email, data.role, data.pains, data.availability, data.lang]);
    return ContentService.createTextOutput(JSON.stringify({ status: 'ok' })).setMimeType(ContentService.MimeType.JSON);
  }

  function doGet(e) {
    return ContentService.createTextOutput('OK');
  }

  3. 點選「部署 > 新增部署」，類型選「網頁應用程式」，執行者「我」，存取權「任何人」
  4. 複製部署 URL，貼到下方 APPS_SCRIPT_URL
*/

const APPS_SCRIPT_URL = 'https://script.google.com/macros/s/AKfycbwLmq8AIQX2RUVOv8CzWJQHAFQjJZ6PMnRBhq0JR3FXP5VtTczgCI1_k__n7ezELfkIdA/exec';

// AI agent 選項 (跟語言無關,選項內容是品牌名稱)
const AGENT_OPTIONS = ['claude', 'open claw', 'Codex', 'Gemini CLI', 'Llama', '其他'];

// pain points / availability 的 KEY (語言無關),顯示文字從 i18n 讀
const PAIN_KEYS = ['skill', 'token', 'pii', 'block', 'data', 'control'];

function Waitlist() {
  const lang = useLang();
  const T = window.__I18N__[lang].waitlist;

  const [email, setEmail]         = useWLState('');
  const [role, setRole]           = useWLState('claude');
  const [roleOther, setRoleOther] = useWLState('');
  const [pains, setPains]         = useWLState(new Set(['pii']));
  const [avails, setAvails]       = useWLState([]);
  const [submitted, setSubmitted] = useWLState(false);
  const [sending, setSending]     = useWLState(false);
  const [errorMsg, setErrorMsg]   = useWLState('');

  // EN 模式時,如果選項 value 是中文 "其他",顯示成 "Other"
  const renderAgentOption = (opt) => {
    if (opt === '其他') return lang === 'en' ? 'Other' : '其他';
    return opt;
  };

  const togglePain = (id) => {
    const next = new Set(pains);
    next.has(id) ? next.delete(id) : next.add(id);
    setPains(next);
  };

  const toggleAvail = (a) => {
    setAvails(prev =>
      prev.includes(a) ? prev.filter(x => x !== a) : [...prev, a]
    );
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setErrorMsg('');
    if (!APPS_SCRIPT_URL) {
      setSubmitted(true);
      return;
    }
    setSending(true);
    try {
      const finalRole = role === '其他' ? (roleOther.trim() || 'Other') : role;
      // pains/avails 永遠以 EN key 送出 (不論 UI 語言),方便後端統一處理
      const payload = {
        timestamp: new Date().toISOString(),
        email,
        role: finalRole,
        pains: [...pains].join(','),
        availability: avails.join(','),
        lang
      };
      const res = await fetch(APPS_SCRIPT_URL, {
        method: 'POST',
        body: JSON.stringify(payload),
        headers: { 'Content-Type': 'text/plain;charset=utf-8' },
      });
      if (!res.ok) throw new Error((res.status));
      setSubmitted(true);
    } catch (err) {
      setErrorMsg(T.submitErrorPrefix + (err?.message || (lang === 'en' ? 'Unknown error' : '未知錯誤')));
    } finally {
      setSending(false);
    }
  };

  return (
    <section id="waitlist" className="lo-waitlist lo-reveal">
      <div className="lo-eyebrow lo-eyebrow-on-dark">{T.eyebrow}</div>
      <h2 className="lo-h1-serif lo-on-dark">{T.title}</h2>
      <p className="lo-on-dark-sub">{T.sub}</p>

      {!submitted ? (
        <form className="lo-waitlist-card" onSubmit={handleSubmit}>
          <div className="lo-form-row">
            <div className="lo-field">
              <label>{T.emailLabel}</label>
              <input
                type="email"
                required
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder={T.emailPlaceholder}
              />
            </div>
            <div className="lo-field">
              <label>{T.agentLabel}</label>
              <select value={role} onChange={(e) => setRole(e.target.value)}>
                {AGENT_OPTIONS.map(opt => (
                  <option key={opt} value={opt}>{renderAgentOption(opt)}</option>
                ))}
              </select>
              {role === '其他' && (
                <input
                  type="text"
                  value={roleOther}
                  onChange={(e) => setRoleOther(e.target.value)}
                  placeholder={T.agentOtherPlaceholder}
                  style={{ marginTop: 8 }}
                />
              )}
            </div>
          </div>

          <div className="lo-field">
            <label>
              {T.painsLabel}<span className="lo-multi-hint">{T.painsHint}</span>
            </label>
            <div className="lo-chips">
              {PAIN_KEYS.map(id => (
                <button
                  type="button"
                  key={id}
                  className={`lo-chip ${pains.has(id) ? 'lo-chip-on' : ''}`}
                  onClick={() => togglePain(id)}
                >{T.pains[id]}</button>
              ))}
            </div>
          </div>

          <div className="lo-field">
            <label>
              {T.interviewLabel}<span className="lo-multi-hint">{T.interviewHint}</span>
            </label>
            <div className="lo-chips">
              {T.slots.map((label, i) => (
                <button
                  type="button"
                  key={i}
                  className={`lo-chip ${avails.includes(label) ? 'lo-chip-on' : ''}`}
                  onClick={() => toggleAvail(label)}
                >{label}</button>
              ))}
            </div>
          </div>

          <button type="submit" className="lo-btn lo-btn-primary lo-btn-block" disabled={sending}>
            {sending ? T.submitting : T.submit}
          </button>
          {errorMsg && (
            <p className="lo-form-error" style={{ color: '#9B3A2F', font: '500 13px/1.5 var(--font-sans)', marginTop: 12 }}>
              {errorMsg}
            </p>
          )}
        </form>
      ) : (
        <div className="lo-waitlist-done">
          <div className="lo-waitlist-check">✓</div>
          <h3>{T.doneTitle}</h3>
          <p>{T.doneBody}</p>
          <p>{T.doneEmailLabel} octopus.cute26@gmail.com</p>
        </div>
      )}
    </section>
  );
}

function Footer() {
  const lang = useLang();
  const T = window.__I18N__[lang].footer;
  return (
    <footer className="lo-footer">
      <div className="lo-logo lo-logo-sm">
        <img src={(window.__resources && window.__resources.mascotPng) || "assets/octopus-mascot.png"} alt="" />
        <span>Little Octopus</span>
      </div>
      <div className="lo-footer-links">
        <a href="#">{T.privacy}</a>
        <a href="#">{T.terms}</a>
        <a href="#">{T.contact}</a>
      </div>
      <div className="lo-footer-meta">{T.meta}</div>
    </footer>
  );
}
