BLK-110Blocks

印刷すると押印欄に切り替わる承認ステッパー|押印欄UI・@media print(React・HTML/CSS付き)

稟議・申請の承認状況を、画面では横並びのステッパー(ピル型の状態バッジ・アイコン・処理日)で、印刷では右から埋まる押印欄で出す UI 部品です。上の「承認」「差戻し」「代理承認」で担当・課長・部長を1段ずつ進め、押した後5秒は取り消せます。押印欄の印は朱の丸印に令和の日付、差戻しは「否」の角印、代理は「代」の小印を添えた丸印、不要は斜線で、縁は SVG の feTurbulence と feDisplacementMap でかすれさせています。「印刷プレビュー」を押すと各段のバッジが印に縮んで枠へ落ち、押印欄に組み替わります(140ms・FLIP)。Ctrl+P でも @media print で押印欄だけが印刷されます。段数(2〜5)・役職名・印の文字を変えられ、「お辞儀」で下位の印を上位者へ傾けられます。コード欄の React(variant="stepper" | "seal" の1コンポーネント)と HTML+CSS(1枚)は状態に追従し、ステッパーと押印欄を並べた「見本」入りの 1200×630 PNG も保存できます。依存ライブラリなし。役職・印影は架空の見本です。

プレビュー

BLK-110

印刷すると押印欄に切り替わる承認ステッパー

状態: 課長の承認待ち(2/3段目)

ボタンは課長の段に適用されます。押してから5秒間は取り消せます(Ctrl+Z / ⌘Z)

  1. 担当承認—
  2. 課長承認待ち—
  3. 3部長承認待ち—

Ctrl+P(⌘P)で印刷すると押印欄だけが出ます

5つの状態と2つの見た目

状態画面印刷
承認待ち空欄のまま承認待ち
承認朱の丸印(令和の日付印)承認課長令承認
差戻し「否」の角印差戻し否
代理承認丸印に「代」の小印を添える代理承認課長令承認代
不要斜線不要

押印欄は右端が担当、左へ行くほど上位者。差戻しの段から先は空欄のまま止まります。

段の設定
役職名印の文字不要
1
2
3

今の状態(3段)を STEPS に入れています。variant="stepper" | "seal" で出し分けます

見本の画像にする

ステッパーと押印欄を上下に並べ、中央に「見本」の透かしを入れた 1200×630 の PNG を保存します。仕様の説明や社内の共有に。

X でシェア

説明の全文を読む

稟議・申請の承認状況を、画面では横並びのステッパー(ピル型の状態バッジ・アイコン・処理日)で、印刷では右から埋まる押印欄で出す UI 部品です。上の「承認」「差戻し」「代理承認」で担当・課長・部長を1段ずつ進め、押した後5秒は取り消せます。押印欄の印は朱の丸印に令和の日付、差戻しは「否」の角印、代理は「代」の小印を添えた丸印、不要は斜線で、縁は SVG の feTurbulence と feDisplacementMap でかすれさせています。「印刷プレビュー」を押すと各段のバッジが印に縮んで枠へ落ち、押印欄に組み替わります(140ms・FLIP)。Ctrl+P でも @media print で押印欄だけが印刷されます。段数(2〜5)・役職名・印の文字を変えられ、「お辞儀」で下位の印を上位者へ傾けられます。コード欄の React(variant="stepper" | "seal" の1コンポーネント)と HTML+CSS(1枚)は状態に追従し、ステッパーと押印欄を並べた「見本」入りの 1200×630 PNG も保存できます。依存ライブラリなし。役職・印影は架空の見本です。

追加日:
2026-11-06
更新日:
2026-11-07
依存:
なし
tags
#approval #stepper #status-badge #workflow #print #media-print #hanko #seal #svg-filter #feturbulence #flip-animation #undo #keyboard #japanese #ui #no-dependency #no-image
"use client";

import {
  useEffect,
  useId,
  useMemo,
  useRef,
  useState,
  useSyncExternalStore,
  type KeyboardEvent,
} from "react";
import { flushSync } from "react-dom";

/**
 * 承認状況の二面表示(画面=ステッパー/印刷=押印欄)
 *
 * 差別化: 既存のステータスバッジ(status-badge)は1つの状態を示すだけの静的な部品、制作フロー(process-steps)は
 * 説明用の図で、どちらも状態を進めない。本ブロックは承認1件の状態機械(承認・差戻し・代理・不要と取り消し)を持ち、
 * 同じ状態を画面と紙の2つの見た目へ出し分ける。英字の小見出し・見出しの「。」止め・末尾の矢印リンク・出現アニメは使わない。
 *
 * 汎用技法メモ:
 * 1. **1つの状態から2つの見た目**。状態は段ごとの {status, date} だけで持ち、ステッパーと押印欄はどちらもそこから描く。
 *    押印欄は配列を逆順に並べるだけで「右から埋まる(担当が右端・上位者が左)」になる。
 * 2. **印のかすれは SVG フィルター**。feTurbulence のノイズで feDisplacementMap が縁を 1px ほど揺らし(大きいと小さな字が崩れる)、
 *    別の低周波ノイズを feColorMatrix で透明度に変えて feComposite(in) で抜くと、朱肉の載りむらになる。
 *    seed を段ごとに変えると、同じ印でも押すたびに違う顔になる。
 * 3. **バッジが印へ縮む組み替えは FLIP**。切り替える前に元の要素の位置を測り、flushSync で切り替えた直後に
 *    行き先の要素へ「元の位置・大きさ」の transform を当ててから 140ms で外す。prefers-reduced-motion では測らず即座に替える。
 * 4. **Ctrl+P で押印欄だけを出す**。@media print で「押印欄を含まない要素」と「押印欄の外の要素」を :has() で display:none にし、
 *    中身の無い白紙ページが出ないようにする。ギャラリーの一覧に並ぶ縮小版(inert の中)は対象から外す。
 * 5. **共有画像は SVG を1枚組んで canvas へ**。フィルターごと Image に読み込んで 1200×630 の PNG にする(新しい依存なし)。
 *
 * 文言・役職・印影はすべて架空の見本。
 */

export type Status = "pending" | "approved" | "rejected" | "proxy" | "skipped";
export type Act = "approved" | "rejected" | "proxy";
export type Stage = {
  key: string;
  role: string;
  seal: string;
  skip: boolean;
  status: Exclude<Status, "skipped">;
  /** 処理日(YYYY-MM-DD)。null は「今日」 */
  date: string | null;
};

export const ROLE_SETS: Record<number, string[]> = {
  2: ["担当", "課長"],
  3: ["担当", "課長", "部長"],
  4: ["担当", "課長", "部長", "本部長"],
  5: ["担当", "係長", "課長", "部長", "本部長"],
};

export const STATES: { id: Status; label: string; screen: string; paper: string }[] = [
  { id: "pending", label: "承認待ち", screen: "時計・白のバッジ(次の段は黄色)", paper: "空欄のまま" },
  { id: "approved", label: "承認", screen: "チェック・緑のバッジと処理日", paper: "朱の丸印(令和の日付印)" },
  { id: "rejected", label: "差戻し", screen: "戻る矢印・赤のバッジ。以降は止まる", paper: "「否」の角印" },
  { id: "proxy", label: "代理承認", screen: "「代」・緑の枠線のバッジ", paper: "丸印に「代」の小印を添える" },
  { id: "skipped", label: "不要", screen: "横線・灰色のバッジ。順番を飛ばす", paper: "斜線" },
];

const LABEL: Record<Status, string> = Object.fromEntries(STATES.map((s) => [s.id, s.label])) as Record<Status, string>;

export const INK = "#c23b22";

