BLK-114Blocks

Year-End Business Day Calendar | Add It to Google Calendar

Tap the days you are closed to build a year-end business day calendar for your shop's website.

Preview

年末年始の営業日カレンダー(12/19〜1/11)

日を押すと休み⇄営業が切り替わります

休み 12/29(火)〜1/3(日) 6日間 / 1/4(月)から営業

コードはお店のサイトにそのまま貼れるHTMLです。書き出したファイル(.ics)は、Googleカレンダーの「設定」→「インポート」で読み込めます。

営業時間・定休日・特別営業を設定する

月・火・木・金 11:00〜20:00 / 水 定休 / 土・日 10:00〜19:00

月
火
水
木
金
土
日
祝日の扱い(定休曜日より優先・個別の日の指定が最優先)

オンにすると、上のカレンダーで開始日と終了日を押して、休業・短縮・特別営業を選べます(矢印キー・Home・End・Escでも操作できます)。

見本
Googleマップ用の日別メモ・お知らせ文を見る

通常と異なる日5日

連続休業6日

入力推奨祝日 1日

6日以内特別営業時間に日別で入れる

12/29〜1/3(6日・定休日を含む)

日付と時刻を1日ずつ、日別メモへ

Googleビジネスプロフィール未接続・特別営業時間を未設定と仮定

日別メモ(設定用)

年末年始の設定用メモ(2026-12-19〜2027-01-11)
前提: Google未接続・特別営業時間を未設定と仮定した比較です。Google上の表示は確かめていません。

■ 特別営業時間に日別で入れる
2026-12-29(火) 休業
2026-12-31(木) 休業
2027-01-01(金) 休業
2027-01-02(土) 休業
2027-01-03(日) 休業

■ 入力推奨日(祝日に通常どおり営業)
2027-01-11(月・成人の日) 11:00〜20:00
  • メモ作成済み(自動)

日ごとの比較(上段=今回の予定・下段=通常の営業時間)

12/19(土)

今回10:00〜19:00

通常10:00〜19:00

12/20(日)

今回10:00〜19:00

通常10:00〜19:00

12/21(月)

今回11:00〜20:00

通常11:00〜20:00

12/22(火)

今回11:00〜20:00

通常11:00〜20:00

12/23(水)

今回定休

通常定休

12/24(木)

今回11:00〜20:00

通常11:00〜20:00

12/25(金)

今回11:00〜20:00

通常11:00〜20:00

12/26(土)

今回10:00〜19:00

通常10:00〜19:00

12/27(日)

今回10:00〜19:00

通常10:00〜19:00

12/28(月)

今回11:00〜20:00

通常11:00〜20:00

12/29(火)

今回休業

通常11:00〜20:00

12/30(水)

今回休業

通常定休

12/31(木)

今回休業

通常11:00〜20:00

1/1(金)元日

今回休業

通常11:00〜20:00

1/2(土)

今回休業

通常10:00〜19:00

1/3(日)

今回休業

通常10:00〜19:00

1/4(月)

今回11:00〜20:00

通常11:00〜20:00

1/5(火)

今回11:00〜20:00

通常11:00〜20:00

1/6(水)

今回定休

通常定休

1/7(木)

今回11:00〜20:00

通常11:00〜20:00

1/8(金)

今回11:00〜20:00

通常11:00〜20:00

1/9(土)

今回10:00〜19:00

通常10:00〜19:00

1/10(日)

今回10:00〜19:00

通常10:00〜19:00

1/11(月)成人の日

今回11:00〜20:00入力推奨

通常11:00〜20:00

連続休業ごとの案内とお知らせ文

12月29日(火)〜1月3日(日)6日(定休日を含む)

6日以内のため、特別営業時間に日付ごとに入力する内容(日付と時刻)をメモにまとめました。

お知らせ文(店頭・SNS・Webサイト)

年末年始の営業についてのお知らせ
・12月29日(火)から1月3日(日)まで休業いたします。
1月4日(月)から通常どおり営業いたします。

設定JSON(曜日 0=日)

{
  "period": {
    "start": "2026-12-19",
    "end": "2027-01-11"
  },
  "assumption": "Google未接続・特別営業時間を未設定と仮定",
  "hours": [
    {
      "open": "10:00",
      "close": "19:00"
    },
    {
      "open": "11:00",
      "close": "20:00"
    },
    {
      "open": "11:00",
      "close": "20:00"
    },
    null,
    {
      "open": "11:00",
      "close": "20:00"
    },
    {
      "open": "11:00",
      "close": "20:00"
    },
    {
      "open": "10:00",
      "close": "19:00"
    }
  ],
  "holidayRule": "weekday",
  "overrides": [
    {
      "date": "2026-12-29",
      "status": "closed"
    },
    {
      "date": "2026-12-30",
      "status": "closed"
    },
    {
      "date": "2026-12-31",
      "status": "closed"
    },
    {
      "date": "2027-01-01",
      "status": "closed"
    },
    {
      "date": "2027-01-02",
      "status": "closed"
    },
    {
      "date": "2027-01-03",
      "status": "closed"
    }
  ],
  "closures": [
    {
      "start": "2026-12-29",
      "end": "2027-01-03",
      "days": 6,
      "resumeDate": "2027-01-04",
      "guidance": "special-hours"
    }
  ],
  "resumeDate": "2027-01-04"
}

Share on X

Read the full description

Tap the days you are closed to build a year-end business day calendar for your shop's website.

Added:
2026-11-11
Updated:
2026-11-17
Dependencies:
None
tags
#calendar #business-hours #holiday #date-range #date-picker #year-end #google-business-profile #toggle #html-snippet #ics #google-calendar #special-hours #small-business #restaurant #salon #notice #json-export #copy #roving-tabindex #aria-live #a11y #keyboard #hairline #no-image
"use client";

import {
  useEffect,
  useId,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  useSyncExternalStore,
  type KeyboardEvent as ReactKeyboardEvent,
} from "react";

/**
 * 年末年始の営業日カレンダー(BLK-114)|Googleにも入れられる
 *
 * 最初に見せる操作は1つだけ: 日を押すと「休み」⇄「営業」が切り替わる(既定で 12/29〜1/3 を休みにしておく)。
 * そのすぐ下に「コードをコピー」(お店のサイトに貼るHTML)と「Googleカレンダー用に書き出す」(.ics)を置き、
 * 営業時間・定休日・祝日の扱い・期間での短縮/特別営業は「設定する」に、Googleマップ用の日別メモ・お知らせ文・
 * 設定JSONは「見る」に畳む。差別化: 空き枠カレンダー(calendar-slot-cta)は来訪者が空きを選ぶ予約CTA、本ブロックは店主側の道具。
 *
 * 汎用技法メモ:
 * 1. **日付は UTC の Date で足し引きする**(Date.UTC(y, m, d))。端末のタイムゾーンや夏時間で1日ずれない。
 *    「今日」だけは Intl.DateTimeFormat の timeZone: "Asia/Tokyo" で取り、マウント後に描いて hydration のずれを避ける。
 * 2. **その日の予定は「個別の日 > 祝日の扱い > 定休曜日」の順で1つに決める**(planFor)。押したときの切り替え(toggleDay)は、
 *    指定を外せば望む状態に戻るなら外し、戻らないときだけ「休業」か「特別営業(その曜日の時間)」を足す。指定が増えすぎない。
 * 3. **連続休業は期間の前後7日まで伸ばして数える**(定休日も含める)。特別営業の日があればそこで切れる。
 * 4. .ics の時刻は日本時間を UTC(末尾 Z)に直して書く。VTIMEZONE を持たなくてもカレンダー側でずれない。連続休業は終日の予定。
 * 5. 貼るHTMLは style 属性だけで見た目を作り、貼り先の CSS・JS に頼らない。
 * 6. 日付は roving tabindex(帯全体で Tab 1回・矢印で1日・上下で1週・Home/End)。月曜始まりの7列で週ごとに折り返す。
 * 7. 予定が変わった日だけ useLayoutEffect で Web Animations を当て、マスをアンバー→朱→今の色へ 280ms で塗り替える。
 *    prefers-reduced-motion では動かさない。
 * 8. コピーは押したボタン自体が「コピーしました ✓」になる(文言を同じマスに重ねて幅を固定)。clipboard が使えないときは
 *    隠した textarea を focus({ preventScroll: true }) で選んで execCommand へ代え、スクロール位置を動かさない。
 */

export type DayHours = { open: string; close: string };
export type WeekRow = DayHours & { closed: boolean };
export type Status = "closed" | "short" | "special";
export type Override = DayHours & { status: Status };
export type HolidayRule = "weekday" | "open" | "closed";
export type Guidance = "special-hours" | "check-help" | "temporarily-closed";

