const TC_WEATHER = { snow: ['Snow', '雪'], cloudy: ['Cloudy', 'くもり'], sunny: ['Sunny', '晴れ'], rain: ['Rain', '雨'] };
const TC_STATUS = { open: 'Open', partial: 'Partial', closed: 'Closed' };
const TC_ROAD = { normal: ['Normal', 'normal'], caution: ['Caution', 'caution'], closed: ['Closed', 'closedroad'] };
const TC_WD = ['日', '月', '火', '水', '木', '金', '土'];
const tcTime = iso => { const d = new Date(iso); return String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0'); };
const tcDate = iso => { const d = new Date(iso); return (d.getMonth() + 1) + '.' + d.getDate() + '（' + TC_WD[d.getDay()] + '）'; };
const tcReduced = () => window.matchMedia('(prefers-reduced-motion: reduce)').matches;

function useTcInView(th = 0.25) {
  const ref = React.useRef(null);
  const [on, setOn] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el || !('IntersectionObserver' in window) || tcReduced()) { setOn(true); return; }
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setOn(true); io.disconnect(); } }, { threshold: th });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return [ref, on];
}

function TcCount({ v, go, sign }) {
  const [n, setN] = React.useState(tcReduced() ? v : 0);
  React.useEffect(() => {
    if (!go || tcReduced()) { if (go) setN(v); return; }
    let raf, t0;
    const step = t => { if (!t0) t0 = t; const p = Math.min(1, (t - t0) / 1100); setN(Math.round(v * (1 - Math.pow(1 - p, 3)))); if (p < 1) raf = requestAnimationFrame(step); };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [go, v]);
  return <>{sign && n > 0 ? '+' : ''}{n}</>;
}

function TcPartHead({ n, title, note }) {
  return (
    <div className="tc-ph">
      <span className="tc-l tc-ph__n">{n}</span>
      <span className="tc-l tc-ph__t">{title}</span>
      <span className="tc-ph__r" aria-hidden="true"></span>
      {note ? <span className="tc-l tc-ph__x">{note}</span> : <span></span>}
    </div>
  );
}

function TcCurrent({ c }) {
  const [ref, on] = useTcInView();
  const w = TC_WEATHER[c.weather] || [c.weather, ''];
  const stats = [
    { k: 'New Snow', jp: '新雪（24h）', v: c.snowfall, u: 'CM', sign: true },
    { k: 'Wind', jp: '風速', v: c.wind_speed, u: 'KM/H' },
    { k: 'Snow Base', jp: '積雪（山頂）', v: c.snow_depth, u: 'CM' },
  ];
  return (
    <div ref={ref} className={on ? 'is-in' : ''}>
      <TcPartHead n="01" title="Current Conditions" note={'Updated ' + tcTime(c.updated_at)} />
      <div className="tc-now">
        <div className="tc-f">
          <div className="tc-now__w"><span className="tc-l">Now</span><span className="tc-d">{w[0]}</span><span className="tc-jp">{w[1]}</span></div>
          <div className="tc-now__t tc-d" aria-label={'気温 ' + c.temperature + '度'}><TcCount v={c.temperature} go={on} /><sup>°</sup></div>
        </div>
        <div className="tc-stats">
          {stats.map((s, i) => (
            <div key={s.k} className="tc-stat tc-f" style={{ '--i': i + 1 }}>
              <div className="tc-stat__k"><span className="tc-l">{s.k}</span><span className="tc-jp">{s.jp}</span></div>
              <div className="tc-stat__v tc-d"><TcCount v={s.v} go={on} sign={s.sign} /><small>{s.u}</small></div>
            </div>
          ))}
          <div className="tc-stat tc-f" style={{ '--i': 4 }}>
            <div className="tc-stat__k"><span className="tc-l">Updated</span><span className="tc-jp">更新時刻</span></div>
            <div className="tc-stat__v tc-d">{tcTime(c.updated_at)}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function TcForecast({ days }) {
  const [ref, on] = useTcInView(0.2);
  return (
    <div ref={ref} className={on ? 'is-in' : ''}>
      <TcPartHead n="02" title="5 Day Forecast" note="猪苗代町" />
      <div className="tc-fc" role="list">
        {days.map((d, i) => {
          const w = TC_WEATHER[d.weather] || [d.weather, ''];
          return (
            <div key={d.date} role="listitem" className={'tc-day tc-f' + (i === 0 ? ' tc-day--today' : '')} style={{ '--i': i }}>
              <div className="tc-day__d"><span className="tc-d">{d.label}</span><span className="tc-l tc-jp">{tcDate(d.date)}</span></div>
              <div className="tc-day__w"><span className="tc-l">{w[0]}</span><span className="tc-jp">{w[1]}</span></div>
              <div className="tc-day__t tc-d">{d.temp_low}<sup>°</sup></div>
              <div className="tc-l tc-day__hl">High {d.temp_high}° / Low {d.temp_low}°</div>
              <div className="tc-day__s"><span className="tc-l">Snow</span><b className={d.snowfall ? '' : 'is-zero'}>{d.snowfall ? '+' + d.snowfall : '0'} CM</b></div>
            </div>
          );
        })}
      </div>
      <div className="tc-swipe tc-l"><span>Swipe</span><span aria-hidden="true">→</span></div>
    </div>
  );
}

function TcSnowReport({ resorts, bg }) {
  const [ref, on] = useTcInView(0.15);
  const max = Math.max(...resorts.map(r => r.snow_depth), 1);
  return (
    <div ref={ref} className={'tc-sr' + (on ? ' is-in' : '')}>
      <div className="tc-sr__bg" aria-hidden="true"><img src={bg} alt="" /></div>
      <div className="tc-sr__in">
        <TcPartHead n="03" title="4 Ski Areas / Snow Report" note={'Updated ' + tcTime(resorts[0].updated_at)} />
        <div className="tc-sr__h tc-f">
          <h3 className="tc-d" style={{ margin: 0 }}>Snow<br /><span>Report.</span></h3>
          <div className="tc-legend tc-l">{Object.keys(TC_STATUS).map(k => <span key={k} className={'tc-st tc-st--' + k}><i></i>{TC_STATUS[k]}</span>)}</div>
        </div>
        <div>
          {resorts.map((r, i) => (
            <div key={r.id} className="tc-rs tc-f" style={{ '--i': i }}>
              <span className="tc-l tc-rs__no">{String(i + 1).padStart(2, '0')}</span>
              <div className="tc-rs__nm"><span className="tc-d">{r.resort_en}</span><span className="tc-jp">{r.resort_name}</span></div>
              <div className="tc-rs__mid">
                <div className="tc-bar" style={{ '--p': (r.snow_depth / max * 100) + '%', '--i': i }}><i></i></div>
                <div className="tc-rs__facts tc-l">
                  <span className={'tc-st tc-st--' + r.status}><i></i>{TC_STATUS[r.status]}</span>
                  <span>New<b>+{r.new_snow} CM</b></span>
                  <span>{tcTime(r.updated_at)}</span>
                </div>
              </div>
              <div className="tc-rs__dep tc-d" aria-label={'積雪 ' + r.snow_depth + 'cm'}><TcCount v={r.snow_depth} go={on} /><small>CM</small></div>
            </div>
          ))}
        </div>
        <p className="tc-sr__note tc-jp">積雪量は各スキー場の発表値です。営業状況は当日の天候により変更になる場合があります。</p>
      </div>
    </div>
  );
}

function TcRoad({ road }) {
  const [ref, on] = useTcInView(0.15);
  return (
    <div ref={ref} className={'tc-rd' + (on ? ' is-in' : '')}>
      <TcPartHead n="03" title="Road To Inawashiro" note="Road & Live Camera" />
      <div className="tc-rd__top">
        <div className="tc-f">
          <h3 className="tc-d tc-rd__h" style={{ margin: 0 }}>Road To<span>Inawashiro.</span></h3>
          <p className="tc-jp tc-rd__desc">郡山・会津方面から猪苗代へ。<br />出発前に道路状況をチェック。</p>
        </div>
        <div className="tc-routes">
          {road.routes.map((r, i) => {
            const c = TC_ROAD[r.condition] || [r.condition, 'normal'];
            return (
              <div key={r.id} className="tc-route tc-f" style={{ '--i': i + 1 }}>
                <span className="tc-d tc-route__r">{r.route}</span>
                <span className="tc-jp tc-route__p">{r.from} → {r.to}<span>{r.note}</span></span>
                <div className={'tc-route__c tc-st--' + c[1]}><span className="tc-l">Road Condition</span><span className="tc-d"><i className="tc-st" style={{ display: 'inline-block' }}></i>{c[0]}</span></div>
              </div>
            );
          })}
        </div>
      </div>
      <div className="tc-cams">
        {road.cameras.map((cam, i) => (
          <a key={cam.id} href={cam.url} target="_blank" rel="noopener" className="tc-cam tc-f" style={{ '--i': i }}>
            <div className="tc-cam__img">
              {cam.image ? <img src={cam.image} alt={cam.name + 'のライブカメラ映像'} /> : <div className="tc-cam__ph">LIVE CAMERA — {cam.name}</div>}
              <span className="tc-cam__live tc-l"><i></i>Live</span>
            </div>
            <div className="tc-cam__b">
              <div><span className="tc-l">{cam.area}</span><div className="tc-jp tc-cam__nm">{cam.name}</div></div>
              <span className="tc-l tc-cam__go">Live Camera <span aria-hidden="true">→</span></span>
            </div>
          </a>
        ))}
      </div>
      <p className="tc-rd__note tc-jp">ライブカメラは国土交通省・福島県等の配信ページへ移動します。</p>
    </div>
  );
}

function TcHead({ c, index, on, rf }) {
  return (
    <div ref={rf} className={'tc__head' + (on ? ' is-in' : '')}>
      <div className="tc-f">
        <div className="tc-l tc__meta"><span>{index}</span><i></i><span>Conditions</span></div>
        <h2 className="tc-d tc__h">Today In<span>Inawashiro.</span></h2>
      </div>
      <div className="tc__aside tc-f" style={{ '--i': 2 }}>
        <span className="tc-l tc__sub">Snow &amp; Road Conditions</span>
        <p className="tc-jp tc__copy">今日の雪、天気、道路状況。<br />猪苗代へ向かう前に、現在のコンディションをチェック。</p>
        <div className="tc__upd tc-l"><span>Last Update</span><b>{tcTime(c.updated_at)}</b><span className="tc-jp" style={{ letterSpacing: '.04em' }}>{tcDate(c.updated_at)}</span></div>
      </div>
    </div>
  );
}

// TOPページ用：現在の状況（要約）＋詳細ページへの2導線
const TCT_ICON = {
  weather: <svg viewBox="0 0 32 32"><path d="M9 20a5 5 0 0 1 .6-10A7 7 0 0 1 23 11a4.5 4.5 0 0 1 0 9"/><path d="M16 19v8M12.5 21l7 4M19.5 21l-7 4"/></svg>,
  temp: <svg viewBox="0 0 32 32"><path d="M13 19V6a3 3 0 0 1 6 0v13a5.5 5.5 0 1 1-6 0z"/><path d="M16 12v11"/></svg>,
  snow: <svg viewBox="0 0 32 32"><path d="M16 3v26M4.7 9.5l22.6 13M4.7 22.5l22.6-13M12.5 4.5 16 8l3.5-3.5M12.5 27.5 16 24l3.5 3.5"/></svg>,
  wind: <svg viewBox="0 0 32 32"><path d="M3 12h17a4 4 0 1 0-4-4M3 18h23a3.5 3.5 0 1 1-3.5 3.5M3 24h11"/></svg>,
};
const tctDate = iso => { const d = new Date(iso); return d.getFullYear() + '.' + (d.getMonth() + 1) + '.' + d.getDate() + '（' + TC_WD[d.getDay()] + '）'; };
const tcTopStats = c => {
  const w = TC_WEATHER[c.weather] || [c.weather, ''];
  return [
    { k: 'Weather', icon: 'weather', jp: '現在の天気', v: w[0], word: true },
    { k: 'Current Temp.', icon: 'temp', jp: '現在気温', v: <>{c.temperature}<sup>°</sup></> },
    { k: 'Snowfall Today', icon: 'snow', jp: '本日の降雪予報', v: <>{c.snowfall > 0 ? '+' : ''}{c.snowfall}<small>CM</small></> },
    { k: 'Wind', icon: 'wind', jp: '風速・風向', v: <>{c.wind_speed}<small>KM/H<b>{c.wind_direction}</b></small></> },
  ];
};

function TopConditions({ data = window.CONDITIONS_DATA, index = '02', href = 'conditions.html' }) {
  const [ref, on] = useTcInView(0.15);
  const c = data.current;
  const img = data.top_links || {};
  const links = [
    { n: '01', t: ['Weather', 'Forecast'], jp: '5日間の天気・降雪予報', id: 'forecast', image: img.weather && img.weather.image, ph: 'PHOTO — 降雪のゲレンデ / 雪山' },
    { n: '02', t: ['Road &', 'Live Cam'], jp: '道路状況・ライブカメラ', id: 'road', image: img.road && img.road.image, ph: 'PHOTO — 雪道 / 冬の国道49号', side: true },
  ];
  return (
    <section id="conditions" className="tc tct" data-screen-label="Conditions">
      <div ref={ref} className={'tct__top' + (on ? ' is-in' : '')}>
        <div className="tct__photo" aria-hidden="true">{img.hero && img.hero.image ? <img src={img.hero.image} alt="" /> : null}</div>
        <div className="tct__in">
          <div className="tc-f">
            <div className="tc-l tc__meta"><span>{index}</span><i></i><span>Conditions</span></div>
            <h2 className="tc-d tct__h">Today In<span>Inawashiro.</span></h2>
            <div className="tct__lead"><p className="tc-jp">今日の猪苗代を、ひと目で。</p><span className="tc-l">Snow &amp; Road Conditions</span></div>
            <div className="tc-l tct__upd">Updated <b>{tcTime(c.updated_at)}</b><span>{tctDate(c.updated_at)}</span></div>
          </div>
          <dl className="tct-now">
            {tcTopStats(c).map((s, i) => (
              <div key={s.k} className={'tct-now__i tc-f' + (s.word ? ' is-word' : '')} style={{ '--i': i + 2 }}>
                <span className="tct-now__ic" aria-hidden="true">{TCT_ICON[s.icon]}</span>
                <div className="tct-now__b">
                  <dt className="tc-l">{s.k}</dt>
                  <dd className="tc-d tct-now__v">{s.v}</dd>
                  <dd className="tc-jp tct-now__jp">{s.jp}</dd>
                </div>
              </div>
            ))}
          </dl>
        </div>
      </div>
      <nav className={'tct-go' + (on ? ' is-in' : '')} aria-label="Conditions detail">
        {links.map((l, i) => (
          <a key={l.id} href={href + '#' + l.id} className={'tct-go__a tc-f' + (l.side ? ' is-side' : '')} style={{ '--i': i + 6 }}>
            <span className="tct-go__bg" aria-hidden="true">{l.image ? <img src={l.image} alt="" /> : <span className="tct-go__ph">{l.ph}</span>}</span>
            <span className="tct-go__top"><span className="tc-d">{l.n}</span><i></i></span>
            <span className="tc-d tct-go__t">{l.t[0]}<span>{l.t[1]}</span></span>
            <span className="tc-jp tct-go__jp">{l.jp}</span>
            <span className="tct-go__ar" aria-hidden="true">→</span>
          </a>
        ))}
      </nav>
    </section>
  );
}

// 詳細ページ用：01 / 02 / 03(Road)
function ConditionsPage({ data = window.CONDITIONS_DATA }) {
  const [ref, on] = useTcInView(0.2);
  const c = data.current;
  return (
    <section className="tc tc--page" data-screen-label="Conditions">
      <div className="tc__in">
        <TcHead c={c} index="Today" on={on} rf={ref} />
        <div id="current"><TcCurrent c={c} /></div>
        <div id="forecast"><TcForecast days={data.forecast} /></div>
      </div>
      <div id="road"><TcRoad road={data.road} /></div>
    </section>
  );
}

Object.assign(window, { TopConditions, ConditionsPage });