export function makeStages(n: number, keep: Stage[] = []): Stage[] {
  return ROLE_SETS[n].map(
    (key) =>
      keep.find((s) => s.key === key) ?? { key, role: key, seal: "", skip: false, status: "pending", date: null },
  );
}

export const INITIAL: Stage[] = makeStages(3).map((s, i) => (i === 0 ? { ...s, status: "approved" } : s));

export const statusOf = (s: Stage): Status => (s.skip ? "skipped" : s.status);

/** 次に処理する段。差戻しで止まっている・全段済みなら -1 */
export function cursor(stages: Stage[]): number {
  for (let i = 0; i < stages.length; i++) {
    const s = stages[i];
    if (s.skip) continue;
    if (s.status === "rejected") return -1;
    if (s.status === "pending") return i;
  }
  return -1;
}

export function phase(stages: Stage[]): "running" | "done" | "halted" {
  if (stages.some((s) => !s.skip && s.status === "rejected")) return "halted";
  return cursor(stages) < 0 ? "done" : "running";
}

// 見出しの右に出す状態の1行。役職名が空の段は key で補う(ほかの表示と同じ)
export function statusLineOf(stages: Stage[]): string {
  const ph = phase(stages);
  if (ph === "done") return "決裁済み(全段の処理が終わりました)";
  const name = (s: Stage) => s.role || s.key;
  if (ph === "halted") {
    const r = stages.find((s) => !s.skip && s.status === "rejected");
    return `差戻し(${r ? name(r) : ""}の段で止まっています)`;
  }
  const c = cursor(stages);
  return `${name(stages[c])}の承認待ち(${c + 1}/${stages.length}段目)`;
}

// 段の設定を書き換える。取り消しは「直前の承認操作の前」へ丸ごと戻すので、
// 編集のあとに残すと編集まで黙って巻き戻る。編集したら取り消しは閉じる
export function editStage<U>(state: { stages: Stage[]; undo: U | null }, i: number, patch: Partial<Stage>) {
  return { stages: state.stages.map((s, j) => (j === i ? { ...s, ...patch } : s)), undo: null };
}

export function act(stages: Stage[], kind: Act, today: string): Stage[] {
  const i = cursor(stages);
  if (i < 0) return stages;
  return stages.map((s, j) => (j === i ? { ...s, status: kind, date: today || null } : s));
}

/** お辞儀: 最上位は 0°、担当に向けて −12° まで等分に傾ける(3段なら 担当−12°・課長−6°・部長0°) */
export const bowAngle = (i: number, n: number, bow: boolean) =>
  bow && n > 1 ? Math.round(((-12 * (n - 1 - i)) / (n - 1)) * 10) / 10 || 0 : 0;

/** 押した手の揺れ(段ごとに決まった小さな傾き) */
const JITTER = [1.5, -2, 1, -1.5, 2.5];

export const sealTextOf = (s: Stage) =>
  Array.from(s.seal.trim() || s.role.trim() || "印")
    .slice(0, 4)
    .join("");

export function reiwa(iso: string) {
  const [y, m, d] = iso.split("-").map(Number);
  return { y: y - 2018, m, d };
}
export const reiwaLong = (iso: string) => {
  if (!iso) return "";
  const r = reiwa(iso);
  return `令和${r.y === 1 ? "元" : r.y}年${r.m}月${r.d}日`;
};
export const reiwaShort = (iso: string) => {
  if (!iso) return "";
  const r = reiwa(iso);
  return `${r.y}.${r.m}.${r.d}`;
};

export const esc = (t: string) =>
  t.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");

const SEAL_FONT = "'Noto Serif JP','Yu Mincho','Hiragino Mincho ProN',serif";

/** かすれのフィルター3種(seed 違い)。id は `${prefix}-0`〜`-2` */
export function inkFilters(prefix: string) {
  return [3, 11, 27]
    .map(
      (seed, k) =>
        `<filter id="${prefix}-${k}" x="-15%" y="-15%" width="130%" height="130%" color-interpolation-filters="sRGB">` +
        `<feTurbulence type="fractalNoise" baseFrequency="0.55" numOctaves="2" seed="${seed}" result="n"/>` +
        `<feDisplacementMap in="SourceGraphic" in2="n" scale="1.3" xChannelSelector="R" yChannelSelector="G" result="d"/>` +
        `<feTurbulence type="fractalNoise" baseFrequency="0.22" numOctaves="2" seed="${seed + 5}" result="s"/>` +
        `<feColorMatrix in="s" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -3 2.4" result="m"/>` +
        `<feComposite in="d" in2="m" operator="in"/>` +
        `</filter>`,
    )
    .join("");
}

/**
 * 押印欄の1マス分の SVG(viewBox 60×60)。画面・HTML の書き出し・共有画像で同じものを使う。
 * pending は空、skipped は斜線(マス全体)、それ以外は朱の印。
 */
export function sealSvg(
  status: Status,
  text: string,
  iso: string,
  filter: string,
  opts: { size?: number | string; tilt?: number } = {},
) {
  const size = opts.size ?? "100%";
  if (status === "pending") return "";
  if (status === "skipped")
    return `<svg viewBox="0 0 60 60" width="${size}" height="${size}" preserveAspectRatio="none" role="img" aria-label="不要"><line x1="60" y1="0" x2="0" y2="60" stroke="#57534e" stroke-width="1" vector-effect="non-scaling-stroke"/></svg>`;
  const t = (x: number, y: number, fs: number, s: string, len?: number, weight = 700) =>
    `<text x="${x}" y="${y}" font-size="${fs}" font-weight="${weight}" text-anchor="middle" fill="${INK}" stroke="none" font-family="${SEAL_FONT}"${
      len ? ` textLength="${len}" lengthAdjust="spacingAndGlyphs"` : ""
    }>${esc(s)}</text>`;
  const rot = opts.tilt ? ` transform="rotate(${opts.tilt} 30 30)"` : "";
  let body: string;
  if (status === "rejected") {
    body =
      `<rect x="7" y="7" width="46" height="46" stroke-width="2.6"/>` +
      `<rect x="11" y="11" width="38" height="38" stroke-width="0.9"/>` +
      t(30, 41, 28, "否", undefined, 700);
  } else {
    const chars = Array.from(text).length;
    const top = chars <= 2 ? t(30, 19.5, 10.5, text) : t(30, 19.5, chars === 3 ? 9.5 : 8.5, text, chars === 3 ? 27 : 30);
    body =
      `<circle cx="30" cy="30" r="26.5" stroke-width="2.3"/>` +
      `<path d="M4.6 23.2H55.4M4.6 36.8H55.4" stroke-width="1.2"/>` +
      top +
      t(30, 33.4, 8.6, `令${reiwaShort(iso)}`, iso ? 38 : undefined, 600) +
      t(30, 48.5, 8.6, "承認");
    if (status === "proxy")
      body +=
        `<circle cx="52" cy="52" r="8.5" fill="#fff" stroke-width="1.7"/>` + t(52, 55.4, 9.5, "代");
  }
  return `<svg viewBox="0 0 60 60" width="${size}" height="${size}" overflow="visible" role="img" aria-label="${esc(
    `${text}・${LABEL[status]}${iso && status !== "rejected" ? `・${reiwaLong(iso)}` : ""}`,
  )}"><g filter="url(#${filter})" fill="none" stroke="${INK}"${rot}>${body}</g></svg>`;
}

/* ───────── 書き出すコード ───────── */

const BADGE_CLASS: Record<Status, string> = {
  pending: "border-stone-300 bg-white text-stone-600",
  approved: "border-emerald-700/30 bg-emerald-50 text-emerald-800",
  rejected: "border-red-700/30 bg-red-50 text-red-700",
  proxy: "border-emerald-700 bg-white text-emerald-800",
  skipped: "border-stone-200 bg-stone-100 text-stone-500",
};