export const PERIOD = { start: "2026-12-19", end: "2027-01-11" };
/** 内閣府「国民の祝日」(2026・2027年)。syukujitsu.csv と照合済み */
export const HOLIDAYS: Record<string, string> = {
  "2026-01-01": "元日",
  "2026-01-12": "成人の日",
  "2026-02-11": "建国記念の日",
  "2026-02-23": "天皇誕生日",
  "2026-03-20": "春分の日",
  "2026-04-29": "昭和の日",
  "2026-05-03": "憲法記念日",
  "2026-05-04": "みどりの日",
  "2026-05-05": "こどもの日",
  "2026-05-06": "休日",
  "2026-07-20": "海の日",
  "2026-08-11": "山の日",
  "2026-09-21": "敬老の日",
  "2026-09-22": "休日",
  "2026-09-23": "秋分の日",
  "2026-10-12": "スポーツの日",
  "2026-11-03": "文化の日",
  "2026-11-23": "勤労感謝の日",
  "2027-01-01": "元日",
  "2027-01-11": "成人の日",
  "2027-02-11": "建国記念の日",
  "2027-02-23": "天皇誕生日",
  "2027-03-21": "春分の日",
  "2027-03-22": "休日",
  "2027-04-29": "昭和の日",
  "2027-05-03": "憲法記念日",
  "2027-05-04": "みどりの日",
  "2027-05-05": "こどもの日",
  "2027-07-19": "海の日",
  "2027-08-11": "山の日",
  "2027-09-20": "敬老の日",
  "2027-09-23": "秋分の日",
  "2027-10-11": "スポーツの日",
  "2027-11-03": "文化の日",
  "2027-11-23": "勤労感謝の日",
};
const SRC_HOLIDAY = "https://www8.cao.go.jp/chosei/shukujitsu/gaiyou.html";
const HELP_SPECIAL = "https://support.google.com/business/answer/6303076?hl=ja";
const HELP_CLOSE = "https://support.google.com/business/answer/15300196?hl=ja";
const CHECKED_ON = "2026-11-11";

const DOW = ["日", "月", "火", "水", "木", "金", "土"];
/** 表示は月曜始まり */
const DOW_ORDER = [1, 2, 3, 4, 5, 6, 0];

// ---- 日付 ----
const toDate = (iso: string) => {
  const [y, m, d] = iso.split("-").map(Number);
  return new Date(Date.UTC(y, m - 1, d));
};
const toIso = (dt: Date) => dt.toISOString().slice(0, 10);
export const addDays = (iso: string, n: number) => {
  const dt = toDate(iso);
  dt.setUTCDate(dt.getUTCDate() + n);
  return toIso(dt);
};
export const dowOf = (iso: string) => toDate(iso).getUTCDay();
export function datesBetween(a: string, b: string): string[] {
  const out: string[] = [];
  for (let d = a; d <= b; d = addDays(d, 1)) out.push(d);
  return out;
}
const md = (iso: string) =>
  `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}`;
const jp = (iso: string) =>
  `${Number(iso.slice(5, 7))}月${Number(iso.slice(8, 10))}日(${DOW[dowOf(iso)]})`;
const isoW = (iso: string) => `${iso}(${DOW[dowOf(iso)]})`;
const range = (h: DayHours) => `${h.open}〜${h.close}`;

export const TIMES: string[] = Array.from({ length: 97 }, (_, i) => {
  const m = i * 15;
  return `${String(Math.floor(m / 60)).padStart(2, "0")}:${String(m % 60).padStart(2, "0")}`;
});

export const DEFAULT_WEEK: WeekRow[] = [
  { closed: false, open: "10:00", close: "19:00" },
  { closed: false, open: "11:00", close: "20:00" },
  { closed: false, open: "11:00", close: "20:00" },
  { closed: true, open: "11:00", close: "20:00" },
  { closed: false, open: "11:00", close: "20:00" },
  { closed: false, open: "11:00", close: "20:00" },
  { closed: false, open: "10:00", close: "19:00" },
];

const SHORT_1227: Record<string, Override> = {
  "2026-12-27": { status: "short", open: "10:00", close: "16:00" },
};
const closedRange = (a: string, b: string): Record<string, Override> =>
  Object.fromEntries(
    datesBetween(a, b).map((d) => [
      d,
      { status: "closed", open: "", close: "" } as Override,
    ]),
  );

export const PRESETS: {
  key: string;
  label: string;
  note: string;
  overrides: Record<string, Override>;
}[] = [
  {
    key: "6",
    label: "6日",
    note: "12/31〜1/4を休み(前日12/30は定休の水曜)",
    overrides: { ...SHORT_1227, ...closedRange("2026-12-31", "2027-01-04") },
  },
  {
    key: "7",
    label: "7日",
    note: "12/29〜1/4を休み(途中の12/30は定休の水曜)",
    overrides: { ...SHORT_1227, ...closedRange("2026-12-29", "2027-01-04") },
  },
  {
    key: "8",
    label: "8日",
    note: "12/28〜1/4を休み",
    overrides: { ...SHORT_1227, ...closedRange("2026-12-28", "2027-01-04") },
  },
  {
    key: "0102",
    label: "1/2だけ特別営業",
    note: "12/28〜1/4の休みのうち、1/2だけ10:00〜15:00で開ける",
    overrides: {
      ...SHORT_1227,
      ...closedRange("2026-12-28", "2027-01-04"),
      "2027-01-02": { status: "special", open: "10:00", close: "15:00" },
    },
  },
];

const VERM = "#b7281a";
const focusRing =
  "outline-none focus-visible:ring-2 focus-visible:ring-[#d97706] focus-visible:ring-offset-2";

// ---- 判定 ----
export type DayPlan = {
  date: string;
  dow: number;
  holiday: string | null;
  plan: DayHours | null;
  normal: DayHours | null;
  status: Status | null;
  source: "override" | "holiday" | "weekday";
  mismatch: boolean;
  recommend: boolean;
};

const sameHours = (a: DayHours | null, b: DayHours | null) =>
  a === null || b === null ? a === b : a.open === b.open && a.close === b.close;

/** 個別の日 > 祝日の扱い > 定休曜日 の順でその日の予定を決め、通常の営業時間(曜日だけ)と比べる */
export function planFor(
  date: string,
  week: WeekRow[],
  rule: HolidayRule,
  overrides: Record<string, Override>,
): DayPlan {
  const dow = dowOf(date);
  const w = week[dow];
  const holiday = HOLIDAYS[date] ?? null;
  const normal = w.closed ? null : { open: w.open, close: w.close };
  let plan: DayHours | null;
  let status: Status | null = null;
  let source: DayPlan["source"] = "weekday";
  const ov = overrides[date];
  if (ov) {
    source = "override";
    status = ov.status;
    plan = ov.status === "closed" ? null : { open: ov.open, close: ov.close };
  } else if (holiday && rule !== "weekday") {
    source = "holiday";
    plan = rule === "closed" ? null : { open: w.open, close: w.close };
  } else plan = normal;
  const mismatch = !sameHours(plan, normal);
  return {
    date,
    dow,
    holiday,
    plan,
    normal,
    status,
    source,
    mismatch,
    recommend: Boolean(holiday) && plan !== null && !mismatch,
  };
}

export function guidanceFor(days: number): Guidance {
  if (days <= 6) return "special-hours";
  if (days === 7) return "check-help";
  return "temporarily-closed";
}

export type Run = {
  start: string;
  end: string;
  days: number;
  resumeDate: string;
  guidance: Guidance;
};

/** 定休日も含めた連続休業。期間の前後7日まで伸ばして数え、通常なら営業する日を含む塊だけを返す */
export function closureRuns(
  week: WeekRow[],
  rule: HolidayRule,
  overrides: Record<string, Override>,
  period = PERIOD,
): Run[] {
  const days = datesBetween(
    addDays(period.start, -7),
    addDays(period.end, 7),
  ).map((d) => planFor(d, week, rule, overrides));
  const runs: Run[] = [];
  let i = 0;
  while (i < days.length) {
    if (days[i].plan !== null) {
      i++;
      continue;
    }
    let j = i;
    while (j + 1 < days.length && days[j + 1].plan === null) j++;
    const block = days.slice(i, j + 1);
    const counts = block.some(
      (d) => d.mismatch && d.date >= period.start && d.date <= period.end,
    );
    if (counts) {
      const n = block.length;
      runs.push({
        start: block[0].date,
        end: block[n - 1].date,
        days: n,
        resumeDate: addDays(block[n - 1].date, 1),
        guidance: guidanceFor(n),
      });
    }
    i = j + 1;
  }
  return runs;
}

export type Result = {
  days: DayPlan[];
  runs: Run[];
  mismatch: DayPlan[];
  recommend: DayPlan[];
  longest: Run | null;
};

export function evaluate(
  week: WeekRow[],
  rule: HolidayRule,
  overrides: Record<string, Override>,
): Result {
  const days = datesBetween(PERIOD.start, PERIOD.end).map((d) =>
    planFor(d, week, rule, overrides),
  );
  const runs = closureRuns(week, rule, overrides);
  const longest = runs.reduce<Run | null>(
    (a, r) => (a === null || r.days > a.days ? r : a),
    null,
  );
  return {
    days,
    runs,
    mismatch: days.filter((d) => d.mismatch),
    recommend: days.filter((d) => d.recommend),
    longest,
  };
}

const runOf = (runs: Run[], date: string) =>
  runs.find((r) => date >= r.start && date <= r.end) ?? null;

const planLabel = (d: DayPlan) => {
  if (d.plan === null) return d.source === "weekday" ? "定休" : "休業";
  const t = range(d.plan);
  if (d.status === "short") return `短縮 ${t}`;
  if (d.status === "special") return `特別 ${t}`;
  return t;
};
const normalLabel = (d: DayPlan) => (d.normal ? range(d.normal) : "定休");
const memoLine = (d: DayPlan) =>
  `${isoW(d.date)} ${d.plan ? `${range(d.plan)}${d.status === "short" ? "(短縮)" : d.status === "special" ? "(特別営業)" : ""}` : "休業"}`;

