// Date card + 4 timeline layouts + detail overlay
const { useState: useStateTL, useMemo: useMemoTL } = React;

function formatDate(iso) {
  const d = new Date(iso);
  return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
}

function photoUrl(fileId) {
  return fileId ? `/api/photo/${encodeURIComponent(fileId)}` : null;
}

function Photo({ fileId, alt, caption }) {
  const url = photoUrl(fileId);
  if (!url) return <div className="photo-empty">{caption || ""}</div>;
  return <img className="photo-img" src={url} alt={alt || ""} loading="lazy" />;
}

function DateCard({ d, onClick, variant = "default" }) {
  return (
    <article className="date-card" onClick={onClick}>
      <div className="date-img" style={{ background: d.color }}>
        <Photo fileId={d.photos?.[0]} alt={d.title} caption={"photo · " + d.area} />
      </div>
      <div className="date-body">
        <div className="date-meta">
          <span className="date-date">{formatDate(d.date)}</span>
          <span className="date-area">{d.area}</span>
        </div>
        <h3 className="date-title">{d.title}</h3>
        {d.spots?.length > 0 && <p className="date-spots">{d.spots.join(" · ")}</p>}
        {d.memory && <p className="date-memory">{d.memory}</p>}
        {d.song?.title && (
          <div className="date-song">
            <span className="date-song-icon">♪</span>
            <span><b>{d.song.title}</b>{d.song.artist ? ` — ${d.song.artist}` : ""}</span>
          </div>
        )}
      </div>
    </article>
  );
}

function VerticalTimeline({ dates, onPick }) {
  return (
    <div className="tl-vert">
      {dates.map((d, i) => (
        <div className="tl-vert-row" key={d.id}>
          {i % 2 === 0 && <div className="tl-card-wrap"><DateCard d={d} onClick={() => onPick(d)} /></div>}
          <div className="tl-vert-node" />
          {i % 2 === 1 && <div className="tl-card-wrap right"><DateCard d={d} onClick={() => onPick(d)} /></div>}
        </div>
      ))}
    </div>
  );
}

function FilmStrip({ dates, onPick }) {
  return (
    <div className="tl-strip-wrap">
      <div className="tl-strip">
        {dates.map((d) => (
          <DateCard key={d.id} d={d} onClick={() => onPick(d)} />
        ))}
      </div>
    </div>
  );
}