export function buildTsx(stages: Stage[], today: string, bow: boolean) {
  const rows = stages
    .map((s) => {
      const st = statusOf(s);
      const parts = [`role: ${JSON.stringify(s.role || s.key)}`];
      if (s.seal.trim()) parts.push(`seal: ${JSON.stringify(sealTextOf(s))}`);
      parts.push(`status: "${st}"`);
      if (st !== "pending" && st !== "skipped") parts.push(`date: "${s.date ?? today}"`);
      return `  { ${parts.join(", ")} },`;
    })
    .join("\n");
  return `"use client";
import { useId } from "react";

// 承認状況を1つのコンポーネントで出し分ける。画面はステッパー、印刷は押印欄。
//   <ApprovalTrail steps={STEPS} variant="stepper" className="print:hidden" />
//   <ApprovalTrail steps={STEPS} variant="seal" bow={${bow}} className="hidden print:table" />
type Status = "pending" | "approved" | "rejected" | "proxy" | "skipped";
type Step = { role: string; seal?: string; status: Status; date?: string };

export const STEPS: Step[] = [
${rows}
];

const LABEL: Record<Status, string> = {
  pending: "承認待ち", approved: "承認", rejected: "差戻し", proxy: "代理承認", skipped: "不要",
};
const BADGE: Record<Status, string> = {
${(Object.keys(BADGE_CLASS) as Status[]).map((k) => `  ${k}: "${BADGE_CLASS[k]}",`).join("\n")}
};
const INK = "${INK}";
const reiwa = (iso: string) => {
  const [y, m, d] = iso.split("-").map(Number);
  return y - 2018 + "." + m + "." + d;
};

export function ApprovalTrail({ steps, variant, bow = false, className = "" }: {
  steps: Step[]; variant: "stepper" | "seal"; bow?: boolean; className?: string;
}) {
  if (variant === "stepper") {
    return (
      <ol className={"flex " + className}>
        {steps.map((s, i) => (
          <li key={i} className="flex min-w-0 flex-1 flex-col items-center gap-1 text-center">
            <span className="text-[13px] font-bold">{s.role}</span>
            <span className={"rounded-full border px-2 py-0.5 text-[11px] " + BADGE[s.status]}>{LABEL[s.status]}</span>
            <span className="text-[11px] tabular-nums text-stone-500">{s.date ? s.date.slice(5).replace("-", "/") : "—"}</span>
          </li>
        ))}
      </ol>
    );
  }
  // 押印欄は右から埋まる(担当が右端・上位者が左)。お辞儀は担当 −12° から最上位 0° まで等分
  const n = steps.length;
  const cells = steps.map((s, i) => ({ s, tilt: bow && n > 1 ? (-12 * (n - 1 - i)) / (n - 1) : 0 })).reverse();
  return (
    <table className={"border-collapse " + className}>
      <thead>
        <tr>{cells.map(({ s }, i) => <th key={i} className="w-16 border border-stone-400 py-0.5 text-[11px] font-medium">{s.role}</th>)}</tr>
      </thead>
      <tbody>
        <tr>
          {cells.map(({ s, tilt }, i) => (
            <td key={i} className="relative h-16 w-16 border border-stone-400 p-1">
              {s.status === "skipped" ? (
                <svg className="absolute inset-0 h-full w-full" viewBox="0 0 64 64" preserveAspectRatio="none" role="img" aria-label="不要">
                  <line x1="64" y1="0" x2="0" y2="64" stroke="#57534e" vectorEffect="non-scaling-stroke" />
                </svg>
              ) : s.status === "pending" ? null : (
                <Seal step={s} tilt={tilt} />
              )}
            </td>
          ))}
        </tr>
      </tbody>
    </table>
  );
}

function Seal({ step, tilt }: { step: Step; tilt: number }) {
  const id = "ink" + useId().replace(/[^\\w-]/g, "");
  const text = step.seal ?? step.role;
  const t = { fill: INK, stroke: "none", textAnchor: "middle" as const, fontFamily: "serif", fontWeight: 700 };
  return (
    <svg viewBox="0 0 60 60" className="h-full w-full overflow-visible" style={{ transform: "rotate(" + tilt + "deg)" }}
      role="img" aria-label={text + "・" + LABEL[step.status]}>
      <filter id={id} x="-15%" y="-15%" width="130%" height="130%">
        <feTurbulence type="fractalNoise" baseFrequency="0.55" numOctaves={2} result="n" />
        <feDisplacementMap in="SourceGraphic" in2="n" scale={1.3} xChannelSelector="R" yChannelSelector="G" result="d" />
        <feTurbulence type="fractalNoise" baseFrequency="0.22" numOctaves={2} seed={8} result="s" />
        <feColorMatrix in="s" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -3 2.4" result="m" />
        <feComposite in="d" in2="m" operator="in" />
      </filter>
      <g filter={"url(#" + id + ")"} fill="none" stroke={INK}>
        {step.status === "rejected" ? (
          <>
            <rect x="7" y="7" width="46" height="46" strokeWidth="2.6" />
            <rect x="11" y="11" width="38" height="38" strokeWidth="0.9" />
            <text x="30" y="41" fontSize="28" {...t} fontWeight={700}>否</text>
          </>
        ) : (
          <>
            <circle cx="30" cy="30" r="26.5" strokeWidth="2.3" />
            <path d="M4.6 23.2H55.4M4.6 36.8H55.4" strokeWidth="1.2" />
            <text x="30" y="19.5" fontSize="10" {...t}>{text}</text>
            <text x="30" y="33.4" fontSize="8.6" {...t}>{"令" + (step.date ? reiwa(step.date) : "")}</text>
            <text x="30" y="48.5" fontSize="8.6" {...t}>承認</text>
            {step.status === "proxy" && (
              <>
                <circle cx="52" cy="52" r="8.5" fill="#fff" strokeWidth="1.7" />
                <text x="52" y="55.4" fontSize="9.5" {...t}>代</text>
              </>
            )}
          </>
        )}
      </g>
    </svg>
  );
}
`;
}

const HTML_BADGE: Record<Status, string> = {
  pending: "border-color:#d6d3d1;color:#57534e;background:#fff",
  approved: "border-color:#04785766;color:#065f46;background:#ecfdf5",
  rejected: "border-color:#b91c1c55;color:#b91c1c;background:#fef2f2",
  proxy: "border-color:#047857;color:#065f46;background:#fff",
  skipped: "border-color:#e7e5e4;color:#78716c;background:#f5f5f4",
};