export const GUIDE_LABEL: Record<Guidance, string> = {
  "special-hours": "特別営業時間に日別で入れる",
  "check-help": "公式ヘルプ間で案内が異なるため要確認",
  "temporarily-closed": "臨時休業マークの案内",
};

/** 日別メモ(スタッフ・Web担当へ渡す本文) */
export function buildMemo(r: Result): string {
  const daily: string[] = [];
  const check: Run[] = [];
  const temp: Run[] = [];
  for (const run of r.runs) {
    if (run.guidance === "check-help") check.push(run);
    if (run.guidance === "temporarily-closed") temp.push(run);
  }
  for (const d of r.mismatch) {
    const run = runOf(r.runs, d.date);
    if (!run || run.guidance === "special-hours") daily.push(memoLine(d));
  }
  const out = [
    `年末年始の設定用メモ(${PERIOD.start}〜${PERIOD.end})`,
    "前提: Google未接続・特別営業時間を未設定と仮定した比較です。Google上の表示は確かめていません。",
  ];
  if (daily.length) out.push("", "■ 特別営業時間に日別で入れる", ...daily);
  for (const run of temp)
    out.push(
      "",
      `■ 臨時休業マーク(連続${run.days}日)`,
      `${isoW(run.start)}〜${isoW(run.end)} / 再開日 ${isoW(run.resumeDate)}`,
    );
  for (const run of check) {
    out.push(
      "",
      `■ 要確認(連続ちょうど7日・公式ヘルプ間で案内が異なる)`,
      `${isoW(run.start)}〜${isoW(run.end)} / 再開日 ${isoW(run.resumeDate)}`,
      "日別で入れる場合:",
      ...r.mismatch
        .filter((d) => d.date >= run.start && d.date <= run.end)
        .map(memoLine),
      `確認先: ${HELP_SPECIAL} / ${HELP_CLOSE}(確認日 ${CHECKED_ON})`,
    );
  }
  if (r.recommend.length)
    out.push(
      "",
      "■ 入力推奨日(祝日に通常どおり営業)",
      ...r.recommend.map(
        (d) =>
          `${d.date}(${DOW[d.dow]}・${d.holiday}) ${d.plan ? range(d.plan) : ""}`,
      ),
    );
  if (!daily.length && !temp.length && !check.length && !r.recommend.length)
    out.push("", "通常の営業時間と異なる日はありません。");
  return out.join("\n");
}

/** 来店客向けのお知らせ文 */
export function buildNotice(r: Result): string {
  const items: { at: string; text: string }[] = [];
  for (const run of r.runs)
    items.push({
      at: run.start,
      text:
        run.days === 1
          ? `${jp(run.start)}は休業いたします。`
          : `${jp(run.start)}から${jp(run.end)}まで休業いたします。`,
    });
  for (const d of r.mismatch) {
    if (d.plan === null || runOf(r.runs, d.date)) continue;
    items.push({
      at: d.date,
      text:
        d.status === "short"
          ? `${jp(d.date)}は${range(d.plan)}の短縮営業です。`
          : `${jp(d.date)}は${range(d.plan)}で営業いたします。`,
    });
  }
  items.sort((a, b) => (a.at < b.at ? -1 : 1));
  if (!items.length) return "年末年始も通常どおり営業いたします。";
  const out = [
    "年末年始の営業についてのお知らせ",
    ...items.map((i) => `・${i.text}`),
  ];
  const last = r.runs[r.runs.length - 1];
  if (last) {
    const next = r.days.find((d) => d.date === last.resumeDate);
    out.push(
      next && next.mismatch
        ? `${jp(last.resumeDate)}から営業を再開いたします。`
        : `${jp(last.resumeDate)}から通常どおり営業いたします。`,
    );
  }
  return out.join("\n");
}

/** 設定JSON(曜日 0=日) */
export function buildJson(
  week: WeekRow[],
  rule: HolidayRule,
  overrides: Record<string, Override>,
  r: Result,
): string {
  return JSON.stringify(
    {
      period: PERIOD,
      assumption: "Google未接続・特別営業時間を未設定と仮定",
      hours: week.map((w) =>
        w.closed ? null : { open: w.open, close: w.close },
      ),
      holidayRule: rule,
      overrides: Object.keys(overrides)
        .sort()
        .map((date) => {
          const o = overrides[date];
          return o.status === "closed"
            ? { date, status: o.status }
            : { date, status: o.status, open: o.open, close: o.close };
        }),
      closures: r.runs,
      resumeDate: r.longest?.resumeDate ?? null,
    },
    null,
    2,
  );
}

/** 通常と異なる日の短い一覧。連続休業は「12/28〜1/4 休業」の1項目にまとめる */
export function mismatchItems(r: Result): string[] {
  const items: { at: string; text: string }[] = r.runs.map((run) => ({
    at: run.start,
    text:
      run.days === 1
        ? `${md(run.start)} 休業`
        : `${md(run.start)}〜${md(run.end)} 休業`,
  }));
  for (const d of r.mismatch)
    if (!runOf(r.runs, d.date))
      items.push({ at: d.date, text: `${md(d.date)} ${planLabel(d)}` });
  return items.sort((a, b) => (a.at < b.at ? -1 : 1)).map((i) => i.text);
}

/** 比較帯(共有用の要約) */
export function buildBand(r: Result): string {
  const lines = [
    `設定用メモ(通常と異なる日 ${r.mismatch.length}日)`,
    `通常の営業時間と異なる日 ${r.mismatch.length}日${r.mismatch.length ? `(${mismatchItems(r).join("、")})` : ""}`,
    `入力推奨祝日 ${r.recommend.length}日${r.recommend.length ? `(${r.recommend.map((d) => `${md(d.date)} ${d.holiday}`).join("、")})` : ""}`,
  ];
  for (const run of r.runs)
    lines.push(
      `連続休業 ${md(run.start)}〜${md(run.end)} ${run.days}日:${GUIDE_LABEL[run.guidance]}${run.guidance === "special-hours" ? "" : `(再開日 ${md(run.resumeDate)})`}`,
    );
  lines.push(
    "※Google未接続・特別営業時間を未設定と仮定した比較です。Google上の表示ではありません。",
  );
  return lines.join("\n");
}

export function summarizeWeek(week: WeekRow[]): string {
  const groups: { key: string; days: number[] }[] = [];
  for (const d of DOW_ORDER) {
    const w = week[d];
    const key = w.closed ? "定休" : range(w);
    const g = groups.find((x) => x.key === key);
    if (g) g.days.push(d);
    else groups.push({ key, days: [d] });
  }
  return groups
    .map((g) => `${g.days.map((d) => DOW[d]).join("・")} ${g.key}`)
    .join(" / ");
}

const sameOverrides = (
  a: Record<string, Override>,
  b: Record<string, Override>,
) => {
  const ka = Object.keys(a).sort();
  const kb = Object.keys(b).sort();
  return (
    ka.length === kb.length &&
    ka.every(
      (k, i) =>
        k === kb[i] &&
        a[k].status === b[k].status &&
        (a[k].status === "closed" ||
          (a[k].open === b[k].open && a[k].close === b[k].close)),
    )
  );
};

const addMinutes = (t: string, m: number) => {
  const [h, mm] = t.split(":").map(Number);
  const v = Math.min(24 * 60, Math.max(0, h * 60 + mm + m));
  return `${String(Math.floor(v / 60)).padStart(2, "0")}:${String(v % 60).padStart(2, "0")}`;
};

/** 最初に塗っておく休み(12/29〜1/3) */
export const DEFAULT_OVERRIDES: Record<string, Override> = closedRange(
  "2026-12-29",
  "2027-01-03",
);

/** 日を押したときの切り替え。休み → 営業、営業 → 休み。曜日・祝日の扱いで決まる状態に戻せるときは指定を外す */
export function toggleDay(
  date: string,
  week: WeekRow[],
  rule: HolidayRule,
  overrides: Record<string, Override>,
): Record<string, Override> {
  const n = { ...overrides };
  delete n[date];
  const cur = planFor(date, week, rule, overrides).plan;
  const base = planFor(date, week, rule, n).plan;
  if (cur === null) {
    if (base !== null) return n;
    const w = week[dowOf(date)];
    n[date] = { status: "special", open: w.open, close: w.close };
    return n;
  }
  if (base === null) return n;
  n[date] = { status: "closed", open: "", close: "" };
  return n;
}

/** 見本の下の1行の要約(例「休み 12/29(火)〜1/3(日) 6日間 / 1/4(月)から営業」) */
export function summaryLine(r: Result): string {
  if (!r.runs.length && !r.mismatch.length)
    return "休みの指定はありません(通常どおり営業)";
  const parts = r.runs.map((run) =>
    run.days === 1
      ? `休み ${md(run.start)}(${DOW[dowOf(run.start)]})`
      : `休み ${md(run.start)}(${DOW[dowOf(run.start)]})〜${md(run.end)}(${DOW[dowOf(run.end)]}) ${run.days}日間`,
  );
  const open = r.mismatch.filter((d) => d.plan !== null).length;
  if (open) parts.push(`短縮・特別営業 ${open}日`);
  const last = r.runs[r.runs.length - 1];
  if (last)
    parts.push(
      `${md(last.resumeDate)}(${DOW[dowOf(last.resumeDate)]})から営業`,
    );
  return parts.join(" / ");
}

