// portal-sections.jsx — Nav, Hero, Districts, Zoo, Footer

function Nav() {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className={"nav" + (scrolled ? " scrolled" : "")}>
      <a href="#top" className="logo">
        <img className="mark-img" src="asacho.png" alt="安佐町 ASA-CHO" />
        <span className="ti">
          <span className="ja">安佐町</span>
          <span className="en">ASA-CHO PORTAL</span>
        </span>
      </a>
      <div className="menu">
        {NAV.map(n => n.external
          ? <a key={n.label} href={n.href} target="_blank" rel="noopener noreferrer">{n.label}</a>
          : <a key={n.label} href={n.href}>{n.label}</a>
        )}
      </div>
      <div className="right">
        <div className="lang"><b className="on">JA</b><span>/</span><b>EN</b></div>
        <a className="cta" href="#events">催しを告知</a>
      </div>
    </nav>
  );
}

function HeroSlideshow() {
  const [images, setImages] = React.useState(null); // null=読込中, []=画像なし
  const [idx, setIdx] = React.useState(0);
  const timer = React.useRef(null);
  const INTERVAL = 5500;

  // images/ フォルダの一覧を取得（フォルダの増減に自動対応）
  React.useEffect(() => {
    let alive = true;
    fetch("images_api.php", { credentials: "same-origin" })
      .then(r => r.ok ? r.json() : Promise.reject())
      .then(d => { if (alive) setImages(Array.isArray(d.images) ? d.images : []); })
      .catch(() => { if (alive) setImages([]); });
    return () => { alive = false; };
  }, []);

  const count = images ? images.length : 0;

  // 自動再生
  React.useEffect(() => {
    if (count <= 1) return;
    timer.current = setInterval(() => setIdx(i => (i + 1) % count), INTERVAL);
    return () => clearInterval(timer.current);
  }, [count]);

  const go = (n) => {
    setIdx((n + count) % count);
    if (timer.current) { clearInterval(timer.current); }
    if (count > 1) timer.current = setInterval(() => setIdx(i => (i + 1) % count), INTERVAL);
  };

  // 画像が無い / 読込中は、従来のイラスト背景を表示
  if (!images || count === 0) {
    return <div className="bg"><HeroScape /></div>;
  }

  return (
    <div className="slides">
      {images.map((src, i) => (
        <div key={src}
          className={"slide" + (i === idx ? " on" : "")}
          style={{ backgroundImage: `url("${src}")` }}
          role="img" aria-label={"安佐町の風景 " + (i + 1)} />
      ))}

      {count > 1 && (
        <>
          <button className="sl-arrow prev" onClick={() => go(idx - 1)} aria-label="前の画像">‹</button>
          <button className="sl-arrow next" onClick={() => go(idx + 1)} aria-label="次の画像">›</button>
          <div className="sl-dots">
            {images.map((_, i) => (
              <button key={i} className={i === idx ? "on" : ""} onClick={() => go(i)}
                aria-label={(i + 1) + "枚目へ"} />
            ))}
          </div>
        </>
      )}
    </div>
  );
}

function Hero() {
  return (
    <section className="hero" id="top">
      <HeroSlideshow />
      <div className="vig"></div>

      <div className="seal">
        安<br/>佐<br/>町
        <span className="est">EST. 1955 ─ HIROSHIMA</span>
      </div>

      <div className="wrap inner">
        <div className="kicker"><span className="ln"></span>広島市 安佐北区 ─ HIROSHIMA CITY · ASAKITA-KU</div>
        <h1>ふるさとは、<br/>少し遠く。</h1>
        <p className="sub">広島の北、太田川と十の地区が、川と山と人でつながる町。<br/>季節とともに、ゆっくり生きるための場所があります。</p>

        <div className="dist">
          {DISTRICTS.map((d, i) => (
            <React.Fragment key={d.name}>
              <div className="d">
                <span className="n">{d.name}</span>
                <span className="r">{d.ro}</span>
              </div>
              {i < DISTRICTS.length - 1 && <span className="plus">·</span>}
            </React.Fragment>
          ))}
          <span className="plus">＋ 安佐動物公園</span>
        </div>
      </div>

      <div className="wrap">
        <div className="botbar">
          <div className="scrollcue"><div className="bar"></div>SCROLL ─ お知らせへ</div>
          <span>34°35′N · 132°27′E · 125.1 KM²</span>
        </div>
      </div>
    </section>
  );
}

