/* global React, Icon, TRIP_DATA */

// 韓語發音：瀏覽器 Web Speech API
function speakKorean(text) {
  if (!('speechSynthesis' in window)) {
    alert('此瀏覽器不支援語音功能，建議用 Chrome 或 Safari');
    return;
  }
  window.speechSynthesis.cancel();
  const u = new SpeechSynthesisUtterance(text);
  u.lang = 'ko-KR';
  u.rate = 0.9;
  u.pitch = 1.0;
  // 嘗試挑選韓文語音
  const voices = window.speechSynthesis.getVoices();
  const ko = voices.find(v => v.lang?.startsWith('ko'));
  if (ko) u.voice = ko;
  window.speechSynthesis.speak(u);
}

// 首次載入時觸發 voices 初始化（Chrome 會非同步載入）
if (typeof window !== 'undefined' && 'speechSynthesis' in window) {
  window.speechSynthesis.getVoices();
  window.speechSynthesis.onvoiceschanged = () => window.speechSynthesis.getVoices();
}

function PhraseCard({ p }) {
  const [playing, setPlaying] = React.useState(false);
  const play = () => {
    setPlaying(true);
    speakKorean(p.ko);
    setTimeout(() => setPlaying(false), Math.max(1200, p.ko.length * 180));
  };
  return (
    <button className={`phrase-card ${playing ? 'playing' : ''}`} onClick={play}>
      <div className="phrase-body">
        <div className="phrase-ko">{p.ko}</div>
        <div className="phrase-zh">{p.zh}</div>
        <div className="phrase-romaji">{p.romaji}</div>
      </div>
      <div className="phrase-play" aria-label="播放韓文發音">
        {playing ? (
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <rect x="6" y="5" width="4" height="14" rx="1" fill="currentColor"/>
            <rect x="14" y="5" width="4" height="14" rx="1" fill="currentColor"/>
          </svg>
        ) : (
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <path d="M4 9v6h4l5 4V5L8 9H4z" fill="currentColor"/>
            <path d="M16 8a5 5 0 010 8M18.5 5.5a8 8 0 010 13" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
          </svg>
        )}
      </div>
    </button>
  );
}

function GuideTab() {
  const g = TRIP_DATA.guide;
  return (
    <>
      <div className="guide-hero fade-in">
        <h3>TRAVEL GUIDE · 여행 가이드</h3>
        <h1>濟州島必備指南</h1>
        <p>匯率、插座、交通、關鍵語句一次收齊</p>
      </div>

      <div className="essential-grid">
        {g.essentials.map((e, i) => (
          <div key={i} className="ess-card">
            <div className="ess-icon">{e.icon}</div>
            <div className="ess-title">{e.title}</div>
            <div className="ess-detail">{e.detail}</div>
          </div>
        ))}
      </div>

      <div className="section-title">行程小貼士</div>
      {g.tips.map((t, i) => (
        <div key={i} className="tip-card">
          <h4>{t.title}</h4>
          <ul>{t.lines.map((l, j) => <li key={j}>{l}</li>)}</ul>
        </div>
      ))}

      <div className="section-title">旅遊韓語 <span style={{ fontSize: 11, fontWeight: 500, color: 'var(--warm-1)', marginLeft: 6 }}>點卡片聽發音 🔊</span></div>
      {g.phrases.map((group, gi) => (
        <div key={gi} className="phrase-group">
          <div className="phrase-cat">{group.cat}</div>
          {group.items.map((p, i) => (
            <PhraseCard key={i} p={p}/>
          ))}
        </div>
      ))}
    </>
  );
}

function WIcon({ type, size = 28 }) {
  if (type === 'sun') return Icon.sun('#E8B74F', size);
  if (type === 'cloud') return Icon.cloudIcon('#8C8276', size);
  if (type === 'sun-cloud') return Icon.sunCloud('#4A7FB5', size);
  if (type === 'rain') return Icon.rain('#4A7FB5', size);
  return Icon.cloudIcon('#8C8276', size);
}

function WeatherTab() {
  const w = TRIP_DATA.weather;
  const today = w[0];
  const avgT = Math.round(w.reduce((s,d)=>s+d.t,0)/w.length);
  return (
    <>
      <div className="w-hero fade-in">
        <div className="w-hero-top">
          <div>
            <div className="sub">JEJU · 제주</div>
            <div className="loc">濟州市</div>
          </div>
          <div style={{ transform: 'scale(1.5) translate(-4px, 4px)' }}>
            <WIcon type={today.icon} size={40}/>
          </div>
        </div>
        <div className="w-hero-temp">{today.t}<sup>°</sup></div>
        <div className="w-hero-cond">{today.cond} · 體感 {today.t - 1}°</div>
        <div className="w-hero-meta">
          <span>{Icon.drop('rgba(255,255,255,0.85)')} {today.pop}%</span>
          <span>{Icon.wind('rgba(255,255,255,0.85)')} {today.wind} km/h</span>
          <span>旅程平均 {avgT}°</span>
        </div>
      </div>

      <div className="section-title">5 日預報</div>
      <div className="w-list">
        {w.map((d, i) => (
          <div key={i} className="w-row">
            <div>
              <div className="w-row-day">{d.day}</div>
              <div className="w-row-date">{d.date}</div>
            </div>
            <div className="w-row-cond">{d.cond}</div>
            <WIcon type={d.icon} size={26}/>
            <div className="w-row-temps"><span className="low">{d.low}°</span>{d.t}°</div>
          </div>
        ))}
      </div>

      <div className="w-advice">
        <div className="w-advice-emoji">🧥</div>
        <div>
          <h4>穿搭建議</h4>
          <p>
            日間 21–25°、夜間 15–18°，溫差大。
            建議薄長袖＋針織外套，Day 5 記得帶防雨外套。牛島風大，髮帶／帽子也別忘！
          </p>
        </div>
      </div>

      <div className="w-advice">
        <div className="w-advice-emoji">☂</div>
        <div>
          <h4>雨備提醒</h4>
          <p>
            Day 3 機率 30%、Day 5 達 40%。折傘塞一把最安心；
            雨天可改走 Audrant 麵包、機場採購等室內行程。
          </p>
        </div>
      </div>
    </>
  );
}

window.GuideTab = GuideTab;
window.WeatherTab = WeatherTab;