const MONTH_WEEKS = (() => {
  const days = datesBetween(PERIOD.start, PERIOD.end);
  const lead = (dowOf(PERIOD.start) + 6) % 7;
  const cells: (string | null)[] = [
    ...Array.from({ length: lead }, () => null),
    ...days,
  ];
  while (cells.length % 7) cells.push(null);
  const out: (string | null)[][] = [];
  for (let i = 0; i < cells.length; i += 7) out.push(cells.slice(i, i + 7));
  return out;
})();

/** お店のサイトに貼るHTML(スタイルは style 属性に入れ、外部のCSS・JSに頼らない) */
export function buildHtml(r: Result): string {
  const byDate = Object.fromEntries(r.days.map((d) => [d.date, d]));
  const head = DOW_ORDER.map(
    (d) =>
      `<th scope="col" style="padding:4px 0;font-weight:600;color:${d === 0 ? VERM : "#57534e"}">${DOW[d]}</th>`,
  ).join("");
  const rows = MONTH_WEEKS.map(
    (wk) =>
      `      <tr>${wk
        .map((d) => {
          if (!d) return `<td style="border:1px solid #e7e5e4"></td>`;
          const p = byDate[d];
          const off = p.plan === null;
          const mark = off
            ? "休"
            : p.status === "short"
              ? "短縮"
              : p.status === "special"
                ? "営業"
                : "";
          const bg = off ? "#fdeeea" : p.status ? "#fffbeb" : "#fff";
          const color = p.holiday || p.dow === 0 ? VERM : "#1c1917";
          const label = d.endsWith("-01") || d === PERIOD.start ? `${Number(d.slice(5, 7))}/` : "";
          return `<td style="border:1px solid #e7e5e4;padding:6px 0;background:${bg};color:${color}">${label}${Number(d.slice(8))}${mark ? `<br><span style="font-size:11px;font-weight:700;color:${off ? VERM : "#92400e"}">${mark}</span>` : ""}</td>`;
        })
        .join("")}</tr>`,
  ).join("\n");
  const notice = buildNotice(r)
    .split("\n")
    .slice(1)
    .map((l) => `    <li>${l.replace(/^・/, "")}</li>`)
    .join("\n");
  return [
    `<section aria-labelledby="year-end-days" style="max-width:28rem;font-family:system-ui,sans-serif;color:#1c1917;line-height:1.6">`,
    `  <h2 id="year-end-days" style="margin:0 0 8px;font-size:18px">年末年始の営業日</h2>`,
    `  <table style="width:100%;border-collapse:collapse;text-align:center;font-size:14px">`,
    `    <thead><tr>${head}</tr></thead>`,
    `    <tbody>`,
    rows,
    `    </tbody>`,
    `  </table>`,
    notice
      ? `  <ul style="margin:8px 0 0;padding-left:1.2em;font-size:14px">\n${notice}\n  </ul>`
      : `  <p style="margin:8px 0 0;font-size:14px">年末年始も通常どおり営業いたします。</p>`,
    `</section>`,
  ].join("\n");
}

const icsDate = (iso: string) => iso.replaceAll("-", "");
const icsUtc = (iso: string, t: string) => {
  const [y, m, d] = iso.split("-").map(Number);
  const [h, mm] = t.split(":").map(Number);
  // 日本時間(UTC+9)を UTC に直す
  return new Date(Date.UTC(y, m - 1, d, h - 9, mm))
    .toISOString()
    .replace(/[-:]/g, "")
    .replace(/\.\d{3}/, "");
};

/** Googleカレンダーへ読み込む .ics。連続休業は終日の予定、短縮・特別営業はその時間の予定にする */
export function buildIcs(r: Result, stamp = new Date()): string {
  const dtstamp = stamp
    .toISOString()
    .replace(/[-:]/g, "")
    .replace(/\.\d{3}/, "");
  const ev: string[][] = [];
  for (const run of r.runs)
    ev.push([
      `UID:closed-${icsDate(run.start)}@business-day-calendar`,
      `DTSTAMP:${dtstamp}`,
      `DTSTART;VALUE=DATE:${icsDate(run.start)}`,
      `DTEND;VALUE=DATE:${icsDate(run.resumeDate)}`,
      "SUMMARY:休業(年末年始)",
      "TRANSP:TRANSPARENT",
    ]);
  for (const d of r.mismatch) {
    if (d.plan === null) continue;
    ev.push([
      `UID:${d.status ?? "open"}-${icsDate(d.date)}@business-day-calendar`,
      `DTSTAMP:${dtstamp}`,
      `DTSTART:${icsUtc(d.date, d.plan.open)}`,
      `DTEND:${icsUtc(d.date, d.plan.close)}`,
      `SUMMARY:${d.status === "short" ? "短縮営業" : "特別営業"} ${range(d.plan)}`,
      "TRANSP:TRANSPARENT",
    ]);
  }
  return [
    "BEGIN:VCALENDAR",
    "VERSION:2.0",
    "PRODID:-//business-day-calendar//JA",
    "CALSCALE:GREGORIAN",
    "METHOD:PUBLISH",
    "X-WR-CALNAME:年末年始の営業日",
    "X-WR-TIMEZONE:Asia/Tokyo",
    ...ev.flatMap((e) => ["BEGIN:VEVENT", ...e, "END:VEVENT"]),
    "END:VCALENDAR",
    "",
  ].join("\r\n");
}

// ---- 画面 ----
const noop = () => () => {};
const tokyoToday = () =>
  new Intl.DateTimeFormat("en-CA", {
    timeZone: "Asia/Tokyo",
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  }).format(new Date());

const DAYS = datesBetween(PERIOD.start, PERIOD.end);
const LEAD = (dowOf(PERIOD.start) + 6) % 7; // 月曜始まりの先頭の空白
const WEEKS: string[][] = (() => {
  const out: string[][] = [];
  let cur: string[] = [];
  for (const d of DAYS) {
    if (dowOf(d) === 1 && cur.length) {
      out.push(cur);
      cur = [];
    }
    cur.push(d);
  }
  if (cur.length) out.push(cur);
  return out;
})();

function TimeSelect({
  label,
  value,
  onChange,
  min,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  min?: string;
}) {
  return (
    <label className="inline-flex items-center gap-1.5 text-[15px]">
      <span className="text-stone-600">{label}</span>
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className={`min-h-11 border border-stone-300 bg-white px-2 font-display text-[16px] tabular-nums text-stone-900 ${focusRing}`}
      >
        {TIMES.filter((t) => (min ? t > min : t < "24:00")).map((t) => (
          <option key={t} value={t}>
            {t}
          </option>
        ))}
      </select>
    </label>
  );
}


const reducedMotion = () =>
  typeof window !== "undefined" &&
  window.matchMedia("(prefers-reduced-motion: reduce)").matches;

/** クリップボードへ書く。使えない環境(権限なし・http)は隠した textarea と execCommand で代え、スクロール位置は動かさない */
async function writeClipboard(text: string): Promise<boolean> {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch {
    const prev = document.activeElement as HTMLElement | null;
    const ta = document.createElement("textarea");
    ta.value = text;
    ta.setAttribute("readonly", "");
    ta.style.cssText =
      "position:fixed;top:0;left:0;width:1px;height:1px;opacity:0;pointer-events:none";
    document.body.appendChild(ta);
    ta.focus({ preventScroll: true });
    ta.select();
    let ok = false;
    try {
      ok = document.execCommand("copy");
    } catch {
      ok = false;
    }
    ta.remove();
    prev?.focus({ preventScroll: true });
    return ok;
  }
}

/** 数。値が変わったときだけ 250ms 拡大してアンバーに光らせる */
function Count({
  value,
  color,
  className = "text-[2rem]",
}: {
  value: number;
  color?: string;
  className?: string;
}) {
  const ref = useRef<HTMLSpanElement>(null);
  const prev = useRef(value);
  useEffect(() => {
    if (prev.current === value) return;
    prev.current = value;
    if (reducedMotion()) return;
    ref.current?.animate(
      [{ transform: "scale(1.3)", color: "#d97706" }, { transform: "scale(1)" }],
      { duration: 250, easing: "cubic-bezier(.2,.7,.3,1)" },
    );
  }, [value]);
  return (
    <span
      ref={ref}
      className={`inline-block origin-bottom-left font-display font-bold leading-none tabular-nums ${className}`}
      style={{ color }}
    >
      {value}
    </span>
  );
}

type Copied = { key: string; ok: boolean } | null;

