/* global React, ReactDOM */
const { useState, useMemo } = React;

const CONTACT_URL = "contact.html";
const ARTICLE_URL = "knowledge-training-subsidy.html";

const COURSES = [
  { id: 1, name: "生成AI＆DX即戦力講座", hours: 14, price: 400000 },
  { id: 2, name: "生成AI基礎＆自走人材育成研修", hours: 10, price: 360000, warn: "8月改正後は、基礎的な内容が対象外と判断されると10時間を下回り、研修全体が不支給になるおそれがあります" },
  { id: 11, group: "職種別AI研修シリーズ（全9講座・各11時間）", name: "生成AI×営業実務研修", role: "営業・営業企画", hours: 11, price: 360000 },
  { id: 12, name: "生成AI×人事総務実務研修", role: "人事・総務", hours: 11, price: 360000 },
  { id: 13, name: "生成AI×マーケティング実務研修", role: "マーケティング・広報・制作", hours: 11, price: 360000 },
  { id: 14, name: "生成AI×経理財務実務研修", role: "経理・財務・購買", hours: 11, price: 360000 },
  { id: 15, name: "生成AI×社内展開実務研修", role: "AI活用推進担当", hours: 11, price: 360000 },
  { id: 16, name: "生成AI×現場管理実務研修", role: "現場・品質管理（建設・製造）", hours: 11, price: 360000 },
  { id: 17, name: "生成AI×開発実務研修", role: "開発・情報システム", hours: 11, price: 360000 },
  { id: 18, name: "生成AI×顧客対応実務研修", role: "カスタマーサポート", hours: 11, price: 360000 },
  { id: 19, name: "生成AI×設計実務研修", role: "設計・設計補助", hours: 11, price: 360000 },
];

const SME_CRITERIA = [
  { type: "小売業（飲食店含む）", capital: "5,000万円以下", emp: "50人以下" },
  { type: "サービス業", capital: "5,000万円以下", emp: "100人以下" },
  { type: "卸売業", capital: "1億円以下", emp: "100人以下" },
  { type: "その他の業種", capital: "3億円以下", emp: "300人以下" },
];

const fmt = n => Math.round(n).toLocaleString("ja-JP");

function expCapFor(isSME, hours) {
  if (hours >= 200) return isSME ? 500000 : 300000;
  if (hours >= 100) return isSME ? 400000 : 250000;
  return isSME ? 300000 : 200000;
}

function calcResult(course, isSME, headcount, isLive) {
  const { price, hours } = course;
  const taxInc = price * 1.1;
  const expRate = isSME ? 0.75 : 0.60;
  const expCap  = expCapFor(isSME, hours);
  const wageRate = isSME ? 1000 : 500;
  const expSub  = Math.min(taxInc * expRate, expCap);
  const wageSub = isLive ? wageRate * hours : 0;
  const totalSub = expSub + wageSub;
  const burdenAfter = taxInc - totalSub;
  const tax = price * 0.1;
  const net = Math.max(burdenAfter - tax, 0);
  const pp = { price, taxInc, expSub, wageSub, totalSub, burdenAfter, tax, net };
  const tot = {};
  Object.keys(pp).forEach(k => tot[k] = pp[k] * headcount);
  return { pp, tot };
}

