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', '主要身分', '希望解決的問題', 'Interview 時段']);
    }
    sheet.appendRow([data.timestamp, data.email, data.role, data.pains, data.availability]);
    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'; // 貼上你的 Apps Script Web App URL

const painPoints = [
  { id: 'skill',   label: '🛡️ 惡意 Skill' },
  { id: 'token',   label: '💰 節省 Token 成本' },
  { id: 'pii',     label: '🔒 擔心資料外洩' },
  { id: 'block',   label: '⚡ 惡意 Chrome 擴充' },
  { id: 'data',    label: '📄 有毒的資料' },
  { id: 'control',     label: '🦠 Agent 被外部操控' }
];

const availability = [
  '週二晚上', '週三晚上', '週四晚上', '週六下午','週日下午'
];

function Waitlist() {
  const [email, setEmail] = useWLState('');
  const [role, setRole] = 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('');

  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 payload = {
        timestamp: new Date().toISOString(),
        email,
        role,
        pains: [...pains].join(','),
        availability: avails.join(',')
      };
      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('送出失敗，請稍後再試：' + (err?.message || '未知錯誤'));
    } finally {
      setSending(false);
    }
  };

  return (
    <section id="waitlist" className="lo-waitlist lo-reveal">
      <div className="lo-eyebrow lo-eyebrow-on-dark">Early Access</div>
      <h2 className="lo-h1-serif lo-on-dark">加入早期預約名單</h2>
      <p className="lo-on-dark-sub">我們將於近期發布 Demo 測試版。</p>

      {!submitted ? (
        <form className="lo-waitlist-card" onSubmit={handleSubmit}>
          <div className="lo-form-row">
            <div className="lo-field">
              <label>聯絡 Email</label>
              <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="dev@company.com" />
            </div>
            <div className="lo-field">
              <label>主要身分</label>
              <select value={role} onChange={(e) => setRole(e.target.value)}>
                <option>獨立開發者 / 個人玩家</option>
                <option>新創團隊 (Solopreneur)</option>
                <option>企業資安管理部門</option>
                <option>AI 研究員</option>
              </select>
            </div>
          </div>

          <div className="lo-field">
            <label>最希望解決的問題？<span className="lo-multi-hint">（可複選）</span></label>
            <div className="lo-chips">
              {painPoints.map(p => (
                <button
                  type="button"
                  key={p.id}
                  className={`lo-chip ${pains.has(p.id) ? 'lo-chip-on' : ''}`}
                  style={p.id === 'observability' ? { opacity: 1.74, backgroundColor: 'rgba(234, 229, 217, 0)' } : undefined}
                  onClick={() => togglePain(p.id)}
                >{p.label}</button>
              ))}
            </div>
          </div>

          <div className="lo-field">
            <label>Interview 時段<span className="lo-multi-hint">（可複選）</span></label>
            <div className="lo-chips">
              {availability.map(a => (
                <button
                  type="button"
                  key={a}
                  className={`lo-chip ${avails.includes(a) ? 'lo-chip-on' : ''}`}
                  onClick={() => toggleAvail(a)}
                >{a}</button>
              ))}
            </div>
          </div>

          <button type="submit" className="lo-btn lo-btn-primary lo-btn-block" disabled={sending}>
            {sending ? '送出中...' : '送出並加入預約名單 →'}
          </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>預約成功！</h3>
          <p>感謝您的支持。我們會在 Demo 發布前先通知您。</p>
          <p>信箱:octopus.cute26@gmail.com</p>
        </div>
      )}
    </section>
  );
}

function Footer() {
  return (
    <footer className="lo-footer">
      <div className="lo-logo lo-logo-sm">
        <img src="../../assets/octopus-mascot.png" alt="" />
        <span>Little Octopus</span>
      </div>
      <div className="lo-footer-links">
        <a href="#">隱私權政策</a>
        <a href="#">使用條款</a>
        <a href="#">聯絡我們</a>
      </div>
      <div className="lo-footer-meta">© 2026 Little Octopus Startup.</div>
    </footer>
  );
}