/** 押したボタン自体が「コピーしました ✓」に変わる。3つの文言を同じマスに重ね、幅を動かさない */
function CopyButton({
  id,
  copied,
  onCopy,
  children,
  primary,
}: {
  id: string;
  copied: Copied;
  onCopy: () => void;
  children: string;
  primary?: boolean;
}) {
  const state = copied?.key === id ? copied.ok : null;
  const look =
    state === true
      ? "border-[#d97706] bg-amber-50 text-amber-950"
      : primary
        ? "border-stone-900 bg-stone-900 text-white hover:bg-amber-800"
        : "border-stone-900 bg-white text-stone-900 hover:bg-stone-50";
  const layer = (on: boolean) => `[grid-area:1/1] ${on ? "" : "invisible"}`;
  return (
    <button
      type="button"
      onClick={onCopy}
      data-copy={id}
      data-copied={state === true ? "" : undefined}
      className={`min-h-11 border px-3.5 text-[15px] font-bold transition-colors duration-200 motion-reduce:transition-none ${look} ${focusRing}`}
    >
      <span className="grid">
        <span className={layer(state === null)}>{children}</span>
        <span className={layer(state === true)}>コピーしました ✓</span>
        <span className={layer(state === false)}>下の欄から選んでコピー</span>
      </span>
    </button>
  );
}

type GuideState = Guidance | "none";
const GUIDE_STATES: GuideState[] = [
  "none",
  "special-hours",
  "check-help",
  "temporarily-closed",
];

/** 連続休業の案内。4つの状態を同じマスに重ねて描き、高さを最大の状態にそろえる(見本を替えても下の日付帯が動かない) */
function GuideBanner({ run }: { run: Run | null }) {
  const active: GuideState = run ? run.guidance : "none";
  const refs = useRef<Partial<Record<GuideState, HTMLDivElement | null>>>({});
  const prev = useRef(active);
  useEffect(() => {
    if (prev.current === active) return;
    prev.current = active;
    if (reducedMotion()) return;
    refs.current[active]?.animate(
      [
        { opacity: 0, transform: "translateY(6px)" },
        { opacity: 1, transform: "translateY(0)" },
      ],
      { duration: 250, easing: "ease-out" },
    );
  }, [active]);
  const frame: Record<GuideState, string> = {
    none: "border-stone-300 bg-white",
    "special-hours": "border-stone-300 bg-white",
    "check-help": "border-2 border-[#d97706] bg-amber-50",
    "temporarily-closed": "border-[#e8b4a8] bg-[#fdeeea]",
  };
  const tag: Record<GuideState, string> = {
    none: "連続休業なし",
    "special-hours": "6日以内",
    "check-help": "ちょうど7日",
    "temporarily-closed": "8日以上",
  };
  return (
    <div className="grid" data-guidance={active}>
      {GUIDE_STATES.map((g) => {
        const on = g === active;
        return (
          <div
            key={g}
            ref={(el) => {
              refs.current[g] = el;
            }}
            aria-hidden={!on}
            className={`[grid-area:1/1] border px-3 py-2 ${frame[g]} ${on ? "" : "invisible"}`}
          >
            <p className="flex flex-wrap items-baseline gap-x-2 text-[16px] font-bold leading-snug">
              <span
                className={`px-1.5 text-[13px] ${g === "check-help" ? "bg-[#d97706] text-white" : g === "temporarily-closed" ? "bg-[#b7281a] text-white" : "bg-stone-200 text-stone-700"}`}
              >
                {tag[g]}
              </span>
              {g === "none" ? "通常どおり" : GUIDE_LABEL[g]}
            </p>
            <p className="mt-1 text-[14px] leading-[1.6] text-stone-700">
              {g === "none"
                ? "通常なら営業する日を含む連続休業はありません"
                : on && run
                  ? `${md(run.start)}〜${md(run.end)}(${run.days}日・定休日を含む)`
                  : "12/28〜1/4(8日・定休日を含む)"}
            </p>
            <p className="mt-0.5 text-[14px] leading-[1.6] text-stone-700">
              {g === "none" && "通常と異なる日は日別メモにまとめます"}
              {g === "special-hours" && "日付と時刻を1日ずつ、日別メモへ"}
              {g === "temporarily-closed" && (
                <>
                  再開日{" "}
                  <strong className="text-[16px] text-stone-900">
                    {on && run ? jp(run.resumeDate) : "1月5日(火)"}
                  </strong>
                </>
              )}
              {g === "check-help" && (
                <span className="flex flex-wrap gap-x-3">
                  {(
                    [
                      [HELP_SPECIAL, "特別営業時間のヘルプ"],
                      [HELP_CLOSE, "臨時休業のヘルプ"],
                    ] as const
                  ).map(([href, t]) => (
                    <a
                      key={href}
                      href={href}
                      target="_blank"
                      rel="noopener noreferrer"
                      tabIndex={on ? undefined : -1}
                      className={`font-bold text-stone-900 underline underline-offset-4 ${focusRing}`}
                    >
                      {t}
                    </a>
                  ))}
                  <span>確認日 {CHECKED_ON}</span>
                </span>
              )}
            </p>
          </div>
        );
      })}
    </div>
  );
}

const summaryCls = `flex min-h-12 cursor-pointer list-none items-center gap-2 px-4 text-[16px] font-bold sm:px-6 [&::-webkit-details-marker]:hidden ${focusRing} focus-visible:ring-offset-0`;

function Chevron() {
  return (
    <span
      aria-hidden
      className="inline-block w-3 text-[14px] leading-none text-stone-500 transition-transform duration-200 group-open:rotate-90 motion-reduce:transition-none"
    >
      ▸
    </span>
  );
}

