// 緊急、打包、地圖、天氣等 sheet 內容
const { useState: useS, useEffect: useE } = React;

// === Emergency ===
function EmergencySheet() {
  const data = window.TRIP_EXTRAS.emergency;
  return (
    <div>
      <h2>🆘 緊急聯絡</h2>
      <p style={{fontSize:"0.78rem", color:"var(--fg-muted)", margin:"-0.4rem 0 1rem"}}>
        資訊校對日：{data.verified}。出發前請再次確認。
      </p>
      {data.sections.map(sec => (
        <section key={sec.id} className="eg-section">
          <h3>{sec.title} <span className="jp">{sec.titleJp}</span></h3>
          {sec.note && <p className="note">{sec.note}</p>}
          <ul className="eg-list">
            {sec.items.map((it, i) => (
              <li key={i} className={`eg-item ${it.placeholder ? "placeholder" : ""}`}>
                <div className="eg-icon">{it.emoji}</div>
                <div>
                  <div className="eg-label">{it.label}</div>
                  <div className="eg-desc">{it.desc}</div>
                </div>
                <div>
                  {it.tel && it.tel !== "—" && (
                    <a className="eg-tel" href={`tel:${it.tel.replace(/[^+0-9]/g,"")}`}>{it.tel}</a>
                  )}
                  {it.tel === "—" && <span className="eg-tel">—</span>}
                  {it.url && !it.tel && (
                    <a className="eg-tel" href={it.url} target="_blank" rel="noreferrer">前往 ↗</a>
                  )}
                  {it.url && it.tel && (
                    <a className="eg-tel" href={it.url} target="_blank" rel="noreferrer" style={{display:"block", fontSize:"0.7rem", marginTop:"2px"}}>↗ 連結</a>
                  )}
                </div>
              </li>
            ))}
          </ul>
        </section>
      ))}

      <section className="eg-section">
        <h3>🗣️ 應急日語 <span className="jp">緊急日本語</span></h3>
        <p className="note">完整日語短句（招呼、餐廳、購物、交通、飯店）請從底部「日語」進入。</p>
        <div style={{padding:"0.5rem 0"}}>
          {window.TRIP_EXTRAS.phrases.sections.map((sec, i) => (
            <div key={i}>
              <div style={{fontSize:"0.78rem", color:"var(--accent)", padding:"0.4rem 1rem 0.2rem", fontWeight:600, letterSpacing:"0.05em"}}>
                {sec.title}
              </div>
              {sec.items.map((p, j) => <PhraseRow key={j} p={p} />)}
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}

// === Phrase Row (shared) ===
function PhraseRow({ p }) {
  return (
    <div className="phrase-item">
      <div style={{display:"flex", alignItems:"flex-start", gap:"0.6rem"}}>
        <div style={{flex:1, minWidth:0}}>
          <div className="phrase-tw">{p.tw}</div>
          <div className="phrase-jp">{p.jp}</div>
          <div className="phrase-romaji">{p.romaji}</div>
        </div>
        <button className="icon-btn" title="朗讀日文"
          style={{flex:"0 0 auto", marginTop:"2px"}}
          onClick={() => {
            try {
              const synth = window.speechSynthesis;
              if (!synth) { alert("此瀏覽器不支援語音朗讀"); return; }
              synth.cancel();
              const u = new SpeechSynthesisUtterance(p.jp);
              u.lang = "ja-JP"; u.rate = 0.85;
              const jpVoice = synth.getVoices().find(v => v.lang.startsWith("ja"));
              if (jpVoice) u.voice = jpVoice;
              synth.speak(u);
            } catch(e){}
          }}>🔊</button>
      </div>
    </div>
  );
}

// === Phrases Sheet (常用 + 應急) ===
function PhrasesSheet() {
  const [tab, setTab] = useS("casual");
  const data = tab === "casual" ? window.TRIP_EXTRAS.phrasesCasual : window.TRIP_EXTRAS.phrases;
  return (
    <div>
      <h2>🗣️ 日語短句</h2>
      <p style={{fontSize:"0.85rem", color:"var(--fg-soft)", margin:"-0.4rem 0 1rem"}}>
        點 🔊 由瀏覽器朗讀。語速放慢，適合複誦。
      </p>
      <div className="choice-row" style={{marginBottom:"1rem"}}>
        <button className={`choice-btn ${tab === "casual" ? "is-active" : ""}`} onClick={() => setTab("casual")}>常用</button>
        <button className={`choice-btn ${tab === "emergency" ? "is-active" : ""}`} onClick={() => setTab("emergency")}>應急</button>
      </div>
      {data.sections.map((sec, i) => (
        <section key={i} className="eg-section">
          <h3>{sec.title}</h3>
          <div style={{padding:"0.25rem 0"}}>
            {sec.items.map((p, j) => <PhraseRow key={j} p={p} />)}
          </div>
        </section>
      ))}
    </div>
  );
}

// === Packing ===
// 預設清單轉成可編輯結構：每項為 { text, done }
function buildDefaultPack() {
  return window.TRIP_EXTRAS.packing.sections.map(sec => ({
    title: sec.title,
    items: sec.items.map(text => ({ text, done: false })),
  }));
}

function PackingSheet() {
  const [list, setList] = useS(() => {
    try {
      const saved = JSON.parse(localStorage.getItem("hkd-pack") || "null");
      if (Array.isArray(saved)) return saved; // 新版整份清單；舊版位置鍵物件則忽略、回到預設
    } catch {}
    return buildDefaultPack();
  });
  const [draft, setDraft] = useS({});        // 各分類「新增」輸入框內容
  const [confirming, setConfirming] = useS(false);

  const persist = (next) => {
    setList(next);
    localStorage.setItem("hkd-pack", JSON.stringify(next));
  };
  const editSection = (si, fn) =>
    persist(list.map((sec, s) => (s === si ? fn(sec) : sec)));

  const toggle = (si, ii) => editSection(si, sec => ({
    ...sec,
    items: sec.items.map((it, i) => (i === ii ? { ...it, done: !it.done } : it)),
  }));
  const removeItem = (si, ii) => editSection(si, sec => ({
    ...sec,
    items: sec.items.filter((_, i) => i !== ii),
  }));
  const addItem = (si) => {
    const text = (draft[si] || "").trim();
    if (!text) return;
    editSection(si, sec => ({ ...sec, items: [...sec.items, { text, done: false }] }));
    setDraft(prev => ({ ...prev, [si]: "" }));
  };
  const resetAll = () => { persist(buildDefaultPack()); setConfirming(false); };

  return (
    <div>
      <div className="pack-head">
        <h2>🎒 打包清單</h2>
        {confirming ? (
          <span className="pack-reset-group">
            <button className="pack-reset is-confirm" onClick={resetAll}>確定還原</button>
            <button className="pack-reset" onClick={() => setConfirming(false)}>取消</button>
          </span>
        ) : (
          <button className="pack-reset" onClick={() => setConfirming(true)}>↺ 還原預設</button>
        )}
      </div>
      <p style={{fontSize:"0.85rem", color:"var(--fg-soft)", margin:"-0.4rem 0 1rem"}}>
        勾選、新增、刪除都會自動存在這支裝置上；按右上「還原預設」可回到原始清單。北海道 6 月初夏，日均溫 12-22°C，早晚涼，請帶薄外套。
      </p>
      {list.map((sec, si) => {
        const total = sec.items.length;
        const checked = sec.items.filter(it => it.done).length;
        return (
          <section key={si} className="pack-section">
            <h3>
              {sec.title}
              <span className="pack-progress">{checked}/{total}</span>
            </h3>
            <ul className="pack-list">
              {sec.items.map((item, i) => (
                <li key={i} className={`pack-item ${item.done ? "is-done" : ""}`}>
                  <span className="pack-check" onClick={() => toggle(si, i)}>✓</span>
                  <span className="pack-label" onClick={() => toggle(si, i)}>{item.text}</span>
                  <button className="pack-del" onClick={() => removeItem(si, i)} aria-label="刪除項目">✕</button>
                </li>
              ))}
            </ul>
            <div className="pack-add">
              <input className="pack-add-input" type="text" placeholder="新增項目…"
                value={draft[si] || ""}
                onChange={(e) => setDraft(prev => ({ ...prev, [si]: e.target.value }))}
                onKeyDown={(e) => { if (e.key === "Enter") addItem(si); }} />
              <button className="pack-add-btn" onClick={() => addItem(si)} aria-label="新增項目">＋</button>
            </div>
          </section>
        );
      })}
    </div>
  );
}

// === Weather ===
function WeatherSheet() {
  const f = window.WEATHER_FORECAST;
  return (
    <div>
      <h2>☁️ 天氣概覽</h2>
      <p style={{fontSize:"0.78rem", color:"var(--fg-muted)", margin:"-0.4rem 0 1rem"}}>
        資料來源：{f.source}
      </p>
      <div className="weather-grid">
        {f.days.map((d, i) => (
          <div key={i} className="weather-card">
            <div className="day">{d.date}</div>
            <div className="icon">{d.icon}</div>
            <div className="temp">{d.high}° / {d.low}°</div>
            <div className="city">{d.city}</div>
          </div>
        ))}
      </div>
      <div className="weather-note">
        <strong>📌 6 月中下旬北海道氣候特性</strong><br/>
        ・本州梅雨期間，但北海道幾乎不受梅雨影響，是旅遊好時機。<br/>
        ・日夜溫差大，早晚 12-15°C 需薄外套，白天 20-24°C。<br/>
        ・偶有短暫陣雨，可備折傘或輕便雨衣。<br/>
        ・接入即時 API（如 Open-Meteo）後，這裡會顯示真實預報。
      </div>
    </div>
  );
}

// === Trip Map (SVG bird-eye) ===
function MapSheet() {
  // 概略示意：北海道輪廓 + 各天標記
  const points = [
    { x: 540, y: 410, label: "千歲 / 新千歲", days: [1, 9] },
    { x: 510, y: 430, label: "支笏湖", days: [2] },
    { x: 470, y: 480, label: "登別", days: [2] },
    { x: 430, y: 510, label: "洞爺湖", days: [2, 3] },
    { x: 370, y: 600, label: "函館", days: [3, 4, 5] },
    { x: 480, y: 380, label: "小樽", days: [5, 6] },
    { x: 545, y: 385, label: "札幌", days: [6, 7, 8] },
  ];
  return (
    <div>
      <h2>🗺️ 旅程地圖</h2>
      <p style={{fontSize:"0.85rem", color:"var(--fg-soft)", margin:"-0.4rem 0 1rem"}}>
        9 天 8 夜路線概覽，從新千歲機場出發，環繞道南再返札幌。
      </p>
      <div className="map-wrap">
        <svg className="map-svg" viewBox="200 250 500 450" xmlns="http://www.w3.org/2000/svg">
          <defs>
            <pattern id="hatch" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
              <line x1="0" y1="0" x2="0" y2="6" stroke="var(--wood-300)" strokeWidth="1"/>
            </pattern>
          </defs>
          {/* 北海道輪廓 (簡化示意) */}
          <path d="M 295 300 Q 350 280 420 290 Q 480 285 540 295 Q 600 305 640 340 Q 680 375 670 420 Q 660 450 620 470 L 580 460 L 560 480 Q 555 490 545 495 L 540 510 Q 535 520 510 525 Q 480 528 460 540 L 440 555 Q 420 570 400 590 Q 380 615 360 630 Q 340 640 320 625 Q 300 605 285 580 Q 270 555 270 520 Q 268 480 280 440 Q 285 400 295 360 Q 295 330 295 300 Z"
            fill="url(#hatch)" stroke="var(--accent)" strokeWidth="2" strokeLinejoin="round" opacity="0.85"/>
          {/* 路線連結 */}
          <g stroke="var(--accent)" strokeWidth="1.5" strokeDasharray="4 3" fill="none" opacity="0.6">
            <path d="M 540 410 L 510 430 L 470 480 L 430 510 L 370 600" />
            <path d="M 370 600 L 480 380" />
            <path d="M 480 380 L 545 385" />
            <path d="M 545 385 L 540 410" />
          </g>
          {/* 點 */}
          {points.map((p, i) => (
            <g key={i}>
              <circle cx={p.x} cy={p.y} r="7" fill="var(--accent)" stroke="#fff" strokeWidth="2"/>
              <text x={p.x + 12} y={p.y + 5} fontSize="13" fill="var(--fg)" fontFamily="var(--font-body)">
                {p.label}
              </text>
              <text x={p.x + 12} y={p.y + 20} fontSize="10" fill="var(--fg-muted)" fontFamily="var(--font-mono)">
                Day {p.days.join("·")}
              </text>
            </g>
          ))}
        </svg>
        <div className="map-legend">
          <span><span className="swatch" style={{background:"var(--accent)"}}></span>停留點</span>
          <span>--- 自駕路線</span>
          <span style={{color:"var(--fg-muted)"}}>※ 為示意圖，實際以 Google Maps 為準</span>
        </div>
      </div>

      <h3 className="section-h">各天 Google Maps 連結</h3>
      {window.TRIP_DATA.days.map(d => {
        // 取每天最多 3 個地圖連結
        const links = d.blocks.filter(b => b.mapLink).slice(0, 3);
        if (!links.length) return null;
        return (
          <div key={d.id} style={{marginBottom:"0.85rem", padding:"0.75rem 1rem", background:"var(--card-bg, #fff)", border:"1px solid var(--line)", borderRadius:"var(--radius)"}}>
            <div style={{fontWeight:600, marginBottom:"0.4rem"}}>{d.label} · {d.title}</div>
            <div className="tl-actions">
              {links.map((b, i) => (
                <a key={i} className="pill" href={b.mapLink} target="_blank" rel="noreferrer">
                  📍 {b.title}
                </a>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// === Settings ===
function SettingsSheet({ style, setStyle, fontSize, setFontSize }) {
  const styleOpts = [
    { id: "zasshi",  label: "日系雜誌", desc: "米白底、襯線、優雅" },
    { id: "minimal", label: "現代簡約", desc: "白底、無襯線、留白" },
    { id: "techo",   label: "復古手帳", desc: "牛皮紙、手寫感、貼紙" },
  ];
  const fontOpts = [
    { id: "small",  label: "小" },
    { id: "normal", label: "中" },
    { id: "large",  label: "大" },
    { id: "xl",     label: "特大" },
  ];
  return (
    <div>
      <h2>⚙️ 設定</h2>
      <div className="settings-row">
        <div className="label">視覺風格</div>
        <div className="desc">同一份內容、三種視覺氛圍。</div>
        <div className="choice-row">
          {styleOpts.map(o => (
            <button key={o.id}
              className={`choice-btn ${style === o.id ? "is-active" : ""}`}
              onClick={() => setStyle(o.id)}>
              {o.label}
            </button>
          ))}
        </div>
      </div>
      <div className="settings-row">
        <div className="label">字級</div>
        <div className="desc">戶外陽光下可調大；翻譯日文時調小。</div>
        <div className="choice-row">
          {fontOpts.map(o => (
            <button key={o.id}
              className={`choice-btn ${fontSize === o.id ? "is-active" : ""}`}
              onClick={() => setFontSize(o.id)}>
              {o.label}
            </button>
          ))}
        </div>
      </div>
      <div className="settings-row">
        <div className="label">PWA · 離線使用</div>
        <div className="desc">已註冊 Service Worker，第二次開啟後即使無網路也能看。可從瀏覽器選單「加到主畫面」。</div>
      </div>
      <div className="settings-row">
        <div className="label">關於</div>
        <div className="desc" style={{lineHeight:1.7}}>
          設計給五人北海道之旅，2026/06/16 — 06/24。<br/>
          所有景點介紹與資訊整理自官網與旅遊指南。<br/>
          照片優先使用官方來源，找不到的留佔位由你補上。
        </div>
      </div>
    </div>
  );
}

window.TripSheets = { EmergencySheet, PackingSheet, WeatherSheet, MapSheet, SettingsSheet, PhrasesSheet };