export function buildHtml(stages: Stage[], today: string, bow: boolean) {
  const n = stages.length;
  const steps = stages
    .map((s) => {
      const st = statusOf(s);
      const d = st === "pending" || st === "skipped" ? "—" : (s.date ?? today).slice(5).replace("-", "/");
      return `    <li><b>${esc(s.role || s.key)}</b><span class="ap-badge" data-s="${st}">${LABEL[st]}</span><small>${d}</small></li>`;
    })
    .join("\n");
  const rev = stages.map((s, i) => ({ s, i })).reverse();
  const heads = rev.map(({ s }) => `<th>${esc(s.role || s.key)}</th>`).join("");
  const cells = rev
    .map(({ s, i }) => {
      const st = statusOf(s);
      const svg = sealSvg(st, sealTextOf(s), s.date ?? today, `ap-ink-${i % 3}`, {
        tilt: bowAngle(i, n, bow) + (st === "skipped" ? 0 : JITTER[i]),
      });
      return `\n      <td data-s="${st}">${svg}</td>`;
    })
    .join("");
  return `<!-- 画面ではステッパー、印刷(@media print)では押印欄だけが出る1枚 -->
<style>
  .ap-steps { display: flex; margin: 0; padding: 0; list-style: none; font: 13px/1.5 "Noto Sans JP", sans-serif; }
  .ap-steps li { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 4px; min-width: 0; }
  .ap-badge { border: 1px solid; border-radius: 999px; padding: 1px 8px; font-size: 11px; }
${(Object.keys(HTML_BADGE) as Status[]).map((k) => `  .ap-badge[data-s="${k}"] { ${HTML_BADGE[k]}; }`).join("\n")}
  .ap-steps small { color: #78716c; font-variant-numeric: tabular-nums; }
  .ap-seal { display: none; margin-left: auto; border-collapse: collapse; }
  .ap-seal th, .ap-seal td { width: 64px; border: 1px solid #a8a29e; text-align: center; }
  .ap-seal th { padding: 2px 0; font: 500 11px "Noto Sans JP", sans-serif; }
  .ap-seal td { position: relative; height: 64px; padding: 4px; }
  .ap-seal td[data-s="skipped"] { padding: 0; }
  .ap-seal svg { display: block; }
  @media print {
    .ap-steps { display: none; }
    .ap-seal { display: table; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
  }
</style>
<svg width="0" height="0" style="position:absolute" aria-hidden="true"><defs>${inkFilters("ap-ink")}</defs></svg>
<ol class="ap-steps">
${steps}
</ol>
<table class="ap-seal">
  <thead><tr>${heads}</tr></thead>
  <tbody>
    <tr>${cells}
    </tr>
  </tbody>
</table>`;
}

/* ───────── 共有画像(1200×630) ───────── */