function DistrictsStrip() {
  return (
    <section className="dstrip" id="districts">
      <div className="wrap">
        <div className="sec-head reveal">
          <div className="l">
            <div className="num" style={{color:"var(--moss-pale)"}}>02 ─ TEN DISTRICTS</div>
            <h2>十の地区<span className="en" style={{color:"rgba(243,238,226,.5)"}}>Ten Districts, One Town</span></h2>
          </div>
          <div className="r">飯室・鈴張・久地・久地南・小河内・毛木・後山・宮野・筒瀬・あさひが丘。それぞれの風土を育んできた十の地区が、太田川と里山に抱かれて連なります。</div>
        </div>
        <div className="drow">
          {DISTRICTS.map(d => (
            <div className="dcell reveal" key={d.name}>
              <div className="idx">{d.idx}</div>
              <div>
                <div className="nm">{d.name}</div>
                <div className="ro">{d.ro}</div>
                <div className="meta">
                  {d.pop && d.pop !== "—" && (
                    <div className="m"><span>人口</span><span className="v">{d.pop}</span></div>
                  )}
                  <div className="m m-feat" style={{borderBottom:0}}><span>特徴</span><span className="v">{d.feat}</span></div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function ZooSlideshow() {
  const [images, setImages] = React.useState(null); // null=読込中, []=画像なし
  const [idx, setIdx] = React.useState(0);
  const timer = React.useRef(null);
  const INTERVAL = 5000;

  // asazoo/ フォルダの一覧を取得（フォルダの増減に自動対応）
  React.useEffect(() => {
    let alive = true;
    fetch("asazoo_api.php", { credentials: "same-origin" })
      .then(r => r.ok ? r.json() : Promise.reject())
      .then(d => { if (alive) setImages(Array.isArray(d.images) ? d.images : []); })
      .catch(() => { if (alive) setImages([]); });
    return () => { alive = false; };
  }, []);

  const count = images ? images.length : 0;

  React.useEffect(() => {
    if (count <= 1) return;
    timer.current = setInterval(() => setIdx(i => (i + 1) % count), INTERVAL);
    return () => clearInterval(timer.current);
  }, [count]);

  const go = (n) => {
    setIdx((n + count) % count);
    if (timer.current) clearInterval(timer.current);
    if (count > 1) timer.current = setInterval(() => setIdx(i => (i + 1) % count), INTERVAL);
  };

  // 画像が無い / 読込中は、従来のプレースホルダ（獸＋足跡）を表示
  if (!images || count === 0) {
    return (
      <>
        <div className="gl">獸</div>
        <svg viewBox="0 0 400 400" style={{position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none",opacity:.16}}>
          {[{x:60,y:90},{x:140,y:330},{x:320,y:150},{x:340,y:300},{x:80,y:230}].map((p,i)=>(
            <g key={i} transform={`translate(${p.x},${p.y}) rotate(${i*40})`} fill="#f3eee2">
              <ellipse cx="0" cy="0" rx="8" ry="11"/>
              <ellipse cx="-10" cy="-12" rx="3" ry="4"/><ellipse cx="10" cy="-12" rx="3" ry="4"/>
              <ellipse cx="-12" cy="-4" rx="3" ry="4"/><ellipse cx="12" cy="-4" rx="3" ry="4"/>
            </g>
          ))}
        </svg>
      </>
    );
  }

  return (
    <div className="zoo-slides">
      {images.map((src, i) => (
        <div key={src}
          className={"zoo-slide" + (i === idx ? " on" : "")}
          style={{ backgroundImage: `url("${src}")` }}
          role="img" aria-label={"安佐動物公園 " + (i + 1)} />
      ))}
      {count > 1 && (
        <>
          <button className="zoo-arrow prev" onClick={() => go(idx - 1)} aria-label="前の画像">‹</button>
          <button className="zoo-arrow next" onClick={() => go(idx + 1)} aria-label="次の画像">›</button>
          <div className="zoo-dots">
            {images.map((_, i) => (
              <button key={i} className={i === idx ? "on" : ""} onClick={() => go(i)}
                aria-label={(i + 1) + "枚目へ"} />
            ))}
          </div>
        </>
      )}
    </div>
  );
}

function ZooSection() {
  return (
    <section className="zoo" id="zoo">
      <div className="pic">
        <div className="lbl">PHOTO ─ 安佐動物公園</div>
        <ZooSlideshow />
      </div>
      <div className="body">
        <div className="k"><span className="ln"></span>03 ─ ICONIC SPOT</div>
        <h3>安佐動物公園<span className="ro">Asa Zoological Park · since 1971</span></h3>
        <p>日浦の丘陵地に広がる、広島市民の動物園。アフリカからやってきたキリンやサイ、希少なツキノワグマまで、約160種・1700頭羽が暮らしています。安佐町の里山に開かれた、季節を映す動物園。</p>
        <div className="st">
          <div className="s"><div className="k2">開園</div><div className="v">1971<small>年</small></div></div>
          <div className="s"><div className="k2">動物</div><div className="v">160<small>種</small></div></div>
          <div className="s"><div className="k2">面積</div><div className="v">25.6<small>ha</small></div></div>
          <div className="s"><div className="k2">入園</div><div className="v">510<small>円</small></div></div>
        </div>
      </div>
    </section>
  );
}

function Footer({ toast }) {
  return (
    <footer id="footer">
      <div className="wrap">
        <div className="ft-top">
          <div className="ft">
            <img className="ft-logo" src="asacho.png" alt="安佐町 ASA-CHO" />
            <div className="brand">安佐町<small>ASA-CHO PORTAL · HIROSHIMA</small></div>
            <p className="lede">広島市安佐北区安佐町。十の地区が、川と山と人で繋がる町。ここに暮らす人と、訪ねる人のためのポータルです。</p>
            <div className="ft-sns">
              <a href="https://x.com/asacho_machiko" target="_blank" rel="noopener noreferrer" title="X (@asacho_machiko)"><IconX/></a>
              <a href="https://www.instagram.com/asa_cho.hiroshima/" target="_blank" rel="noopener noreferrer" title="Instagram"><IconIG/></a>
              <a href="https://www.facebook.com/asachofm" target="_blank" rel="noopener noreferrer" title="Facebook"><IconFB/></a>
              <a href="#" onClick={e=>e.preventDefault()} title="YouTube"><IconYT/></a>
            </div>
          </div>
          <div className="ft">
            <h5>CONTENTS</h5>
            <ul>
              <li><a href="#events">お知らせ・催し</a></li>
              <li><a href="#districts">10地区のご案内</a></li>
              <li><a href="#zoo">安佐動物公園</a></li>
              <li><a href="https://map.asa-cho.com" target="_blank" rel="noopener noreferrer">魅力マップ ↗</a></li>
              <li><a href="#events">移住・暮らし</a></li>
            </ul>
          </div>
          <div className="ft">
            <h5>CONTACT</h5>
            <ul>
              <li>Asaみらい会議</li>
              <li>〒731-1142</li>
              <li>広島市安佐北区安佐町飯室7755（安佐公民館内）</li>
            </ul>
          </div>
          <div className="ft">
            <h5>NEWSLETTER</h5>
            <ul>
              <li>月刊「あさ」配信中</li>
              <li><a href="#events" style={{color:"var(--moss-pale)"}}>→ 購読する</a></li>
            </ul>
          </div>
        </div>
        <div className="ft-btm">
          <span>© 2026 ASA-CHO COMMUNITY COUNCIL</span>
          <span>34°35′N · 132°27′E · ELEV 180–520M</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Nav, Hero, DistrictsStrip, ZooSection, Footer });