function Scrapbook({ dates, onPick }) {
  const layouts = useMemoTL(() => {
    // Hand-tuned offsets per index for an organic scattered look
    const positions = [
      { left: "3%",  top: "20px",   rot: -4 },
      { left: "35%", top: "60px",   rot: 3 },
      { left: "65%", top: "10px",   rot: -2 },
      { left: "12%", top: "320px",  rot: 5 },
      { left: "42%", top: "380px",  rot: -3 },
      { left: "70%", top: "330px",  rot: 4 },
      { left: "5%",  top: "640px",  rot: 2 },
      { left: "38%", top: "700px",  rot: -5 },
      { left: "68%", top: "660px",  rot: 3 },
      { left: "20%", top: "960px",  rot: -2 },
      { left: "52%", top: "1020px", rot: 4 },
    ];
    return positions;
  }, []);

  const captions = [
    "first ♥", "books & burgs", "sakura day", "rooftop", "gelato faces",
    "artbox night", "BKT nap", "island day", "skyline ♪", "atlas !!!", "ktv kings"
  ];

  return (
    <div className="tl-scrap">
      {dates.map((d, i) => {
        const pos = layouts[i] || { left: "10%", top: 100 + i * 280 + "px", rot: 0 };
        return (
          <div
            key={d.id}
            className="polaroid"
            style={{ left: pos.left, top: pos.top, transform: `rotate(${pos.rot}deg)` }}
            onClick={() => onPick(d)}
          >
            <div className="tape" />
            <div className="polaroid-img" style={{ background: d.color }}>
              <Photo fileId={d.photos?.[0]} alt={d.title} caption={d.area} />
            </div>
            <div className="polaroid-cap">
              <span className="d">{formatDate(d.date)}</span>
              {captions[i] || d.title.toLowerCase()}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function CalendarView({ dates, onPick }) {
  // Group dates by YYYY-MM
  const byMonth = useMemoTL(() => {
    const map = {};
    dates.forEach((d) => {
      const key = d.date.slice(0, 7);
      (map[key] = map[key] || []).push(d);
    });
    return map;
  }, [dates]);

  const monthKeys = Object.keys(byMonth).sort();

  const monthName = (k) => {
    const [y, m] = k.split("-");
    return new Date(+y, +m - 1, 1).toLocaleDateString("en-US", { month: "long", year: "numeric" });
  };

  function renderMonth(key) {
    const [y, m] = key.split("-").map(Number);
    const first = new Date(y, m - 1, 1);
    const startDow = first.getDay();
    const daysInMonth = new Date(y, m, 0).getDate();
    const cells = [];
    for (let i = 0; i < startDow; i++) cells.push(<div className="tl-cal-day empty" key={"e" + i}>·</div>);
    for (let d = 1; d <= daysInMonth; d++) {
      const iso = `${y}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
      const hit = byMonth[key].find((x) => x.date === iso);
      cells.push(
        <div
          key={d}
          className={"tl-cal-day" + (hit ? " has" : "")}
          onClick={hit ? () => onPick(hit) : undefined}
          title={hit ? hit.title : ""}
        >{d}</div>
      );
    }
    return cells;
  }

  return (
    <div className="tl-cal">
      {monthKeys.map((k) => (
        <div className="tl-cal-month" key={k}>
          <h3 className="tl-cal-h">{monthName(k)}</h3>
          <div className="tl-cal-sub">{byMonth[k].length} date{byMonth[k].length > 1 ? "s" : ""}</div>
          <div className="tl-cal-grid">
            {["s","m","t","w","t","f","s"].map((dw, i) => (
              <div key={i} className="tl-cal-dow">{dw}</div>
            ))}
            {renderMonth(k)}
          </div>
        </div>
      ))}
    </div>
  );
}

function DetailOverlay({ date, onClose }) {
  const [activeIdx, setActiveIdx] = useStateTL(0);
  if (!date) return null;
  const photos = date.photos || [];
  const activeFileId = photos[activeIdx];
  return (
    <div className="detail" onClick={onClose}>
      <div className="detail-card" onClick={(e) => e.stopPropagation()} style={{ position: "relative" }}>
        <button className="detail-close" onClick={onClose}>✕</button>
        <div className="detail-gallery">
          <div className="detail-img" style={{ background: date.color }}>
            <Photo fileId={activeFileId} alt={date.title} caption={photos.length ? "" : `${date.area}`} />
          </div>
          {photos.length > 1 && (
            <div className="detail-thumbs">
              {photos.map((fid, i) => (
                <button
                  key={fid + i}
                  className={"detail-thumb" + (i === activeIdx ? " on" : "")}
                  onClick={() => setActiveIdx(i)}
                  style={{ background: date.color }}
                  aria-label={`photo ${i + 1}`}
                >
                  <Photo fileId={fid} alt="" />
                </button>
              ))}
            </div>
          )}
        </div>
        <div className="detail-body">
          <div className="date-meta">
            <span className="date-date">{formatDate(date.date)}</span>
            <span className="date-area">{date.area}</span>
          </div>
          <h2 className="date-title" style={{ fontSize: 34 }}>{date.title}</h2>
          {date.spots?.length > 0 && <p className="date-spots">{date.spots.join(" · ")}</p>}
          {date.memory && <p className="date-memory" style={{ fontSize: 16, lineHeight: 1.6 }}>{date.memory}</p>}
          {date.song?.title && (
            <div className="date-song">
              <span className="date-song-icon">♪</span>
              <span><b>{date.song.title}</b>{date.song.artist ? ` — ${date.song.artist}` : ""}</span>
            </div>
          )}
          <p className="detail-hint">add more photos by sending them to the bot ↓</p>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DateCard, VerticalTimeline, FilmStrip, Scrapbook, CalendarView, DetailOverlay, Photo, formatDate });
