// 主要 React 元件
const { useState, useEffect, useMemo, useRef, useCallback } = React;

// === Helpers ===
// 回傳今天對應的 day id；若今天不在旅行範圍內回傳 null
function getTodayDayId(days) {
  const today = new Date();
  const todayStr = today.getFullYear() + "-" +
    String(today.getMonth() + 1).padStart(2, "0") + "-" +
    String(today.getDate()).padStart(2, "0");
  const match = days.find(d => d.date === todayStr);
  return match ? match.id : null;
}

// 依現在 HH:MM 找該天目前該在哪個 block (回傳 index 或 -1)
function getCurrentBlockIdx(day) {
  if (!day) return -1;
  const now = new Date();
  const cur = now.getHours() * 60 + now.getMinutes();
  let idx = -1;
  for (let i = 0; i < day.blocks.length; i++) {
    const t = day.blocks[i].time;
    if (!t) continue;
    const [h, m] = t.split(":").map(Number);
    const mins = h * 60 + m;
    if (mins <= cur) idx = i;
    else break;
  }
  return idx;
}

const KIND_LABEL = {
  spot:   { label: "景點", emoji: "📍" },
  food:   { label: "餐食", emoji: "🍚" },
  hotel:  { label: "住宿", emoji: "🏨" },
  transit:{ label: "交通", emoji: "🚗" },
  flight: { label: "航班", emoji: "✈️" },
};

function formatDate(iso) {
  const [y, m, d] = iso.split("-");
  return `${m}/${d}`;
}

// === Route Card (替代 Google Maps Static API) ===
function RouteCard({ from, to, km, mins, mapLink }) {
  const inner = (
    <>
      <div>
        <div className="route-line">
          <span className="from">{from}</span>
          <span className="arrow">→</span>
          <span className="to">{to}</span>
        </div>
        <div className="route-stat">{km} km · 約 {mins} 分鐘</div>
      </div>
      <span className="route-go">在 Google Maps 開啟 ↗</span>
    </>
  );
  if (mapLink) {
    return <a className="route-card" href={mapLink} target="_blank" rel="noreferrer" onClick={e => e.stopPropagation()}>{inner}</a>;
  }
  return <div className="route-card">{inner}</div>;
}

// === Image Frame (single) ===
function ImageFrame({ src, alt, placeholder, onClick }) {
  const [errored, setErrored] = useState(false);
  if (!src || errored) {
    return (
      <div className="img-frame">
        <div className="placeholder">[ {placeholder || alt || "請提供照片"} ]</div>
      </div>
    );
  }
  return (
    <div className={"img-frame" + (onClick ? " is-clickable" : "")} onClick={onClick}>
      <img src={src} alt={alt} loading="lazy" referrerPolicy="no-referrer"
           onError={() => setErrored(true)} />
    </div>
  );
}