export default function BusinessDayCalendar() {
  const uid = useId();
  const [week, setWeek] = useState<WeekRow[]>(DEFAULT_WEEK);
  const [rule, setRule] = useState<HolidayRule>("weekday");
  const [overrides, setOverrides] =
    useState<Record<string, Override>>(DEFAULT_OVERRIDES);
  const [rangeMode, setRangeMode] = useState(false);
  const [anchor, setAnchor] = useState<string | null>(null);
  const [sel, setSel] = useState<{ a: string; b: string } | null>(null);
  const [focusIdx, setFocusIdx] = useState(DAYS.indexOf("2026-12-28"));
  const [copied, setCopied] = useState<Copied>(null);
  const [confirmedFor, setConfirmedFor] = useState<string | null>(null);
  const [msg, setMsg] = useState("");
  const [fallback, setFallback] = useState<{ key: string; text: string } | null>(
    null,
  );
  const cellRefs = useRef<(HTMLButtonElement | null)[]>([]);
  const rootRef = useRef<HTMLElement>(null);
  const prevSig = useRef<Record<string, string> | null>(null);
  const copyTimer = useRef<number | undefined>(undefined);
  const first = useRef(true);

  // 今日(Asia/Tokyo)。サーバーでは null にして hydration のずれを避ける
  const today = useSyncExternalStore(noop, tokyoToday, () => null);

  const r = useMemo(
    () => evaluate(week, rule, overrides),
    [week, rule, overrides],
  );
  const memo = useMemo(() => buildMemo(r), [r]);
  const notice = useMemo(() => buildNotice(r), [r]);
  const json = useMemo(
    () => buildJson(week, rule, overrides, r),
    [week, rule, overrides, r],
  );
  const band = useMemo(() => buildBand(r), [r]);
  const html = useMemo(() => buildHtml(r), [r]);
  const summary = useMemo(() => summaryLine(r), [r]);
  const byDate = useMemo(
    () => Object.fromEntries(r.days.map((d) => [d.date, d])),
    [r],
  );
  const activePreset =
    PRESETS.find((p) => sameOverrides(p.overrides, overrides))?.key ?? null;
  const inPeriod =
    today !== null && today >= PERIOD.start && today <= PERIOD.end;

  // 変わるたびに要点を読み上げる(初回は読まない)
  useEffect(() => {
    if (first.current) {
      first.current = false;
      return;
    }
    setMsg(summary);
  }, [summary]);

  // 予定が変わった日だけ、日付のマスと2段比較の行をアンバーから朱を経て今の色へ 280ms で塗り替える。
  // 描画の直後・塗る前に始めるので、今の色が一瞬見えてから戻るちらつきが出ない
  useLayoutEffect(() => {
    const sig = Object.fromEntries(
      r.days.map((d) => [d.date, `${planLabel(d)}|${d.mismatch}`]),
    );
    const prev = prevSig.current;
    prevSig.current = sig;
    const root = rootRef.current;
    if (!prev || !root || reducedMotion()) return;
    for (const d of DAYS) {
      if (prev[d] === sig[d]) continue;
      root
        .querySelectorAll<HTMLElement>(`[data-day="${d}"],[data-cmp="${d}"]`)
        .forEach((el) => {
          const to = getComputedStyle(el).backgroundColor;
          el.animate(
            [
              { backgroundColor: "#fbbf24" },
              { backgroundColor: "#f19a85", offset: 0.45 },
              { backgroundColor: to },
            ],
            { duration: 280, easing: "ease-out" },
          );
        });
    }
  }, [r]);

  useEffect(() => () => window.clearTimeout(copyTimer.current), []);

  const copy = async (key: string, text: string, what: string) => {
    const ok = await writeClipboard(text);
    setCopied({ key, ok });
    setFallback(ok ? null : { key, text });
    setMsg(
      ok
        ? `コピーしました(${what})`
        : "コピーできませんでした。下の欄から選んでコピーしてください。",
    );
    window.clearTimeout(copyTimer.current);
    copyTimer.current = window.setTimeout(() => setCopied(null), 1500);
  };

  const downloadIcs = () => {
    const blob = new Blob([buildIcs(r)], { type: "text/calendar;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "year-end-business-days.ics";
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.setTimeout(() => URL.revokeObjectURL(url), 1000);
    setCopied({ key: "ics", ok: true });
    setMsg("Googleカレンダー用のファイル(.ics)を書き出しました");
    window.clearTimeout(copyTimer.current);
    copyTimer.current = window.setTimeout(() => setCopied(null), 1500);
  };

  const tapDay = (d: string) => {
    if (!rangeMode) {
      setOverrides((o) => toggleDay(d, week, rule, o));
      return;
    }
    if (anchor === null) {
      setAnchor(d);
      setSel(null);
      setMsg(
        `${jp(d)}から。終了日を選んでください(同じ日をもう一度で1日だけ)。`,
      );
      return;
    }
    const a = anchor < d ? anchor : d;
    const b = anchor < d ? d : anchor;
    setAnchor(null);
    setSel({ a, b });
    setMsg(
      `${md(a)}〜${md(b)}(${datesBetween(a, b).length}日)を選びました。状態を選んでください。`,
    );
  };

  const selDates = sel ? datesBetween(sel.a, sel.b) : [];
  const selStatus: Status | null | "mixed" = (() => {
    if (!sel) return null;
    const s = new Set(selDates.map((d) => overrides[d]?.status ?? null));
    return s.size === 1 ? [...s][0] : "mixed";
  })();
  const selHours: DayHours | null =
    sel && overrides[sel.a] && overrides[sel.a].status !== "closed"
      ? overrides[sel.a]
      : null;

  const apply = (status: Status | null) => {
    if (!sel) return;
    setOverrides((o) => {
      const n = { ...o };
      for (const d of selDates) {
        if (status === null) {
          delete n[d];
          continue;
        }
        const w = week[dowOf(d)];
        if (status === "closed") n[d] = { status, open: "", close: "" };
        else if (status === "short") {
          const close = addMinutes(w.close, -180);
          n[d] = {
            status,
            open: w.open,
            close: close > w.open ? close : addMinutes(w.open, 120),
          };
        } else n[d] = { status, open: "10:00", close: "15:00" };
      }
      return n;
    });
  };
  const setSelHours = (patch: Partial<DayHours>) => {
    if (!sel) return;
    setOverrides((o) => {
      const n = { ...o };
      for (const d of selDates) {
        const cur = n[d];
        if (!cur || cur.status === "closed") continue;
        const next = { ...cur, ...patch };
        if (next.close <= next.open) next.close = addMinutes(next.open, 15);
        n[d] = next;
      }
      return n;
    });
  };

  const onStripKey = (e: ReactKeyboardEvent<HTMLDivElement>) => {
    const k = e.key;
    let n = focusIdx;
    if (k === "ArrowRight") n++;
    else if (k === "ArrowLeft") n--;
    else if (k === "ArrowDown") n += 7;
    else if (k === "ArrowUp") n -= 7;
    else if (k === "Home") n = 0;
    else if (k === "End") n = DAYS.length - 1;
    else if (k === "Escape") {
      setAnchor(null);
      setSel(null);
      return;
    } else return;
    e.preventDefault();
    n = Math.max(0, Math.min(DAYS.length - 1, n));
    setFocusIdx(n);
    cellRefs.current[n]?.focus();
  };

  const setWeekRow = (dow: number, patch: Partial<WeekRow>) =>
    setWeek((w) =>
      w.map((row, i) => {
        if (i !== dow) return row;
        const next = { ...row, ...patch };
        if (next.close <= next.open) next.close = addMinutes(next.open, 15);
        return next;
      }),
    );

  const memoDone = memo.length > 0;
  const confirmed = confirmedFor === memo;
  const l = r.longest;

  const fallbackBox = (keys: string[]) =>
    fallback !== null &&
    keys.includes(fallback.key) && (
      <label className="mt-3 block text-[15px]">
        コピーする本文(選択してコピーしてください)
        <textarea
          readOnly
          value={fallback.text}
          rows={6}
          className={`mt-1 block w-full border border-stone-300 p-2 text-[15px] ${focusRing}`}
        />
      </label>
    );

  return (
    <section
      ref={rootRef}
      className="@container mx-auto w-full max-w-3xl overflow-x-clip border border-stone-200 bg-white text-stone-900"
      aria-labelledby={`${uid}-h`}
    >
      <h2 id={`${uid}-h`} className="sr-only">
        年末年始の営業日カレンダー({md(PERIOD.start)}〜{md(PERIOD.end)})
      </h2>

      {/* 見本: 日を押すと休み⇄営業 */}
      <div className="px-4 pb-5 pt-4 sm:px-6">
        <p className="flex flex-wrap items-center gap-x-1.5 text-[16px] font-bold leading-snug">
          {rangeMode ? (
            "開始日と終了日を押して、下で状態を選びます"
          ) : (
            <>
              日を押すと
              <span className="bg-[#fdeeea] px-1.5" style={{ color: VERM }}>
                休み
              </span>
              ⇄<span className="border border-stone-300 px-1.5">営業</span>
              が切り替わります
            </>
          )}
        </p>

        <div
          className="mt-3 grid grid-cols-7 text-center text-[13px] text-stone-500"
          aria-hidden
        >
          {DOW_ORDER.map((d) => (
            <span key={d} className={d === 0 ? "text-[#b7281a]" : ""}>
              {DOW[d]}
            </span>
          ))}
        </div>
        <div
          role="group"
          aria-label={`日付 ${md(PERIOD.start)}〜${md(PERIOD.end)}`}
          onKeyDown={onStripKey}
          className="mt-1 grid grid-cols-7 border-l border-t border-stone-200"
          data-strip
        >
          {Array.from({ length: LEAD }, (_, i) => (
            <span
              key={`b${i}`}
              aria-hidden
              className="border-b border-r border-stone-200 bg-stone-50"
            />
          ))}
          {DAYS.map((d, i) => {
            const p = byDate[d];
            const inSel = sel !== null && d >= sel.a && d <= sel.b;
            const isAnchor = anchor === d;
            const off = p.plan === null;
            const glyph = off
              ? p.source === "weekday"
                ? "定休"
                : "休み"
              : p.status === "short"
                ? "短縮"
                : p.status === "special"
                  ? "営業"
                  : "";
            const bg = isAnchor
              ? "bg-amber-200"
              : off && p.source !== "weekday"
                ? "bg-[#fdeeea]"
                : off
                  ? "bg-stone-100"
                  : p.status
                    ? "bg-amber-50"
                    : "bg-white";
            const firstOfMonth = i === 0 || d.endsWith("-01");
            return (
              <button
                key={d}
                ref={(el) => {
                  cellRefs.current[i] = el;
                }}
                type="button"
                data-day={d}
                tabIndex={i === focusIdx ? 0 : -1}
                onFocus={() => setFocusIdx(i)}
                onClick={() => tapDay(d)}
                aria-pressed={rangeMode ? inSel || isAnchor : off}
                aria-label={`${jp(d)}${p.holiday ? ` ${p.holiday}` : ""} ${off ? (p.source === "weekday" ? "定休" : "休み") : planLabel(p)}`}
                className={`relative flex min-h-[60px] flex-col items-center justify-start border-b border-r border-stone-200 pb-1.5 pt-1 transition-colors duration-150 motion-reduce:transition-none ${bg} ${isAnchor ? "" : "hover:bg-amber-50"} ${focusRing} focus-visible:z-10 focus-visible:ring-offset-0`}
              >
                {(inSel || isAnchor) && (
                  <span
                    aria-hidden
                    className="pointer-events-none absolute inset-0 opacity-100 shadow-[inset_0_0_0_2px_#d97706] transition-opacity duration-200 motion-reduce:transition-none starting:opacity-0"
                  />
                )}
                <span
                  className={`text-[12px] leading-tight ${p.holiday || p.dow === 0 ? "text-[#b7281a]" : "text-stone-500"}`}
                >
                  {firstOfMonth
                    ? `${Number(d.slice(5, 7))}月`
                    : p.holiday
                      ? "祝"
                      : " "}
                </span>
                <span
                  className={`font-display text-[17px] font-bold leading-tight tabular-nums ${p.holiday || p.dow === 0 ? "text-[#b7281a]" : ""}`}
                >
                  {Number(d.slice(8))}
                </span>
                <span
                  className="text-[12px] font-bold leading-tight"
                  style={{
                    color:
                      off && p.source !== "weekday" ? VERM : "#78716c",
                  }}
                >
                  {glyph || " "}
                </span>
                {isAnchor && (
                  <span className="absolute left-0.5 top-0.5 text-[10px] font-bold text-amber-900">
                    開始
                  </span>
                )}
                {today === d && (
                  <span className="absolute right-0.5 top-0.5 text-[10px] font-bold text-[#b45309]">
                    今日
                  </span>
                )}
              </button>
            );
          })}
        </div>

        <p className="mt-2 text-[15px] leading-[1.6]" data-summary>
          {summary}
        </p>

        {sel && (
          <div
            role="group"
            aria-label={`${md(sel.a)}〜${md(sel.b)}の状態`}
            className="mt-3 border-l-2 border-[#d97706] bg-amber-50/50 py-3 pl-4 pr-3 opacity-100 transition-opacity motion-reduce:transition-none starting:opacity-0"
            data-picker
          >
            <p className="text-[16px] font-bold">
              {jp(sel.a)}
              {sel.a !== sel.b && `〜${jp(sel.b)}`}({selDates.length}日)
            </p>
            <div className="mt-2 flex flex-wrap gap-2">
              {(
                [
                  ["closed", "休業"],
                  ["short", "短縮"],
                  ["special", "特別営業"],
                  [null, "指定を外す"],
                ] as const
              ).map(([s, t]) => (
                <button
                  key={t}
                  type="button"
                  data-status={s ?? "none"}
                  aria-pressed={selStatus === s}
                  onClick={() => apply(s)}
                  className={`min-h-11 min-w-[5.5rem] border px-3 text-[16px] font-bold ${
                    selStatus === s
                      ? "border-stone-900 bg-stone-900 text-white"
                      : "border-stone-300 bg-white hover:bg-stone-50"
                  } ${focusRing}`}
                >
                  {t}
                </button>
              ))}
              <button
                type="button"
                onClick={() => setSel(null)}
                className={`min-h-11 px-2 text-[15px] text-stone-600 underline underline-offset-4 ${focusRing}`}
              >
                閉じる
              </button>
            </div>
            {selHours && (selStatus === "short" || selStatus === "special") && (
              <div className="mt-3 flex flex-wrap gap-3">
                <TimeSelect
                  label="開店"
                  value={selHours.open}
                  onChange={(v) => setSelHours({ open: v })}
                />
                <TimeSelect
                  label="閉店"
                  value={selHours.close}
                  min={selHours.open}
                  onChange={(v) => setSelHours({ close: v })}
                />
              </div>
            )}
          </div>
        )}

        <div className="mt-3 flex flex-wrap gap-2">
          <CopyButton
            id="code"
            copied={copied}
            primary
            onCopy={() => copy("code", html, "サイトに貼るHTML")}
          >
            コードをコピー
          </CopyButton>
          <button
            type="button"
            onClick={downloadIcs}
            data-ics
            className={`min-h-11 border px-3.5 text-[15px] font-bold transition-colors duration-200 motion-reduce:transition-none ${
              copied?.key === "ics"
                ? "border-[#d97706] bg-amber-50 text-amber-950"
                : "border-stone-900 bg-white text-stone-900 hover:bg-stone-50"
            } ${focusRing}`}
          >
            <span className="grid">
              <span
                className={`[grid-area:1/1] ${copied?.key === "ics" ? "invisible" : ""}`}
              >
                Googleカレンダー用に書き出す
              </span>
              <span
                className={`[grid-area:1/1] ${copied?.key === "ics" ? "" : "invisible"}`}
              >
                書き出しました ✓
              </span>
            </span>
          </button>
        </div>
        <p className="mt-2 text-[14px] leading-[1.6] text-stone-600">
          コードはお店のサイトにそのまま貼れるHTMLです。書き出したファイル(.ics)は、Googleカレンダーの「設定」→「インポート」で読み込めます。
        </p>
        {fallbackBox(["code"])}
      </div>

      {/* 営業時間・定休日・特別営業の設定(最初は畳む) */}
      <details className="group border-t border-stone-200" data-settings>
        <summary className={summaryCls}>
          <Chevron />
          営業時間・定休日・特別営業を設定する
        </summary>
        <div className="px-4 pb-5 sm:px-6">
          <p className="text-[15px] font-bold text-stone-700">
            {summarizeWeek(week)}
          </p>
          <div className="mt-2 border-t border-stone-200" data-week>
            {DOW_ORDER.map((d) => {
              const w = week[d];
              return (
                <div
                  key={d}
                  className="flex flex-wrap items-center gap-x-4 gap-y-2 border-b border-stone-200 py-2"
                >
                  <span className="w-8 text-[16px] font-bold">{DOW[d]}</span>
                  <label className="inline-flex min-h-11 items-center gap-2 text-[15px]">
                    <input
                      type="checkbox"
                      checked={w.closed}
                      onChange={(e) =>
                        setWeekRow(d, { closed: e.target.checked })
                      }
                      className={`size-5 accent-[#d97706] ${focusRing}`}
                    />
                    定休
                  </label>
                  {!w.closed && (
                    <>
                      <TimeSelect
                        label="開店"
                        value={w.open}
                        onChange={(v) => setWeekRow(d, { open: v })}
                      />
                      <TimeSelect
                        label="閉店"
                        value={w.close}
                        min={w.open}
                        onChange={(v) => setWeekRow(d, { close: v })}
                      />
                    </>
                  )}
                </div>
              );
            })}
          </div>
          <fieldset className="mt-4">
            <legend className="text-[15px] font-bold text-stone-700">
              祝日の扱い(定休曜日より優先・個別の日の指定が最優先)
            </legend>
            <div className="mt-1 flex flex-wrap gap-x-5 gap-y-1">
              {(
                [
                  ["weekday", "曜日どおり"],
                  ["open", "祝日は営業"],
                  ["closed", "祝日は休み"],
                ] as const
              ).map(([v, t]) => (
                <label
                  key={v}
                  className="inline-flex min-h-11 items-center gap-2 text-[16px]"
                >
                  <input
                    type="radio"
                    name={`${uid}-rule`}
                    checked={rule === v}
                    onChange={() => setRule(v)}
                    className={`size-5 accent-[#d97706] ${focusRing}`}
                  />
                  {t}
                </label>
              ))}
            </div>
          </fieldset>

          <div className="mt-4 border-t border-stone-200 pt-4">
            <label className="flex min-h-11 items-center gap-2 text-[16px] font-bold">
              <input
                type="checkbox"
                checked={rangeMode}
                onChange={(e) => {
                  setRangeMode(e.target.checked);
                  setAnchor(null);
                  setSel(null);
                }}
                className={`size-5 accent-[#d97706] ${focusRing}`}
                data-range-mode
              />
              期間を選んで、短縮・特別営業の時間を入れる
            </label>
            <p className="text-[14px] leading-[1.6] text-stone-600">
              オンにすると、上のカレンダーで開始日と終了日を押して、休業・短縮・特別営業を選べます(矢印キー・Home・End・Escでも操作できます)。
            </p>
            <div
              className="mt-3 flex flex-wrap items-center gap-2"
              role="group"
              aria-label="見本"
            >
              <span className="text-[15px] text-stone-600">見本</span>
              {PRESETS.map((p) => (
                <button
                  key={p.key}
                  type="button"
                  data-preset={p.key}
                  aria-pressed={activePreset === p.key}
                  title={p.note}
                  onClick={() => {
                    setOverrides(p.overrides);
                    setSel(null);
                    setAnchor(null);
                  }}
                  className={`min-h-11 border px-3 text-[15px] font-bold transition-colors duration-200 motion-reduce:transition-none ${
                    activePreset === p.key
                      ? "border-[#d97706] bg-amber-50 text-amber-950 shadow-[inset_0_-3px_0_#d97706]"
                      : "border-stone-300 bg-white hover:bg-stone-50"
                  } ${focusRing}`}
                >
                  {p.label}
                </button>
              ))}
              <button
                type="button"
                onClick={() => {
                  setOverrides({});
                  setSel(null);
                  setAnchor(null);
                }}
                className={`min-h-11 px-1 text-[15px] text-stone-600 underline underline-offset-4 hover:text-stone-900 ${focusRing}`}
              >
                指定をすべて外す
              </button>
            </div>
          </div>
        </div>
      </details>

      {/* Googleマップ(ビジネスプロフィール)用の日別メモ・お知らせ文(最初は畳む) */}
      <details className="group border-t border-stone-200" data-google>
        <summary className={summaryCls}>
          <Chevron />
          Googleマップ用の日別メモ・お知らせ文を見る
        </summary>
        <div className="border-t border-stone-200 bg-stone-50/60 px-4 py-4 sm:px-6" data-band>
          <div className="flex flex-wrap items-end gap-x-6 gap-y-2">
            <p>
              <span className="block text-[14px] text-stone-600">
                通常と異なる日
              </span>
              <Count
                value={r.mismatch.length}
                color={r.mismatch.length ? VERM : undefined}
              />
              <span className="ml-1 text-[16px] font-bold">日</span>
            </p>
            <p>
              <span className="block text-[14px] text-stone-600">連続休業</span>
              <Count value={l ? l.days : 0} />
              <span className="ml-1 text-[16px] font-bold">日</span>
            </p>
            <p className="text-[14px] leading-snug text-stone-600">
              入力推奨祝日{" "}
              <Count
                value={r.recommend.length}
                className="text-[16px] text-stone-900"
              />
              日
            </p>
          </div>
          <div className="mt-2.5">
            <GuideBanner run={l} />
          </div>
          <p className="mt-1.5 text-[14px] leading-snug text-stone-600">
            Googleビジネスプロフィール未接続・特別営業時間を未設定と仮定
            {today !== null && !inPeriod && "/期間外のため見本"}
          </p>
        </div>

        <div data-out="memo" className="border-t border-stone-200 px-4 py-5 sm:px-6">
          <h3 className="text-[16px] font-bold">日別メモ(設定用)</h3>
          <div className="mt-2 flex flex-wrap gap-2">
            <CopyButton
              id="band"
              copied={copied}
              primary
              onCopy={() => copy("band", `${band}\n\n${memo}`, "日ごとの比較とメモ")}
            >
              日ごとの比較とメモをまとめてコピー
            </CopyButton>
            <CopyButton
              id="memo"
              copied={copied}
              onCopy={() => copy("memo", memo, "日別メモ")}
            >
              メモだけコピー
            </CopyButton>
          </div>
          <pre className="mt-2 max-h-[22rem] overflow-auto whitespace-pre-wrap border border-stone-200 bg-stone-50/60 p-3 font-sans text-[15px] leading-[1.75]">
            {memo}
          </pre>
          <ul className="mt-2 grid gap-1 text-[15px]">
            <li className="flex min-h-11 items-center gap-2">
              <span
                aria-hidden
                className={`grid size-5 shrink-0 place-items-center border text-[13px] font-bold ${memoDone ? "border-[#d97706] bg-[#d97706] text-white" : "border-stone-300"}`}
              >
                {memoDone ? "✓" : ""}
              </span>
              メモ作成済み(自動)
            </li>
            <li>
              <label className="flex min-h-11 items-center gap-2">
                <input
                  type="checkbox"
                  checked={confirmed}
                  onChange={(e) =>
                    setConfirmedFor(e.target.checked ? memo : null)
                  }
                  className={`size-5 shrink-0 accent-[#d97706] ${focusRing}`}
                  data-confirm
                />
                Googleで設定・表示を確認(手動でチェック。メモが変わるとチェックが外れます)
              </label>
            </li>
          </ul>
        </div>

        {/* 2段比較 */}
        <div className="border-t border-stone-200 px-4 py-5 sm:px-6" data-compare>
          <h3 className="text-[16px] font-bold">
            日ごとの比較(上段=今回の予定・下段=通常の営業時間)
          </h3>
          <div className="mt-3 border-t border-stone-300">
            {WEEKS.map((wk) => (
              <div key={wk[0]} className="border-b border-stone-200">
                {wk.map((d) => {
                  const p = byDate[d];
                  return (
                    <div
                      key={d}
                      data-cmp={d}
                      className={`grid grid-cols-[6.5rem_minmax(0,1fr)] items-baseline gap-x-3 border-t border-stone-100 px-2 py-2 first:border-t-0 ${
                        p.mismatch ? "bg-[#fdeeea]" : ""
                      }`}
                    >
                      <p className="text-[15px] font-bold leading-snug">
                        {md(d)}
                        <span
                          className={
                            p.holiday || p.dow === 0
                              ? "text-[#b7281a]"
                              : "text-stone-500"
                          }
                        >
                          ({DOW[p.dow]})
                        </span>
                        {p.holiday && (
                          <span className="block text-[13px] font-normal text-stone-500">
                            {p.holiday}
                          </span>
                        )}
                      </p>
                      <div className="min-w-0 @xl:grid @xl:grid-cols-2 @xl:gap-x-4">
                        <p className="flex items-baseline gap-2 text-[16px] leading-snug">
                          <span className="w-7 shrink-0 text-[12px] text-stone-500">
                            今回
                          </span>
                          <span
                            className="font-display tabular-nums"
                            style={{
                              color: p.mismatch ? VERM : undefined,
                              fontWeight: p.mismatch ? 700 : 500,
                            }}
                          >
                            {planLabel(p)}
                          </span>
                          {p.recommend && (
                            <span className="whitespace-nowrap bg-stone-200 px-1 text-[12px] text-stone-700">
                              入力推奨
                            </span>
                          )}
                        </p>
                        <p className="flex items-baseline gap-2 text-[16px] leading-snug text-stone-500">
                          <span className="w-7 shrink-0 text-[12px]">通常</span>
                          <span className="font-display tabular-nums">
                            {normalLabel(p)}
                          </span>
                        </p>
                      </div>
                    </div>
                  );
                })}
              </div>
            ))}
          </div>
        </div>

        {/* 案内と出力 */}
        <div className="border-t border-stone-200 px-4 py-5 sm:px-6">
          <h3 className="text-[16px] font-bold">連続休業ごとの案内とお知らせ文</h3>
          <div className="mt-2 border-t border-stone-200" data-guides>
            {r.runs.length === 0 && (
              <p className="border-b border-stone-200 py-3 text-[16px] text-stone-600">
                通常なら営業する日を含む連続休業はありません。
              </p>
            )}
            {r.runs.map((run) => (
              <div
                key={run.start}
                className="border-b border-stone-200 py-3"
                data-guide={run.guidance}
              >
                <p className="text-[16px]">
                  <span className="font-bold">
                    {jp(run.start)}〜{jp(run.end)}
                  </span>
                  <span className="ml-2 font-display font-bold tabular-nums">
                    {run.days}日
                  </span>
                  <span className="ml-1 text-[14px] text-stone-500">
                    (定休日を含む)
                  </span>
                </p>
                <p className="mt-1 text-[16px] leading-[1.75]">
                  {run.guidance === "special-hours" && (
                    <>
                      6日以内のため、特別営業時間に日付ごとに入力する内容(日付と時刻)をメモにまとめました。
                    </>
                  )}
                  {run.guidance === "temporarily-closed" && (
                    <>
                      8日以上なので、臨時休業マークの案内です。再開日は{" "}
                      <strong className="text-[18px]">{jp(run.resumeDate)}</strong>
                      。
                    </>
                  )}
                  {run.guidance === "check-help" && (
                    <>
                      <strong style={{ color: VERM }}>要確認</strong>
                      :ちょうど7日は公式ヘルプ間で案内が異なります。両方を読んでから決めてください(確認日{" "}
                      {CHECKED_ON})。
                    </>
                  )}
                </p>
                {run.guidance === "check-help" && (
                  <ul className="mt-2 grid gap-2 text-[15px] leading-[1.6] @xl:grid-cols-2">
                    <li className="border-l-2 border-stone-300 pl-3">
                      <a
                        href={HELP_SPECIAL}
                        target="_blank"
                        rel="noopener noreferrer"
                        className={`font-bold underline underline-offset-4 ${focusRing}`}
                      >
                        特別営業時間を設定する方法
                      </a>
                      <span className="block text-stone-600">
                        6日間以下は特別営業時間、7日間以上は臨時休業で設定するよう案内しています
                      </span>
                    </li>
                    <li className="border-l-2 border-stone-300 pl-3">
                      <a
                        href={HELP_CLOSE}
                        target="_blank"
                        rel="noopener noreferrer"
                        className={`font-bold underline underline-offset-4 ${focusRing}`}
                      >
                        臨時休業として設定する方法
                      </a>
                      <span className="block text-stone-600">
                        7日間以下は特別営業時間、8日間以上は臨時休業で設定するよう案内しています
                      </span>
                    </li>
                  </ul>
                )}
              </div>
            ))}
          </div>

          <div className="mt-5 grid gap-x-8 gap-y-6">
            <div data-out="notice" className="min-w-0">
              <div className="flex flex-wrap items-center justify-between gap-2">
                <h4 className="text-[16px] font-bold">
                  お知らせ文(店頭・SNS・Webサイト)
                </h4>
                <CopyButton
                  id="notice"
                  copied={copied}
                  onCopy={() => copy("notice", notice, "お知らせ文")}
                >
                  お知らせ文をコピー
                </CopyButton>
              </div>
              <pre className="mt-2 whitespace-pre-wrap border border-stone-200 p-3 font-sans text-[16px] leading-[1.8]">
                {notice}
              </pre>
            </div>
            <div data-out="json" className="min-w-0">
              <div className="flex flex-wrap items-center justify-between gap-2">
                <h4 className="text-[16px] font-bold">設定JSON(曜日 0=日)</h4>
                <CopyButton
                  id="json"
                  copied={copied}
                  onCopy={() => copy("json", json, "設定JSON")}
                >
                  JSONをコピー
                </CopyButton>
              </div>
              <pre className="mt-2 max-h-[16rem] overflow-auto border border-stone-200 bg-stone-50/60 p-3 font-mono text-[13px] leading-[1.6]">
                {json}
              </pre>
            </div>
          </div>
          {fallbackBox(["band", "memo", "notice", "json"])}
        </div>
      </details>

      <footer className="border-t border-stone-200 px-4 py-4 text-[14px] leading-[1.7] text-stone-600 sm:px-6">
        <p>
          祝日:
          <a
            href={SRC_HOLIDAY}
            target="_blank"
            rel="noopener noreferrer"
            className={`underline underline-offset-4 ${focusRing}`}
          >
            内閣府「国民の祝日について」
          </a>
          の2026・2027年の祝日を同梱。日数の区切り:
          <a
            href={HELP_SPECIAL}
            target="_blank"
            rel="noopener noreferrer"
            className={`underline underline-offset-4 ${focusRing}`}
          >
            特別営業時間を設定する方法
          </a>
          ・
          <a
            href={HELP_CLOSE}
            target="_blank"
            rel="noopener noreferrer"
            className={`underline underline-offset-4 ${focusRing}`}
          >
            臨時休業として設定する方法
          </a>
          (Google ビジネス プロフィール ヘルプ・確認日 {CHECKED_ON}
          )。Googleへの自動反映は行いません。
          {today !== null && !inPeriod && (
            <>
              今日({md(today)})は{md(PERIOD.start)}〜{md(PERIOD.end)}
              の期間外のため、見本で表示しています。
            </>
          )}
          営業時間・日付は架空の見本です。
        </p>
      </footer>

      <p className="sr-only" aria-live="polite">
        {msg}
      </p>
    </section>
  );
}

Add to your project via shadcn CLI

npx shadcn@latest add https://designs.first-ch.com/r/business-day-calendar.json