export function shareSvg(stages: Stage[], today: string, bow: boolean) {
  const W = 1200;
  const H = 630;
  const n = stages.length;
  const f = "'Noto Sans JP','Hiragino Sans','Yu Gothic',sans-serif";
  const txt = (x: number, y: number, fs: number, s: string, extra = "") =>
    `<text x="${x}" y="${y}" font-size="${fs}" font-family="${f}" ${extra}>${esc(s)}</text>`;
  const col = { pending: "#78716c", approved: "#065f46", rejected: "#b91c1c", proxy: "#065f46", skipped: "#78716c" };
  const bg = { pending: "#fff", approved: "#ecfdf5", rejected: "#fef2f2", proxy: "#fff", skipped: "#f5f5f4" };
  const stroke = { pending: "#d6d3d1", approved: "#a7d7c5", rejected: "#efb4b4", proxy: "#047857", skipped: "#e7e5e4" };
  const cur = cursor(stages);
  // ステッパー(上段)
  const x0 = 140;
  const span = n > 1 ? (W - 2 * x0) / (n - 1) : 0;
  let stepper = "";
  stages.forEach((s, i) => {
    const st = statusOf(s);
    const x = n > 1 ? x0 + span * i : W / 2;
    if (i < n - 1) {
      const done = st !== "pending" && st !== "rejected";
      stepper += `<line x1="${x + 24}" y1="196" x2="${x + span - 24}" y2="196" stroke="${done ? "#d97706" : "#d6d3d1"}" stroke-width="${done ? 2 : 1}"/>`;
    }
    const isCur = i === cur;
    stepper += `<rect x="${x - 17}" y="179" width="34" height="34" fill="#fff" stroke="${isCur ? "#d97706" : "#a8a29e"}" stroke-width="${isCur ? 2 : 1}"/>`;
    stepper += txt(x, 202, 15, st === "approved" ? "✓" : st === "rejected" ? "↩" : st === "proxy" ? "代" : st === "skipped" ? "—" : String(i + 1), `text-anchor="middle" font-weight="700" fill="${isCur ? "#b45309" : "#44403c"}"`);
    stepper += txt(x, 244, 19, s.role || s.key, `text-anchor="middle" font-weight="700" fill="#1c1917"`);
    const label = isCur ? "承認待ち(次)" : LABEL[st];
    const bw = Array.from(label).length * 14 + 26;
    stepper += `<rect x="${x - bw / 2}" y="256" width="${bw}" height="26" rx="13" fill="${isCur ? "#fffbeb" : bg[st]}" stroke="${isCur ? "#d97706" : stroke[st]}"/>`;
    stepper += txt(x, 274, 14, label, `text-anchor="middle" fill="${isCur ? "#92400e" : col[st]}"`);
    const d = st === "pending" || st === "skipped" ? "—" : (s.date ?? today).slice(5).replace("-", "/");
    stepper += txt(x, 304, 14, d, `text-anchor="middle" fill="#78716c"`);
  });
  // 押印欄(下段・右から埋まる)
  const cell = 96;
  const tw = cell * n;
  const tx = (W - tw) / 2;
  const ty = 380;
  let seals = `<rect x="${tx}" y="${ty}" width="${tw}" height="${cell + 28}" fill="#fff" stroke="#a8a29e"/>`;
  seals += `<line x1="${tx}" y1="${ty + 28}" x2="${tx + tw}" y2="${ty + 28}" stroke="#a8a29e"/>`;
  stages
    .map((s, i) => ({ s, i }))
    .reverse()
    .forEach(({ s, i }, k) => {
      const cx = tx + cell * k;
      if (k > 0) seals += `<line x1="${cx}" y1="${ty}" x2="${cx}" y2="${ty + cell + 28}" stroke="#a8a29e"/>`;
      seals += txt(cx + cell / 2, ty + 20, 14, s.role || s.key, `text-anchor="middle" fill="#292524"`);
      const st = statusOf(s);
      const inner = sealSvg(st, sealTextOf(s), s.date ?? today, `sh-ink-${i % 3}`, {
        size: st === "skipped" ? cell : cell - 14,
        tilt: bowAngle(i, n, bow) + (st === "skipped" ? 0 : JITTER[i]),
      });
      const off = st === "skipped" ? 0 : 7;
      if (inner) seals += `<g transform="translate(${cx + off} ${ty + 28 + off})">${inner}</g>`;
    });
  const title = phase(stages) === "done" ? "決裁済み" : phase(stages) === "halted" ? "差戻し" : `${cur + 1}/${n}段目の承認待ち`;
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">
<defs>${inkFilters("sh-ink")}</defs>
<rect width="${W}" height="${H}" fill="#fff"/>
<rect x="24.5" y="24.5" width="${W - 49}" height="${H - 49}" fill="none" stroke="#e7e5e4"/>
<rect x="24" y="24" width="6" height="64" fill="#d97706"/>
${txt(60, 66, 15, "BLK-110", `font-weight="600" letter-spacing="3" fill="#78716c"`)}
${txt(60, 108, 32, "画面はステッパー、印刷すると押印欄", `font-weight="700" fill="#1c1917"`)}
${txt(W - 60, 66, 16, title, `text-anchor="end" font-weight="700" fill="#b45309"`)}
${txt(60, 160, 14, "画面", `font-weight="700" fill="#78716c" letter-spacing="2"`)}
${stepper}
<line x1="60" y1="340" x2="${W - 60}" y2="340" stroke="#e7e5e4"/>
${txt(60, 372, 14, "印刷", `font-weight="700" fill="#78716c" letter-spacing="2"`)}
${seals}
<g transform="rotate(-16 600 330)" opacity="0.12">${txt(600, 390, 190, "見本", `text-anchor="middle" font-weight="700" fill="#d97706"`)}</g>
${txt(W - 60, 590, 14, "designs.first-ch.com", `text-anchor="end" fill="#a8a29e" letter-spacing="1"`)}
</svg>`;
}

/* ───────── 画面 ───────── */

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

const noop = () => () => {};
const todayIso = () => {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
};
const md = (iso: string) => (iso ? `${Number(iso.slice(5, 7))}月${Number(iso.slice(8))}日` : "—");

function Icon({ st, n, current }: { st: Status; n: number; current: boolean }) {
  const c = "h-3.5 w-3.5";
  if (st === "approved")
    return (
      <svg viewBox="0 0 16 16" className={c} aria-hidden="true">
        <path d="M3 8.5l3.2 3L13 4.5" fill="none" stroke="currentColor" strokeWidth="2" />
      </svg>
    );
  if (st === "rejected")
    return (
      <svg viewBox="0 0 16 16" className={c} aria-hidden="true">
        <path d="M6 3.5L2.5 7 6 10.5M3 7h6.5a3.5 3.5 0 010 7H7" fill="none" stroke="currentColor" strokeWidth="1.8" />
      </svg>
    );
  if (st === "proxy") return <span className="text-[12px] font-bold leading-none">代</span>;
  if (st === "skipped")
    return (
      <svg viewBox="0 0 16 16" className={c} aria-hidden="true">
        <path d="M3 8h10" stroke="currentColor" strokeWidth="1.8" />
      </svg>
    );
  if (current)
    return (
      <svg viewBox="0 0 16 16" className={c} aria-hidden="true">
        <circle cx="8" cy="8" r="5.6" fill="none" stroke="currentColor" strokeWidth="1.6" />
        <path d="M8 5v3.3l2.2 1.4" fill="none" stroke="currentColor" strokeWidth="1.6" />
      </svg>
    );
  return <span className="font-display text-[12px] font-semibold leading-none">{n}</span>;
}

function Badge({ st, current, className = "" }: { st: Status; current?: boolean; className?: string }) {
  return (
    <span
      className={`inline-flex items-center whitespace-nowrap rounded-full border px-2 py-0.5 text-[11.5px] font-medium leading-[1.4] ${
        current ? "border-[#d97706] bg-amber-50 text-amber-800" : BADGE_CLASS[st]
      } ${className}`}
    >
      {LABEL[st]}
    </span>
  );
}

const LINKS = [
  { slug: "status-badge", code: "BDG-01", name: "ステータスバッジ", note: "状態を1つだけ示す小さな札" },
  { slug: "toast-undo-notice", code: "BLK-87", name: "トースト通知", note: "取り消しつきの一時的な知らせ" },
  { slug: "contact-form-block", code: "BLK-12", name: "お問い合わせフォーム", note: "入力と送信の基本形" },
  { slug: "press-depth-button", code: "BTN-02", name: "押し込みボタン", note: "押した手応えを出すボタン" },
];

export default function HankoApprovalStamp({
  headingTag: Heading = "h2",
}: {
  headingTag?: "h1" | "h2" | "p";
}) {
  const uid = useId();
  const fid = `hk${uid.replace(/[^\w-]/g, "")}`;
  const today = useSyncExternalStore(noop, todayIso, () => "");
  const [stages, setStages] = useState<Stage[]>(INITIAL);
  const [bow, setBow] = useState(false);
  const [preview, setPreview] = useState(false);
  const [undo, setUndo] = useState<{ id: number; prev: Stage[]; what: string } | null>(null);
  const [msg, setMsg] = useState("");
  const [tab, setTab] = useState<"tsx" | "html">("tsx");
  const [copied, setCopied] = useState<{ tab: string; code: string; ok: boolean } | null>(null);
  const [png, setPng] = useState<{ url: string; key: string } | null>(null);
  const rootRef = useRef<HTMLElement>(null);
  const badgeEls = useRef<(HTMLElement | null)[]>([]);
  const sealEls = useRef<(HTMLElement | null)[]>([]);
  const codeRef = useRef<HTMLTextAreaElement>(null);
  const undoSeq = useRef(0);

  const n = stages.length;
  const cur = cursor(stages);
  const ph = phase(stages);
  const curRole = cur >= 0 ? stages[cur].role || stages[cur].key : "";
  const tsx = useMemo(() => buildTsx(stages, today, bow), [stages, today, bow]);
  const html = useMemo(() => buildHtml(stages, today, bow), [stages, today, bow]);
  const code = tab === "tsx" ? tsx : html;
  const shareKey = JSON.stringify([stages, bow, today]);
  const statusLine = statusLineOf(stages);

  // 印刷の対象はこの1つだけ(ギャラリー一覧の縮小版=inert の中は印刷に関わらない)
  useEffect(() => {
    const el = rootRef.current;
    if (el) el.dataset.hkPrint = el.closest("[inert]") ? "off" : "on";
  }, []);

  // 取り消しは5秒だけ出す
  useEffect(() => {
    if (!undo) return;
    const t = window.setTimeout(() => setUndo(null), 5000);
    return () => window.clearTimeout(t);
  }, [undo]);

  // 書き出した画像の URL は差し替え・破棄で解放する
  useEffect(() => {
    if (!png) return;
    return () => URL.revokeObjectURL(png.url);
  }, [png]);

  const commit = (next: Stage[], what: string) => {
    undoSeq.current += 1;
    setUndo({ id: undoSeq.current, prev: stages, what });
    setStages(next);
    setMsg(what);
  };

  const doAct = (kind: Act) => {
    if (cur < 0) return;
    const date = reiwaLong(today);
    const what =
      kind === "approved"
        ? `${curRole}を承認しました${date ? `(${date})` : ""}`
        : kind === "proxy"
          ? `${curRole}を代理で承認しました${date ? `(${date})` : ""}`
          : `${curRole}で差し戻しました。以降の段は止まります`;
    commit(act(stages, kind, today), what);
  };

  const doUndo = () => {
    if (!undo) return;
    setStages(undo.prev);
    setUndo(null);
    setMsg("直前の操作を取り消しました");
  };

  const reset = () =>
    commit(
      stages.map((s) => ({ ...s, status: "pending", date: null })),
      "全段を承認待ちに戻しました",
    );

  const setCount = (c: number) => {
    if (c === n) return;
    setStages(makeStages(c, stages));
    setUndo(null);
    setMsg(`${c}段にしました`);
  };

  const edit = (i: number, patch: Partial<Stage>) => {
    const next = editStage({ stages, undo }, i, patch);
    setStages(next.stages);
    setUndo(next.undo);
  };

  // バッジ ⇄ 印の組み替え(FLIP・140ms)
  const togglePreview = () => {
    const next = !preview;
    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const from = (next ? badgeEls : sealEls).current.slice(0, n).map((el) => el?.getBoundingClientRect() ?? null);
    flushSync(() => setPreview(next));
    setMsg(next ? "印刷プレビュー: 押印欄に組み替えました" : "画面の表示(ステッパー)に戻しました");
    if (reduced) return;
    (next ? sealEls : badgeEls).current.slice(0, n).forEach((el, i) => {
      const a = from[i];
      if (!el || !a || !a.width) return;
      const b = el.getBoundingClientRect();
      if (!b.width || !b.height) return;
      const dx = a.left + a.width / 2 - (b.left + b.width / 2);
      const dy = a.top + a.height / 2 - (b.top + b.height / 2);
      el.style.transition = "none";
      el.style.transform = `translate(${dx}px, ${dy}px) scale(${a.width / b.width}, ${a.height / b.height})`;
      el.style.opacity = "0.35";
      void el.offsetWidth;
      el.style.transition = "transform 140ms cubic-bezier(.2,.7,.2,1), opacity 140ms linear";
      el.style.transform = "";
      el.style.opacity = "";
    });
  };

  const onKey = (e: KeyboardEvent<HTMLElement>) => {
    const tag = (e.target as HTMLElement).tagName;
    if (tag === "INPUT" || tag === "TEXTAREA") return;
    if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "z" && undo) {
      e.preventDefault();
      doUndo();
    }
  };

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(code);
      setCopied({ tab, code, ok: true });
    } catch {
      codeRef.current?.select();
      setCopied({ tab, code, ok: false });
    }
  };
  const copyState = copied && copied.tab === tab && copied.code === code ? (copied.ok ? "ok" : "fail") : null;

  const savePng = () => {
    const svg = shareSvg(stages, today, bow);
    const img = new Image();
    const src = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" }));
    img.onload = () => {
      const c = document.createElement("canvas");
      c.width = 1200;
      c.height = 630;
      const ctx = c.getContext("2d");
      if (!ctx) return;
      ctx.drawImage(img, 0, 0);
      URL.revokeObjectURL(src);
      c.toBlob((blob) => {
        if (!blob) return;
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = "approval-stamp-sample.png";
        a.click();
        setPng({ url, key: shareKey });
        setMsg("見本の画像(1200×630)を保存しました");
      }, "image/png");
    };
    img.onerror = () => {
      URL.revokeObjectURL(src);
      setMsg("画像を作れませんでした");
    };
    img.src = src;
  };

  const tabKey = (e: KeyboardEvent<HTMLButtonElement>) => {
    if (e.key !== "ArrowRight" && e.key !== "ArrowLeft") return;
    e.preventDefault();
    const next = tab === "tsx" ? "html" : "tsx";
    setTab(next);
    document.getElementById(`${uid}-tab-${next}`)?.focus();
  };

  const actBtn = `inline-flex min-h-11 items-center gap-1.5 border px-3.5 text-[14px] font-bold transition-[transform] active:scale-[0.97] disabled:cursor-not-allowed disabled:opacity-40 disabled:active:scale-100 motion-reduce:transition-none ${focusRing}`;

  return (
    <section
      ref={rootRef}
      onKeyDown={onKey}
      className="hk-root mx-auto w-full max-w-6xl border border-stone-200 bg-white text-stone-900"
      aria-labelledby={`${uid}-h`}
    >
      <style>{PRINT_CSS}</style>
      <svg width="0" height="0" className="hk-defs absolute" aria-hidden="true">
        <defs dangerouslySetInnerHTML={{ __html: inkFilters(fid) }} />
      </svg>

      {/* 見出し */}
      <div className="flex flex-wrap items-end justify-between gap-x-6 gap-y-1 px-4 pb-3 pt-4 sm:px-6">
        <div>
          <p className="font-display text-[11px] font-semibold tracking-[0.18em] text-stone-500">BLK-110</p>
          <Heading id={`${uid}-h`} className="mt-1 text-[1.05rem] font-bold leading-[1.5] [word-break:keep-all] sm:text-[1.3rem]">
            印刷すると押印欄に切り替わる
            <wbr />
            承認ステッパー
          </Heading>
        </div>
        <p className="text-[12.5px] text-stone-600">
          状態:{" "}
          <strong className={`font-bold ${ph === "halted" ? "text-red-700" : ph === "done" ? "text-emerald-800" : "text-amber-800"}`}>
            {statusLine}
          </strong>
        </p>
      </div>

      <div className="grid border-t border-stone-200 lg:grid-cols-[minmax(0,1fr)_21rem]">
        {/* 操作と表示 */}
        <div className="min-w-0 px-4 pb-5 pt-3 sm:px-6">
          <div className="flex flex-wrap items-center gap-2">
            <button type="button" className={`act-approve ${actBtn} border-stone-900 bg-stone-900 text-white hover:bg-amber-800`} disabled={cur < 0} onClick={() => doAct("approved")}>
              承認
            </button>
            <button type="button" className={`act-reject ${actBtn} border-red-700/50 bg-white text-red-700 hover:bg-red-50`} disabled={cur < 0} onClick={() => doAct("rejected")}>
              差戻し
            </button>
            <button type="button" className={`act-proxy ${actBtn} border-stone-300 bg-white text-stone-800 hover:border-stone-500`} disabled={cur < 0} onClick={() => doAct("proxy")}>
              代理承認
            </button>
            {undo && (
              <button
                key={undo.id}
                type="button"
                onClick={doUndo}
                className={`act-undo relative inline-flex min-h-11 items-center overflow-hidden border border-[#d97706] bg-amber-50 px-3 text-[13px] font-bold text-amber-900 ${focusRing}`}
              >
                取り消す
                <span className="hk-count absolute inset-x-0 bottom-0 h-0.5 origin-left bg-[#d97706] motion-reduce:hidden" aria-hidden="true" />
              </button>
            )}
            <button type="button" onClick={reset} className={`act-reset ml-auto inline-flex min-h-11 items-center px-2 text-[13px] text-stone-600 underline decoration-stone-300 underline-offset-4 hover:text-stone-900 ${focusRing}`}>
              最初から
            </button>
          </div>
          <p className="mt-1.5 min-h-[1.2em] text-[12px] text-stone-500">
            {cur >= 0 ? (
              <>
                ボタンは<strong className="font-bold text-stone-800">{curRole}</strong>の段に適用されます。押してから5秒間は取り消せます(Ctrl+Z / ⌘Z)
              </>
            ) : (
              "これ以上進める段はありません。「最初から」で戻せます"
            )}
          </p>

          <div className="hk-stage mt-2 grid min-h-[13.5rem] border border-stone-200 bg-[radial-gradient(#e7e5e4_1px,transparent_1px)] [background-size:14px_14px]">
            {/* 画面=ステッパー */}
            <div
              className={`[grid-area:1/1] flex items-center px-2 py-6 sm:px-6 ${preview ? "invisible opacity-0 transition-[opacity,visibility] duration-[140ms] motion-reduce:transition-none" : "visible opacity-100"}`}
              aria-hidden={preview}
              inert={preview}
            >
              <ol className="flex w-full" aria-label="承認の段(画面の表示)">
                {stages.map((s, i) => {
                  const st = statusOf(s);
                  const isCur = i === cur;
                  const passed = st === "approved" || st === "proxy" || st === "skipped";
                  return (
                    <li key={s.key} className="relative flex min-w-0 flex-1 flex-col items-center text-center" aria-current={isCur ? "step" : undefined}>
                      {i < n - 1 && (
                        <span
                          aria-hidden="true"
                          className={`absolute left-[calc(50%+18px)] right-[calc(-50%+18px)] top-[15px] h-px ${passed ? "bg-[#d97706]" : "bg-stone-300"}`}
                        />
                      )}
                      <span
                        className={`grid h-[30px] w-[30px] place-items-center border bg-white ${
                          isCur
                            ? "border-[#d97706] text-amber-700 outline outline-2 outline-offset-2 outline-amber-200"
                            : st === "approved" || st === "proxy"
                              ? "border-emerald-700 text-emerald-800"
                              : st === "rejected"
                                ? "border-red-700 text-red-700"
                                : "border-stone-300 text-stone-500"
                        }`}
                      >
                        <Icon st={st} n={i + 1} current={isCur} />
                      </span>
                      <span className="mt-2 max-w-full truncate px-0.5 text-[13.5px] font-bold">{s.role || s.key}</span>
                      <span ref={(el) => { badgeEls.current[i] = el; }} className="mt-1.5 inline-block">
                        <Badge st={st} current={isCur} />
                      </span>
                      <span className="mt-1 font-display text-[11.5px] tabular-nums text-stone-500">
                        {st === "pending" || st === "skipped" ? "—" : md(s.date ?? today)}
                      </span>
                    </li>
                  );
                })}
              </ol>
            </div>

            {/* 印刷=押印欄 */}
            <div
              className={`[grid-area:1/1] flex items-center justify-center px-2 py-4 ${preview ? "visible opacity-100" : "invisible opacity-0 transition-[opacity,visibility] duration-[140ms] motion-reduce:transition-none"}`}
              aria-hidden={!preview}
              inert={!preview}
            >
              <div className="hk-sheet w-full max-w-[34rem] border border-stone-300 bg-white px-4 py-3 shadow-[0_1px_0_#e7e5e4,0_8px_24px_-16px_rgba(28,25,23,0.35)] sm:px-5">
                <div className="flex items-baseline justify-between gap-3 border-b border-stone-200 pb-1.5 text-[11.5px] text-stone-600">
                  <span className="font-bold text-stone-900">稟議書(見本)</span>
                  <span className="tabular-nums">起案 {reiwaLong(stages[0].date ?? today) || "—"}</span>
                </div>
                <table className="ml-auto mt-3 border-collapse" aria-label="押印欄(右から担当→上位者)">
                  <thead>
                    <tr>
                      {stages
                        .map((s, i) => ({ s, i }))
                        .reverse()
                        .map(({ s }) => (
                          <th key={s.key} scope="col" className="w-[3.6rem] border border-stone-400 px-0.5 py-0.5 text-[11px] font-medium sm:w-[4.75rem]">
                            {s.role || s.key}
                          </th>
                        ))}
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      {stages
                        .map((s, i) => ({ s, i }))
                        .reverse()
                        .map(({ s, i }) => {
                          const st = statusOf(s);
                          const tilt = bowAngle(i, n, bow);
                          return (
                            <td key={s.key} className="relative h-[3.6rem] w-[3.6rem] border border-stone-400 p-0 sm:h-[4.75rem] sm:w-[4.75rem]">
                              <span
                                ref={(el) => { sealEls.current[i] = el; }}
                                className={`absolute grid place-items-center ${st === "skipped" ? "inset-0" : "inset-[3px]"}`}
                              >
                                <span
                                  className="block h-full w-full transition-transform duration-200 motion-reduce:transition-none"
                                  style={{ transform: st === "skipped" ? undefined : `rotate(${tilt + JITTER[i]}deg)` }}
                                  dangerouslySetInnerHTML={{ __html: sealSvg(st, sealTextOf(s), s.date ?? today, `${fid}-${i % 3}`) }}
                                />
                              </span>
                            </td>
                          );
                        })}
                    </tr>
                  </tbody>
                </table>
                <p className="mt-2 text-right text-[11px] text-stone-500">
                  {ph === "done" ? "決裁済み" : ph === "halted" ? "差戻し" : `${curRole}の承認待ち`}
                  {bow && "・お辞儀あり"}
                </p>
              </div>
            </div>
          </div>
          {/* 表示の切り替え */}
          <div className="mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
            <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
              <button
                type="button"
                aria-pressed={preview}
                onClick={togglePreview}
                className={`act-preview inline-flex min-h-11 items-center gap-2 border px-3.5 text-[14px] font-bold ${preview ? "border-[#d97706] bg-[#d97706] text-white" : "border-stone-900 bg-white text-stone-900 hover:bg-stone-50"} ${focusRing}`}
              >
                <svg viewBox="0 0 16 16" className="h-4 w-4" aria-hidden="true">
                  <path d="M4 6V2h8v4M4 12H2.5V6.5h11V12H12M4.5 9.5h7V14h-7z" fill="none" stroke="currentColor" strokeWidth="1.3" />
                </svg>
                {preview ? "画面の表示に戻す" : "印刷プレビュー"}
              </button>
              <label className="has-[:focus-visible]:outline has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-[#d97706] inline-flex min-h-11 cursor-pointer items-center gap-2 text-[13.5px]">
                <input type="checkbox" className="bow h-4 w-4 accent-[#d97706]" checked={bow} onChange={(e) => setBow(e.target.checked)} />
                お辞儀(下位の印を左へ傾ける)
              </label>
            </div>
            <p className="text-[12px] text-stone-500">Ctrl+P(⌘P)で印刷すると押印欄だけが出ます</p>
          </div>

          <p role="status" className="mt-2 min-h-[1.3em] text-[12.5px] text-stone-700">
            {msg}
          </p>
        </div>

        {/* 対応表 */}
        <div className="border-t border-stone-200 px-4 pb-5 pt-3 sm:px-6 lg:border-l lg:border-t-0">
          <h3 className="text-[13.5px] font-bold">5つの状態と2つの見た目</h3>
          <table className="mt-2 w-full border-collapse text-left text-[12px]">
            <thead>
              <tr className="border-b border-stone-200 text-[11px] text-stone-500">
                <th scope="col" className="py-1 pr-2 font-medium">状態</th>
                <th scope="col" className="py-1 pr-2 font-medium">画面</th>
                <th scope="col" className="py-1 font-medium">印刷</th>
              </tr>
            </thead>
            <tbody>
              {STATES.map((s, k) => (
                <tr key={s.id} className="border-b border-stone-100 align-middle last:border-0">
                  <th scope="row" className="py-2 pr-2 text-[12.5px] font-bold">
                    {s.label}
                    <span className="block text-[11px] font-normal leading-snug text-stone-500">{s.paper}</span>
                  </th>
                  <td className="py-2 pr-2">
                    <Badge st={s.id} />
                  </td>
                  <td className="py-2">
                    <span className="relative block h-11 w-11 border border-stone-300">
                      <span
                        className={`absolute ${s.id === "skipped" ? "inset-0" : "inset-[3px]"} block`}
                        dangerouslySetInnerHTML={{ __html: sealSvg(s.id, "課長", today, `${fid}-${k % 3}`) }}
                      />
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          <p className="mt-2 text-[11.5px] leading-relaxed text-stone-500">
            押印欄は右端が担当、左へ行くほど上位者。差戻しの段から先は空欄のまま止まります。
          </p>
        </div>
      </div>

      {/* 設定とコード */}
      <div className="grid border-t border-stone-200 lg:grid-cols-[19rem_minmax(0,1fr)]">
        <fieldset className="min-w-0 px-4 pb-5 pt-3 sm:px-6">
          <legend className="sr-only">段の設定</legend>
          <h3 className="text-[13.5px] font-bold" aria-hidden="true">段の設定</h3>
          <div role="radiogroup" aria-label="段数" className="mt-2 flex">
            {[2, 3, 4, 5].map((c) => (
              <label
                key={c}
                className={`count-${c} -ml-px flex min-h-11 flex-1 cursor-pointer items-center justify-center border text-[13.5px] first:ml-0 has-[:focus-visible]:z-10 has-[:focus-visible]:outline has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-[#d97706] ${
                  c === n ? "z-[1] border-stone-900 bg-stone-900 text-white" : "border-stone-300 bg-white hover:bg-stone-50"
                }`}
              >
                <input type="radio" name={`${uid}-count`} className="sr-only" checked={c === n} onChange={() => setCount(c)} />
                <span className="font-display font-semibold">{c}</span>段
              </label>
            ))}
          </div>
          <div className="mt-3 grid grid-cols-[1.2rem_minmax(0,1fr)_minmax(0,1fr)_auto] items-center gap-x-2 gap-y-1.5 text-[12px]">
            <span aria-hidden="true" />
            <span className="text-[11px] text-stone-500">役職名</span>
            <span className="text-[11px] text-stone-500">印の文字</span>
            <span className="text-[11px] text-stone-500">不要</span>
            {stages.map((s, i) => (
              <div key={s.key} className="contents">
                <span className="font-display text-[11px] font-semibold text-stone-400">{i + 1}</span>
                <input
                  aria-label={`${i + 1}段目の役職名`}
                  value={s.role}
                  maxLength={5}
                  onChange={(e) => edit(i, { role: e.target.value })}
                  className={`role-input h-10 w-full min-w-0 border border-stone-300 px-2 text-[16px] ${focusRing}`}
                />
                <input
                  aria-label={`${i + 1}段目の印の文字(空なら役職名)`}
                  value={s.seal}
                  placeholder={Array.from(s.role || s.key).slice(0, 4).join("")}
                  maxLength={4}
                  onChange={(e) => edit(i, { seal: e.target.value })}
                  className={`seal-input h-10 w-full min-w-0 border border-stone-300 px-2 text-[16px] placeholder:text-stone-400 ${focusRing}`}
                />
                <input
                  type="checkbox"
                  aria-label={`${i + 1}段目は不要`}
                  checked={s.skip}
                  onChange={(e) => edit(i, { skip: e.target.checked })}
                  className={`skip-input h-4 w-4 justify-self-center accent-[#d97706] ${focusRing}`}
                />
              </div>
            ))}
          </div>
        </fieldset>

        <div className="min-w-0 border-t border-stone-200 px-4 pb-5 pt-3 sm:px-6 lg:border-l lg:border-t-0">
          <div className="flex flex-wrap items-end justify-between gap-2">
            <div role="tablist" aria-label="コードの種類" className="flex border-b border-stone-200">
              {(
                [
                  ["tsx", "React(TSX)"],
                  ["html", "HTML+CSS"],
                ] as const
              ).map(([id, label]) => (
                <button
                  key={id}
                  id={`${uid}-tab-${id}`}
                  role="tab"
                  type="button"
                  aria-selected={tab === id}
                  aria-controls={`${uid}-panel`}
                  tabIndex={tab === id ? 0 : -1}
                  onClick={() => setTab(id)}
                  onKeyDown={tabKey}
                  className={`tab-${id} -mb-px min-h-11 border-b-2 px-3 text-[13.5px] font-bold ${tab === id ? "border-[#d97706] text-stone-900" : "border-transparent text-stone-500 hover:text-stone-800"} ${focusRing}`}
                >
                  {label}
                </button>
              ))}
            </div>
            <button
              type="button"
              onClick={copy}
              className={`copy-code inline-flex min-h-11 items-center bg-stone-900 px-3.5 text-[13.5px] font-bold text-white hover:bg-amber-800 ${focusRing}`}
            >
              {copyState === "ok" ? "コピーしました" : "コードをコピー"}
            </button>
          </div>
          <div id={`${uid}-panel`} role="tabpanel" aria-labelledby={`${uid}-tab-${tab}`}>
            <textarea
              ref={codeRef}
              readOnly
              value={code}
              spellCheck={false}
              aria-label={tab === "tsx" ? "React(TSX)のコード" : "HTML+CSS のコード"}
              className={`mt-2 block h-[19rem] w-full resize-y border border-stone-200 bg-stone-50 p-2.5 font-mono text-[12px] leading-relaxed text-stone-800 ${focusRing}`}
            />
          </div>
          <p className="mt-1.5 min-h-[1.2em] text-[12px] text-stone-500" aria-live="polite">
            {copyState === "fail"
              ? "コピーできませんでした。欄の内容を選択したので、Ctrl+C(⌘C)でコピーしてください"
              : tab === "tsx"
                ? `今の状態(${n}段${bow ? "・お辞儀あり" : ""})を STEPS に入れています。variant="stepper" | "seal" で出し分けます`
                : "1枚の HTML で、印刷すると @media print でステッパーが消えて押印欄が出ます"}
          </p>
        </div>
      </div>

      {/* 共有 */}
      <div className="grid gap-x-6 gap-y-3 border-t border-stone-200 px-4 pb-5 pt-3 sm:px-6 md:grid-cols-[minmax(0,1fr)_minmax(0,22rem)]">
        <div>
          <h3 className="text-[13.5px] font-bold">見本の画像にする</h3>
          <p className="mt-1 text-[12.5px] leading-relaxed text-stone-600">
            ステッパーと押印欄を上下に並べ、中央に「見本」の透かしを入れた 1200×630 の PNG を保存します。仕様の説明や社内の共有に。
          </p>
          <button
            type="button"
            onClick={savePng}
            className={`save-png mt-2 inline-flex min-h-11 items-center border border-stone-900 bg-white px-3.5 text-[13.5px] font-bold hover:bg-stone-50 ${focusRing}`}
          >
            画像を保存(PNG)
          </button>
        </div>
        {png && (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={png.url}
            alt="保存した見本の画像(ステッパーと押印欄)"
            width={1200}
            height={630}
            className={`share-thumb h-auto w-full border border-stone-200 ${png.key === shareKey ? "" : "opacity-50"}`}
          />
        )}
      </div>

      {/* 関連する部品 */}
      <nav aria-label="関連する部品" className="border-t border-stone-200 px-4 pb-4 pt-3 sm:px-6">
        <h3 className="text-[13.5px] font-bold">関連するステータス・フォーム・ボタン部品</h3>
        <ul className="mt-2 grid gap-x-6 sm:grid-cols-2 lg:grid-cols-4">
          {LINKS.map((l) => (
            <li key={l.slug} className="border-t border-stone-100 first:border-0 sm:border-0">
              <a href={`/d/${l.slug}`} className={`group block py-2 ${focusRing}`}>
                <span className="font-display text-[10.5px] font-semibold tracking-[0.14em] text-stone-400">{l.code}</span>
                <span className="block text-[13.5px] font-bold underline decoration-stone-300 underline-offset-4 group-hover:decoration-[#d97706]">
                  {l.name}
                </span>
                <span className="block text-[11.5px] text-stone-500">{l.note}</span>
              </a>
            </li>
          ))}
        </ul>
        <p className="mt-3 text-[11px] text-stone-400">役職・印影・稟議書は架空の見本です。保存や承認ルートの分岐は扱いません。</p>
      </nav>
    </section>
  );
}

const PRINT_CSS = `
.hk-count { animation: hk-count 5s linear forwards; }
@keyframes hk-count { from { transform: scaleX(1); } to { transform: scaleX(0); } }
@media (prefers-reduced-motion: reduce) { .hk-count { animation: none; } }
@media print {
  body:has(.hk-root[data-hk-print="on"]) *:not(:has(.hk-root[data-hk-print="on"])):not(.hk-root[data-hk-print="on"]):not(.hk-root[data-hk-print="on"] *) { display: none !important; }
  .hk-root[data-hk-print="on"] *:not(.hk-sheet):not(.hk-sheet *):not(:has(.hk-sheet)):not(.hk-defs):not(.hk-defs *) { display: none !important; }
  body:has(.hk-root[data-hk-print="on"]) :has(.hk-root[data-hk-print="on"]), .hk-root[data-hk-print="on"], .hk-root[data-hk-print="on"] :has(.hk-sheet) {
    margin: 0 !important; padding: 0 !important; border: 0 !important; box-shadow: none !important; background: none !important;
    min-height: 0 !important; max-width: none !important; transform: none !important; display: block !important;
    visibility: visible !important; opacity: 1 !important;
  }
  .hk-root[data-hk-print="on"] .hk-sheet { visibility: visible !important; opacity: 1 !important; max-width: 40rem; margin: 0 0 0 auto !important; box-shadow: none !important; }
  .hk-root[data-hk-print="on"] .hk-sheet, .hk-root[data-hk-print="on"] .hk-sheet * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
}
`;

shadcn CLI でプロジェクトに追加

npx shadcn@latest add https://designs.first-ch.com/r/hanko-approval-stamp.json