// === Image Gallery (1+ images) ===
// 用法：<ImageGallery images={[url1, url2]} alt="..." />  或  <ImageGallery src="..." />
function ImageGallery({ src, images, alt, placeholder }) {
  const list = useMemo(() => {
    if (Array.isArray(images) && images.length > 0) return images.filter(Boolean);
    if (src) return [src];
    return [];
  }, [images, src]);

  const [active, setActive] = useState(0);
  const [lightbox, setLightbox] = useState(-1);
  // 圖片數變動時重置
  useEffect(() => { setActive(0); }, [list.join("|")]);

  // Lightbox 鍵盤
  useEffect(() => {
    if (lightbox < 0) return;
    const onKey = (e) => {
      if (e.key === "Escape") setLightbox(-1);
      else if (e.key === "ArrowRight") setLightbox(i => (i + 1) % list.length);
      else if (e.key === "ArrowLeft") setLightbox(i => (i - 1 + list.length) % list.length);
    };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [lightbox, list.length]);

  if (list.length === 0) {
    return <ImageFrame placeholder={placeholder} alt={alt} />;
  }
  if (list.length === 1) {
    return (
      <>
        <ImageFrame src={list[0]} alt={alt} placeholder={placeholder}
                    onClick={() => setLightbox(0)} />
        {lightbox >= 0 && <Lightbox list={list} index={lightbox} setIndex={setLightbox} alt={alt} />}
      </>
    );
  }

  // 多張：hero + 縮圖列
  const MAX_THUMBS = 4;
  const visible = list.slice(0, MAX_THUMBS);
  const overflow = list.length - MAX_THUMBS;

  return (
    <>
      <div className="gallery" onClick={e => e.stopPropagation()}>
        <ImageFrame src={list[active]} alt={alt} placeholder={placeholder}
                    onClick={() => setLightbox(active)} />
        <div className="gallery-thumbs" role="tablist">
          {visible.map((u, i) => {
            const isLast = i === MAX_THUMBS - 1 && overflow > 0;
            return (
              <button key={i}
                className={"gallery-thumb" + (i === active ? " is-active" : "")}
                onClick={() => isLast ? setLightbox(i) : setActive(i)}
                aria-label={`第 ${i + 1} 張`}>
                <img src={u} alt="" loading="lazy" referrerPolicy="no-referrer"
                     onError={(e) => { e.currentTarget.style.opacity = 0.15; }} />
                {isLast && <span className="gallery-more">+{overflow}</span>}
              </button>
            );
          })}
        </div>
        <div className="gallery-count">
          <span className="gallery-dot-row">
            {list.map((_, i) => (
              <span key={i} className={"gallery-dot" + (i === active ? " is-active" : "")}></span>
            ))}
          </span>
          <span className="gallery-count-text">{active + 1} / {list.length}</span>
        </div>
      </div>
      {lightbox >= 0 && <Lightbox list={list} index={lightbox} setIndex={setLightbox} alt={alt} />}
    </>
  );
}

// === Lightbox ===
function Lightbox({ list, index, setIndex, alt }) {
  const close = (e) => { e?.stopPropagation(); setIndex(-1); };
  const prev = (e) => { e.stopPropagation(); setIndex((index - 1 + list.length) % list.length); };
  const next = (e) => { e.stopPropagation(); setIndex((index + 1) % list.length); };
  // 觸控滑動
  const touch = useRef(null);
  const onTouchStart = (e) => { touch.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    if (touch.current == null) return;
    const dx = e.changedTouches[0].clientX - touch.current;
    if (Math.abs(dx) > 40) {
      if (dx < 0) setIndex((index + 1) % list.length);
      else setIndex((index - 1 + list.length) % list.length);
    }
    touch.current = null;
  };
  // 用 portal 掛到 body：避免卡片的 hover transform 變成 fixed 定位基準，
  // 造成「開燈箱 → hover 解除/觸發 → 閃爍」的循環（transform 會建立 containing block）。
  return ReactDOM.createPortal(
    <div className="lightbox" onClick={close}
         onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
      <button className="lightbox-close" onClick={close} aria-label="關閉">✕</button>
      {list.length > 1 && (
        <>
          <button className="lightbox-nav prev" onClick={prev} aria-label="上一張">‹</button>
          <button className="lightbox-nav next" onClick={next} aria-label="下一張">›</button>
        </>
      )}
      <img className="lightbox-img" src={list[index]} alt={alt}
           referrerPolicy="no-referrer" onClick={e => e.stopPropagation()} />
      {list.length > 1 && (
        <div className="lightbox-count">{index + 1} / {list.length}</div>
      )}
    </div>,
    document.body
  );
}

// 判斷一個 block 是否有「圖片位」(用於編號)
// 規則：排除 transit/flight；hotel 中的「退房」「回到」也跳過
function hasImageSlot(block) {
  if (block.kind === "transit" || block.kind === "flight") return false;
  if (block.kind === "hotel" && /退房|回到/.test(block.title || "")) return false;
  return true;
}

// 為一天計算每個 block 的 ref 編號 (e.g. "3-2")，沒有圖片位的回傳 null
function computeRefs(day) {
  let n = 0;
  return day.blocks.map(b => hasImageSlot(b) ? `${day.id}-${++n}` : null);
}

// 解析卡片最終要顯示的圖片來源
// 優先序：images.js 登記表 TRIP_IMAGES[refNo]（非空）→ data.js 的 images[] → data.js 的 image → 空（佔位框）
function resolveImages(block, refNo) {
  const reg = (refNo && window.TRIP_IMAGES) ? window.TRIP_IMAGES[refNo] : null;
  if (Array.isArray(reg)) {
    const picked = reg.filter(Boolean);
    if (picked.length) return picked;
  }
  if (Array.isArray(block.images) && block.images.length) return block.images.filter(Boolean);
  if (block.image) return [block.image];
  return [];
}

// === Timeline Card ===
function TimelineCard({ block, isActive, onClick, refNo }) {
  const kind = KIND_LABEL[block.kind] || KIND_LABEL.spot;
  const handleAction = (e, url) => {
    e.stopPropagation();
    window.open(url, "_blank", "noreferrer");
  };
  return (
    <div className={`tl-card ${isActive ? "is-active" : ""}`} onClick={onClick}>
      <div className="tl-card-head">
        <span className="tl-kind">{kind.emoji} {kind.label}</span>
        {refNo && <span className="tl-ref" title="圖片編號">#{refNo}</span>}
      </div>
      <h3 className="tl-title">
        {block.title}
        {block.titleJp && <span className="jp">{block.titleJp}</span>}
      </h3>
      {block.note && <p className="tl-note">{block.note}</p>}
      {block.drive && <RouteCard {...block.drive} mapLink={block.mapLink} />}
      {(() => {
        const imgs = resolveImages(block, refNo);
        // 沒有圖也沒有圖片位（退房／回到飯店／交通等）→ 不畫佔位框
        if (!imgs.length && !refNo) return null;
        return <ImageGallery images={imgs} alt={block.title} placeholder={`照片：${block.title}`} />;
      })()}
      <div className="tl-actions">
        {(() => {
          const list = block.links || (block.link ? [block.link] : []);
          return list.map((l, i) => (
            <button key={i} className={"pill" + (i === 0 ? " primary" : "")}
                    onClick={e => handleAction(e, l.url)}>
              🔗 {l.label}
            </button>
          ));
        })()}
        {block.mapLink && !block.drive && (
          <button className="pill" onClick={e => handleAction(e, block.mapLink)}>
            🗺️ Google Maps
          </button>
        )}
      </div>
    </div>
  );
}

// === Day Timeline ===
function DayTimeline({ day, activeBlockIdx, onSelectBlock, nowBlockIdx }) {
  const refs = useMemo(() => computeRefs(day), [day]);
  return (
    <>
      <div className="day-header">
        <div>
          <h2>
            {day.title}
            {day.titleJp && <span className="jp">{day.titleJp}</span>}
          </h2>
          <div className="stat">
            <span>📅 {day.date.slice(5).replace("-", "/")} ({day.weekday})</span>
            {day.driveKm > 0 && <span>🚗 共開車 {day.driveKm} km</span>}
          </div>
        </div>
        <p className="summary">{day.summary}</p>
      </div>
      <ul className="timeline">
        {day.blocks.map((b, i) => (
          <li key={i} className={`tl-item ${i === nowBlockIdx ? "is-now" : ""} ${nowBlockIdx >= 0 && i < nowBlockIdx ? "is-past" : ""}`}>
            <div className="tl-time">{b.time}</div>
            <div className="tl-dot" data-kind={b.kind}></div>
            <div style={{minWidth:0}}>
              {i === nowBlockIdx && <span className="now-pill">⏱ 現在</span>}
              <TimelineCard
                block={b}
                refNo={refs[i]}
                isActive={activeBlockIdx === i}
                onClick={() => onSelectBlock(i)}
              />
            </div>
          </li>
        ))}
      </ul>
    </>
  );
}

// === Detail Panel (right column on wide screens) ===
function DetailPanel({ block, refNo }) {
  if (!block) {
    return (
      <div className="detail-panel">
        <h3>選一個行程看細節</h3>
        <p className="empty">點擊左側時間軸的任一卡片，這裡會顯示更多介紹、圖片、官方連結與 Google Maps。</p>
      </div>
    );
  }
  const kind = KIND_LABEL[block.kind] || KIND_LABEL.spot;
  return (
    <div className="detail-panel">
      <div style={{display:"flex", alignItems:"center", gap:"0.5rem", marginBottom:"0.4rem"}}>
        <span className="tl-kind">{kind.emoji} {kind.label}</span>
        <span style={{fontFamily:"var(--font-mono)", fontSize:"0.85rem", color:"var(--fg-muted)"}}>{block.time}</span>
        {refNo && <span className="tl-ref" style={{marginLeft:"auto"}} title="圖片編號">#{refNo}</span>}
      </div>
      <h3>{block.title}</h3>
      {block.titleJp && <div className="jp">{block.titleJp}</div>}
      {(() => {
        const imgs = resolveImages(block, refNo);
        if (!imgs.length && !refNo) return null;
        return <div style={{marginTop:"0.85rem"}}><ImageGallery images={imgs} alt={block.title} placeholder={`照片：${block.title}`} /></div>;
      })()}
      {block.note && <p style={{fontSize:"0.95rem", color:"var(--fg-soft)", lineHeight:1.7, marginTop:"0.85rem"}}>{block.note}</p>}
      {block.drive && <RouteCard {...block.drive} mapLink={block.mapLink} />}
      <div className="tl-actions" style={{marginTop:"1rem"}}>
        {(block.links || (block.link ? [block.link] : [])).map((l, i) => (
          <a key={i} className={"pill" + (i === 0 ? " primary" : "")}
             href={l.url} target="_blank" rel="noreferrer">
            🔗 {l.label}
          </a>
        ))}
        {block.mapLink && (
          <a className="pill" href={block.mapLink} target="_blank" rel="noreferrer">
            🗺️ Google Maps
          </a>
        )}
      </div>
    </div>
  );
}

window.TripUI = { TimelineCard, DayTimeline, DetailPanel, RouteCard, ImageFrame, ImageGallery, Lightbox, getTodayDayId, getCurrentBlockIdx, KIND_LABEL, formatDate, computeRefs, hasImageSlot, resolveImages };