function App() {
  const [course, setCourse]     = useState(null);
  const [isSME, setIsSME]       = useState(null);
  const [count, setCount]       = useState(1);
  const [showSME, setShowSME]   = useState(false);
  const [isLive, setIsLive]     = useState(true);

  const res = useMemo(() =>
    course && isSME !== null && count >= 1 ? calcResult(course, isSME, count, isLive) : null,
    [course, isSME, count, isLive]
  );

  const rows = res ? [
    { label: "① 定価（税抜）",                         pp: res.pp.price,       tot: res.tot.price,       cls: "" },
    { label: "② 税込価格",                              pp: res.pp.taxInc,      tot: res.tot.taxInc,      cls: "" },
    { label: "③ 人材開発支援助成金（経費助成）",         pp: res.pp.expSub,      tot: res.tot.expSub,      cls: "text-teal-700" },
    { label: "④ 賃金助成額",                            pp: res.pp.wageSub,     tot: res.tot.wageSub,     cls: "text-teal-700" },
    { label: "⑤ 助成される総額（③＋④）",               pp: res.pp.totalSub,    tot: res.tot.totalSub,    cls: "text-teal-700 font-bold bg-teal-50" },
    { label: "⑥ 支払いの負担（②－⑤）",                 pp: res.pp.burdenAfter, tot: res.tot.burdenAfter, cls: "font-bold" },
    { label: "⑦ 消費税（仕入税額控除で実質除外）",       pp: res.pp.tax,         tot: res.tot.tax,         cls: "text-gray-400" },
    { label: "⑧ 実質の負担（消費税控除後・⑥－⑦）",     pp: res.pp.net,         tot: res.tot.net,         cls: "text-orange-600 font-bold bg-orange-50" },
  ] : [];

  // Bar chart
  const BAR_H = 200;
  const BarChart = () => {
    if (!res) return null;
    const max = res.tot.taxInc;
    const ph = v => Math.max(Math.round((v / max) * BAR_H), v > 0 ? 12 : 0);
    return (
      <div className="flex items-end justify-around py-2 px-4" style={{ height: BAR_H + 60 }}>
        {/* 研修費用 */}
        <div className="flex flex-col items-center">
          <span className="text-xs font-semibold text-gray-600 mb-1">¥{fmt(res.tot.taxInc)}</span>
          <div className="w-20 flex flex-col justify-end" style={{ height: BAR_H }}>
            <div style={{ height: ph(res.tot.tax), background: "#80cbc4" }} className="flex items-center justify-center">
              <span className="text-xs text-teal-900 font-medium text-center leading-none">消費税</span>
            </div>
            <div style={{ height: ph(res.tot.price), background: "#00796b" }} className="flex items-center justify-center">
              <span className="text-xs text-white font-semibold text-center leading-tight">研修定価<br/>税抜</span>
            </div>
          </div>
          <div className="text-xs font-bold mt-2 text-gray-700">研修費用</div>
        </div>
        {/* 助成金 */}
        <div className="flex flex-col items-center">
          <span className="text-xs font-semibold text-teal-700 mb-1">¥{fmt(res.tot.totalSub)}</span>
          <div className="w-20 flex flex-col justify-end" style={{ height: BAR_H }}>
            <div style={{ height: ph(res.tot.wageSub), background: "#4db6ac" }} className="flex items-center justify-center">
              <span className="text-xs text-white font-semibold text-center leading-tight">賃金<br/>助成</span>
            </div>
            <div style={{ height: ph(res.tot.expSub), background: "#00796b" }} className="flex items-center justify-center">
              <span className="text-xs text-white font-semibold text-center leading-tight">人材開発<br/>支援助成金</span>
            </div>
          </div>
          <div className="text-xs font-bold mt-2 text-teal-700">助成金</div>
        </div>
        {/* 実質負担 */}
        <div className="flex flex-col items-center">
          <span className="text-xs font-semibold text-orange-600 mb-1">¥{fmt(res.tot.net)}</span>
          <div className="w-20 flex flex-col justify-end" style={{ height: BAR_H }}>
            <div style={{ height: ph(res.tot.net), background: "#f57c00" }} className="flex items-center justify-center rounded-t-sm">
              <span className="text-xs text-white font-bold text-center leading-tight">¥{fmt(res.tot.net)}</span>
            </div>
          </div>
          <div className="text-xs font-bold mt-2 text-orange-600">実質の負担</div>
        </div>
      </div>
    );
  };

  return (
    <div className="max-w-2xl mx-auto p-3 font-sans text-gray-800">
      {/* Header */}
      <div className="rounded-2xl p-4 mb-5 text-white" style={{ background: "linear-gradient(135deg,#00695c,#00897b)" }}>
        <div className="text-xs font-semibold opacity-70 mb-0.5">CATORCE Inc.</div>
        <h1 className="text-lg font-bold leading-tight">人材開発支援助成金<br/>研修費用シミュレーター</h1>
        <p className="text-xs opacity-70 mt-1">実質負担額を今すぐ確認</p>
      </div>

      {/* STEP 1 */}
      <div className="mb-5">
        <div className="flex items-center gap-2 mb-3">
          <span className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white" style={{ background: "#00796b" }}>1</span>
          <span className="font-bold text-sm text-gray-700">研修プランを選択</span>
        </div>
        <div className="space-y-2">
          {COURSES.map(c => (
            <React.Fragment key={c.id}>
            {c.group && <div className="pt-3 pb-1 text-xs font-bold" style={{ color: "#00796b" }}>{c.group}</div>}
            <button onClick={() => setCourse(c)}
              className="w-full text-left flex items-center justify-between p-3 rounded-xl border-2 transition-all"
              style={{ borderColor: course?.id === c.id ? "#00796b" : "#e5e7eb", background: course?.id === c.id ? "#e0f2f1" : "#fff" }}>
              <div>
                <div className="font-semibold text-sm">{c.name}{c.role && <span className="ml-2 text-xs font-normal text-gray-500">{c.role}</span>}</div>
                <div className="text-xs text-gray-500 mt-0.5">{c.hours}時間｜¥{fmt(c.price)}（税抜）/人</div>
                {c.warn && <div className="text-xs mt-1" style={{ color: "#b45309" }}>※{c.warn}</div>}
              </div>
              {course?.id === c.id && <span style={{ color: "#00796b" }} className="text-lg font-bold">✓</span>}
            </button>
            </React.Fragment>
          ))}
        </div>
      </div>

      {/* STEP 2 */}
      <div className="mb-5">
        <div className="flex items-center gap-2 mb-2">
          <span className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white" style={{ background: "#00796b" }}>2</span>
          <span className="font-bold text-sm text-gray-700">企業規模を選択</span>
          <button onClick={() => setShowSME(!showSME)} className="text-xs underline ml-1" style={{ color: "#00796b" }}>中小企業の判断基準</button>
        </div>
        {showSME && (
          <div className="mb-3 p-3 rounded-xl border border-gray-200 bg-gray-50 text-xs">
            <div className="font-bold text-gray-700 mb-2">中小企業の定義（A・Bいずれかを満たす）</div>
            <table className="w-full border-collapse text-xs">
              <thead>
                <tr style={{ background: "#b2dfdb" }}>
                  <th className="border border-gray-300 p-1 text-left">主たる事業</th>
                  <th className="border border-gray-300 p-1">A 資本金</th>
                  <th className="border border-gray-300 p-1">B 従業員数</th>
                </tr>
              </thead>
              <tbody>
                {SME_CRITERIA.map((r, i) => (
                  <tr key={i} className={i % 2 === 0 ? "bg-white" : "bg-gray-50"}>
                    <td className="border border-gray-200 p-1">{r.type}</td>
                    <td className="border border-gray-200 p-1 text-center">{r.capital}</td>
                    <td className="border border-gray-200 p-1 text-center">{r.emp}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        <div className="flex gap-3">
          {[
            { val: true,  label: "中小企業", sub: "経費助成率 75% ／ 上限30万円〜" },
            { val: false, label: "大企業",   sub: "経費助成率 60% ／ 上限20万円〜" },
          ].map(opt => (
            <button key={String(opt.val)} onClick={() => setIsSME(opt.val)}
              className="flex-1 p-3 rounded-xl border-2 text-sm font-bold transition-all"
              style={{ borderColor: isSME === opt.val ? "#00796b" : "#e5e7eb", background: isSME === opt.val ? "#e0f2f1" : "#fff", color: isSME === opt.val ? "#00796b" : "#6b7280" }}>
              {opt.label}
              <div className="text-xs font-normal mt-0.5" style={{ color: isSME === opt.val ? "#00897b" : "#9ca3af" }}>{opt.sub}</div>
            </button>
          ))}
        </div>
      </div>

      {/* STEP 2b: format */}
      <div className="mb-5">
        <div className="flex items-center gap-2 mb-2">
          <span className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white" style={{ background: "#00796b" }}>3</span>
          <span className="font-bold text-sm text-gray-700">実施形式を選択</span>
        </div>
        <div className="flex gap-3">
          {[
            { val: true,  label: "ライブ", sub: "対面・同時双方向のオンライン" },
            { val: false, label: "eラーニング", sub: "賃金助成なし／1人1年度1回まで" },
          ].map(opt => (
            <button key={String(opt.val)} onClick={() => setIsLive(opt.val)}
              className="flex-1 p-3 rounded-xl border-2 text-sm font-bold transition-all"
              style={{ borderColor: isLive === opt.val ? "#00796b" : "#e5e7eb", background: isLive === opt.val ? "#e0f2f1" : "#fff", color: isLive === opt.val ? "#00796b" : "#6b7280" }}>
              {opt.label}
              <div className="text-xs font-normal mt-0.5" style={{ color: isLive === opt.val ? "#00897b" : "#9ca3af" }}>{opt.sub}</div>
            </button>
          ))}
        </div>
        <p className="text-xs text-gray-500 mt-2">※賃金助成は、所定労働時間内に実施し、受講者が研修時間の8割以上に出席することが前提です。</p>
      </div>

      {/* STEP 3 */}
      <div className="mb-5">
        <div className="flex items-center gap-2 mb-2">
          <span className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white" style={{ background: "#00796b" }}>4</span>
          <span className="font-bold text-sm text-gray-700">受講人数を入力</span>
        </div>
        <div className="flex items-center gap-3 mb-2">
          <input type="number" min="1" max="500" value={count}
            onChange={e => setCount(Math.max(1, parseInt(e.target.value) || 1))}
            className="w-24 p-2 border-2 rounded-xl text-center text-xl font-bold focus:outline-none"
            style={{ borderColor: "#00796b" }} />
          <span className="text-gray-600 font-semibold">名</span>
        </div>
        <div className="flex items-start gap-2 p-2 rounded-xl border text-xs" style={{ background: "#fff8e1", borderColor: "#ffe082" }}>
          <span>⚠️</span>
          <span style={{ color: "#7c4d00" }}><strong>申請対象は雇用保険の被保険者のみ</strong>です。取締役などの役員は対象外となります。人数の確認をお願いします。</span>
        </div>
      </div>

      {/* STEP 4: Results */}
      {res && (
        <div className="mb-5">
          <div className="flex items-center gap-2 mb-3">
            <span className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white" style={{ background: "#00796b" }}>5</span>
            <span className="font-bold text-sm text-gray-700">シミュレーション結果</span>
          </div>

          {/* KPI Cards */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 mb-4">
            <div className="rounded-xl p-3 text-center text-white" style={{ background: "#00796b" }}>
              <div className="text-xs opacity-80">研修費用（税込）</div>
              <div className="text-base font-bold mt-0.5">¥{fmt(res.tot.taxInc)}</div>
              <div className="text-xs opacity-60">税抜 ¥{fmt(res.tot.price)}</div>
            </div>
            <div className="rounded-xl p-3 text-center text-white" style={{ background: "#00897b" }}>
              <div className="text-xs opacity-80">助成金合計</div>
              <div className="text-base font-bold mt-0.5">¥{fmt(res.tot.totalSub)}</div>
              <div className="text-xs opacity-60">経費＋賃金</div>
            </div>
            <div className="rounded-xl p-3 text-center text-white" style={{ background: "#37474f" }}>
              <div className="text-xs opacity-80">支払いの負担</div>
              <div className="text-base font-bold mt-0.5">¥{fmt(res.tot.burdenAfter)}</div>
              <div className="text-xs opacity-60">消費税控除前</div>
            </div>
            <div className="rounded-xl p-3 text-center text-white" style={{ background: "#e65100" }}>
              <div className="text-xs opacity-80">実質の負担</div>
              <div className="text-base font-bold mt-0.5">¥{fmt(res.tot.net)}</div>
              <div className="text-xs opacity-60">消費税控除後</div>
            </div>
          </div>

          {/* Detail Table */}
          <div className="rounded-xl border border-gray-200 overflow-hidden mb-4">
            <div className="flex text-xs font-bold text-white p-2" style={{ background: "#37474f" }}>
              <div className="flex-1">項目</div>
              <div className="w-28 text-right">1人あたり</div>
              <div className="w-28 text-right">{count}名合計</div>
            </div>
            {rows.map((r, i) => (
              <div key={i} className={`flex text-xs p-2 border-t border-gray-100 ${r.cls}`}>
                <div className="flex-1 pr-2">{r.label}</div>
                <div className="w-28 text-right tabular-nums">¥{fmt(r.pp)}</div>
                <div className="w-28 text-right tabular-nums font-semibold">¥{fmt(r.tot)}</div>
              </div>
            ))}
          </div>

          {/* Bar Chart */}
          <div className="rounded-xl border border-gray-200 bg-white p-4">
            <div className="text-sm font-bold text-gray-700 mb-1">{count}名合計 費用内訳</div>
            <BarChart />
            <p className="text-xs text-gray-400 text-center -mt-2">※消費税は仕入税額控除（課税事業者の場合）として実質負担から除外</p>
          </div>
        </div>
      )}

      {/* STEP 5: Notes */}
      <div className="mb-5">
        <div className="flex items-center gap-2 mb-3">
          <span className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white" style={{ background: "#00796b" }}>6</span>
          <span className="font-bold text-sm text-gray-700">申請にあたっての注意事項</span>
        </div>
        <div className="rounded-xl border p-4 mb-3 text-xs space-y-1" style={{ background: "#fffde7", borderColor: "#ffe082" }}>
          <div className="font-bold mb-2" style={{ color: "#6d4c00" }}>⚠️ 申請対象外・不正受給となる主な事例</div>
          {[
            "雇用保険の被保険者でない方（役員・代表者等）は助成対象外",
            "訓練経費を事業主が全額負担していない場合は受給不可",
            "キャッシュバック・返金・無料サービス提供を受けると不正受給に該当",
            "「実質無料」「後からキャッシュバック」等の提案は不正受給リスクあり",
            "不正受給の場合：全額返金＋20%加算＋5年間の助成金停止・会社名公表",
          ].map((t, i) => <div key={i} style={{ color: "#7c4d00" }}>・{t}</div>)}
        </div>
        <div className="rounded-xl border p-4 text-xs space-y-1" style={{ background: "#e8f5e9", borderColor: "#a5d6a7" }}>
          <div className="font-bold mb-2" style={{ color: "#1b5e20" }}>💡 賃上げ促進税制との併用もご検討ください</div>
          {[
            "教育訓練費が前年比増加の場合、法人税から追加控除が受けられる可能性があります",
            "「賃上げ促進税制（教育訓練費増加控除）」との併用でさらなるコスト削減が期待できます",
            "助成金と税制優遇のダブル活用により、実質負担を大幅に圧縮できるケースがあります",
          ].map((t, i) => <div key={i} style={{ color: "#2e7d32" }}>・{t}</div>)}
          <div className="mt-2 font-semibold" style={{ color: "#2e7d32" }}>※詳細な適用可否・計算は税理士にご相談ください</div>
        </div>
      </div>

      <div className="mb-5 p-4 rounded-xl border border-gray-200 bg-white text-sm">
        <div className="font-bold text-gray-700 mb-1">助成金の対象条件と注意点</div>
        <p className="text-xs text-gray-600 mb-2">8月改正で対象外になった研修、計画届の期限、自己負担の計算例は記事で解説しています。</p>
        <a href={ARTICLE_URL} className="text-xs font-bold underline" style={{ color: "#00796b" }}>AI研修の助成金（対象条件と自己負担の計算例）を読む →</a>
      </div>

      {/* CTA */}
      <div className="rounded-2xl p-5 text-center text-white" style={{ background: "linear-gradient(135deg,#00695c,#00897b)" }}>
        <div className="font-bold text-base mb-1">研修計画と申請資料づくりを支援します</div>
        <p className="text-xs opacity-80 mb-3">手続きは提携の社会保険労務士をご紹介します</p>
        <a href={CONTACT_URL}
          className="inline-block bg-white font-bold px-6 py-2 rounded-full text-sm transition-all hover:opacity-90" style={{ color: "#00796b" }}>
          お問い合わせ・詳細を見る →
        </a>
      </div>

      <p className="text-xs text-gray-400 text-center mt-5 leading-relaxed">
        ※ 本シミュレーションは概算です。助成率・上限額・支給要件は年度や訓練内容により変動し、実際の支給を保証するものではありません。<br/>
        最新の制度内容・適用可否は厚生労働省の公式情報および労働局・社会保険労務士にご確認ください。
      </p>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("sim-root")).render(<App />);
