/* ============================================================
   pandanow.jsx — トップの「パンダNOW！」
   いまパンダが何してるかを、曜日×時間帯のスケジュールで自動切替。
   短いループアニメ（gif風）＋「〇〇してる」の現状テキストだけ。
   window.PixelPanda を利用。window.PandaNow を公開。
   ============================================================ */

/* ポップなロゴ「パンダNOW！」（1文字ずつ色・回転） */
const PN_LOGO = [
  { c: "パ", col: "#ff6b6b", rot: -7 },
  { c: "ン", col: "#ffd24a", rot: 5 },
  { c: "ダ", col: "#4cc3d9", rot: -4 },
  { c: "N",  col: "#7ee0a0", rot: 6 },
  { c: "O",  col: "#ff8fb1", rot: -5 },
  { c: "W",  col: "#ffb14a", rot: 4 },
  { c: "！", col: "#ff6b6b", rot: -3 },
];
function PNPopLogo() {
  return (
    <span className="pn-pop-logo">
      {PN_LOGO.map((g, i) => (
        <span key={i} className="pn-pop-ch" style={{ color: g.col, "--r": g.rot + "deg" }}>{g.c}</span>
      ))}
    </span>
  );
}

/* ドットの電源マーク（ポップ） */
const POWER_ROWS = [
  "....k....",
  "..k.k.k..",
  ".k..k..k.",
  ".k..k..k.",
  ".k.....k.",
  ".k.....k.",
  "..k...k..",
  "...kkk...",
];
const PN_ACT = {
  sleep:    { label: "寝てる" },
  asagohan: { label: "子どもと朝ごはん" },
  claude:   { label: "Claudeと戯れてる" },
  hirumeshi:{ label: "ごはん食べてる" },
  super:    { label: "スーパーで買い物" },
  yugohan:  { label: "子どもと夕ごはん" },
  slot:     { label: "スロット打ってる" },
  nomi:     { label: "飲みに行ってる" },
};

/* --- 曜日×時間で「いまの活動」を決める --- */
function pnActivityFor(d) {
  const day = d.getDay();       // 0=日 .. 6=土
  const h = d.getHours();
  const weekend = (day === 0 || day === 6);

  if (h < 6 || h >= 23) return "sleep";
  if (h < 8) return "asagohan";

  if (weekend) {
    if (h < 11) return "super";
    if (h < 13) return "hirumeshi";
    if (h < 17) return "slot";
    if (h < 19) return "yugohan";
    return "nomi";              // 19–23
  } else {
    if (h < 12) return "claude";
    if (h < 13) return "hirumeshi";
    if (h < 17) return "claude";
    if (h < 18) return "super";
    if (h < 20) return "yugohan";
    if (day === 5) return "nomi";   // 金曜の夜は飲み
    return "claude";                // 平日の夜は戯れ
  }
}

/* --- パンダ本体（スケール付き） --- */
function PNPanda({ pose = "stand", scale = 0.62 }) {
  const C = window.PixelPanda;
  return (
    <div className="pn-panda" style={{ transform: `translateX(-11px) scale(${scale})` }}>
      {C ? <C pose={pose} /> : null}
    </div>
  );
}

/* --- 各シーン（短いループ） --- */
function PNScene({ act }) {
  switch (act) {
    case "sleep":
      return (
        <div className="pn-scene sc-sleep">
          <div className="pn-bed"></div>
          <div className="pn-stage breathe"><PNPanda pose="sleep" /></div>
          <span className="pn-z z1">Z</span>
          <span className="pn-z z2">z</span>
          <span className="pn-z z3">z</span>
        </div>
      );
    case "asagohan":
    case "yugohan":
      return (
        <div className="pn-scene sc-meal2">
          <div className="pn-table"></div>
          <div className="pn-stage bob"><PNPanda pose="stand" scale={0.6} /></div>
          <div className="pn-stage pn-child bob2"><PNPanda pose="stand" scale={0.4} /></div>
          <div className="pn-plate p-l"></div>
          <div className="pn-plate p-r"></div>
        </div>
      );
    case "claude":
      return (
        <div className="pn-scene sc-claude">
          <div className="pn-stage bob"><PNPanda pose="stand" /></div>
          <div className="pn-laptop">
            <div className="pn-laptop-screen"><span className="pn-cursor2"></span></div>
            <div className="pn-laptop-base"></div>
          </div>
        </div>
      );
    case "hirumeshi":
      return (
        <div className="pn-scene sc-meshi">
          <div className="pn-stage bob"><PNPanda pose="stand" /></div>
          <div className="pn-bowl"></div>
          <div className="pn-chopsticks"></div>
        </div>
      );
    case "super":
      return (
        <div className="pn-scene sc-super">
          <div className="pn-walk">
            <div className="pn-stage step"><PNPanda pose="stand" /></div>
            <div className="pn-cart">
              <div className="pn-cart-basket"></div>
              <div className="pn-cart-wheel w1"></div>
              <div className="pn-cart-wheel w2"></div>
            </div>
          </div>
        </div>
      );
    case "slot":
      return (
        <div className="pn-scene sc-slot">
          <div className="pn-stage bob"><PNPanda pose="stand" scale={0.56} /></div>
          <div className="pn-slot">
            <div className="pn-reels">
              <div className="pn-reel"><div className="pn-reel-strip s1">7▲●7◆7</div></div>
              <div className="pn-reel"><div className="pn-reel-strip s2">●7◆7▲●</div></div>
              <div className="pn-reel"><div className="pn-reel-strip s3">◆7●7▲7</div></div>
            </div>
            <div className="pn-lever"><span className="pn-lever-knob"></span></div>
          </div>
        </div>
      );
    case "nomi":
      return (
        <div className="pn-scene sc-nomi">
          <div className="pn-stage tip"><PNPanda pose="stand" /></div>
          <div className="pn-mug tipmug">
            <span className="pn-mug-foam"></span>
            <span className="pn-mug-handle"></span>
          </div>
        </div>
      );
    default:
      return <div className="pn-scene"><div className="pn-stage bob"><PNPanda pose="stand" /></div></div>;
  }
}

/* --- 本体 --- */
function PandaNow() {
  const ACTS = Object.keys(PN_ACT); // スケジュール順
  const [now, setNow] = React.useState(() => new Date());
  const [on, setOn] = React.useState(false);     // テレビON/OFF
  const [idx, setIdx] = React.useState(0);        // いま表示中の活動
  const [turning, setTurning] = React.useState(false);
  const [live, setLive] = React.useState(false);  // 本物のパンダ チャンネル

  const PN_LIVE_ID = "V7MUP69nLqA"; // iPanda 24/7 ライブ（差し替え可）

  const toLive = () => { setLive(true); setTurning(true); setTimeout(() => setTurning(false), 650); };
  const toDots = () => { setLive(false); setTurning(true); setTimeout(() => setTurning(false), 650); };

  React.useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 30000);
    return () => clearInterval(id);
  }, []);

  const schedAct = pnActivityFor(now);

  const powerOn = () => {
    setIdx(ACTS.indexOf(schedAct));
    setTurning(true);
    setOn(true);
    setTimeout(() => setTurning(false), 650);
  };
  const powerOff = () => { setOn(false); setLive(false); };
  const go = (d) => setIdx((i) => (i + d + ACTS.length) % ACTS.length);

  const act = ACTS[idx];
  const label = PN_ACT[act].label;
  const isNow = act === schedAct;
  const hh = String(now.getHours()).padStart(2, "0");
  const mm = String(now.getMinutes()).padStart(2, "0");

  return (
    <div style={{ padding: "32px 16px 0" }}>
      <div className="sec-label dot" style={{ justifyContent: "center", marginBottom: 16, width: "100%" }}>PANDA NOW！</div>

      <div className={"pn-tv hardshadow pixbox" + (on ? " is-on" : "")}>
        <div className="pn-tv-frame">
          {!on ? (
            <button className="pn-power-btn" onClick={powerOn}>
              <span className="pn-tv-glass">
                <span className="pn-head pn-head-off">
                  <span className="pn-off-pill dim" aria-hidden="true">OFF</span>
                  <span className="pn-live off"><i></i>LIVE</span>
                  <span className="pn-clock dot">{hh}:{mm}</span>
                </span>
                <span className="pn-screen off">
                  <span className="pn-noise"></span>
                  <span className="pn-off-inner">
                    <PNPopLogo />
                    <span className="pn-power-pix">
                      {window.PixelSprite ? <window.PixelSprite rows={POWER_ROWS} palette={{ k: "#7ee0a0" }} cell={7} /> : null}
                    </span>
                    <span className="pn-power-sub dot">▶ タップして つける</span>
                  </span>
                </span>
              </span>
            </button>
          ) : (
            <div className="pn-tv-glass">
              <div className="pn-head pn-head-on" onClick={powerOff} role="button" tabIndex={0}>
                <span className="pn-off-pill" aria-label="けす">OFF</span>
                <span className="pn-live real"><i></i>LIVE</span>
                <span className="pn-clock dot">{hh}:{mm}</span>
              </div>
              <div className="pn-screen">
                {turning && <span className="pn-crt"></span>}
                <div className="pn-live-embed">
                  <iframe
                    src={`https://www.youtube-nocookie.com/embed/${PN_LIVE_ID}?autoplay=1&mute=1&rel=0&playsinline=1`}
                    title="本物のパンダ" allow="autoplay; encrypted-media; picture-in-picture" allowFullScreen
                  ></iframe>
                </div>
              </div>
            </div>
          )}
        </div>
        <div className="pn-tv-foot"><span className="pn-tv-brand dot">405-TV</span><span className="pn-tv-knob"></span></div>
      </div>
    </div>
  );
}

window.PandaNow = PandaNow;
window.PNScene = PNScene;
window.PN_ACT = PN_ACT;
