const { useState, useMemo, useEffect, Fragment } = React;

const INITIAL_DATA = [
  { month: 5, budget: { frontEnd: 30, middleEnd: 0, stock: 0, backEnd: 0, cashIn: 50, expense: 100 }, actual: { frontEnd: 0, middleEnd: 0, stock: 0, backEnd: 0, cashIn: 0, expense: 100 } },
  { month: 6, budget: { frontEnd: 40, middleEnd: 76, stock: 0, backEnd: 0, cashIn: 150, expense: 100 }, actual: { frontEnd: 0, middleEnd: 0, stock: 0, backEnd: 0, cashIn: 0, expense: 100 } },
  { month: 7, budget: { frontEnd: 40, middleEnd: 114, stock: 2, backEnd: 0, cashIn: 200, expense: 100 }, actual: { frontEnd: 0, middleEnd: 0, stock: 0, backEnd: 0, cashIn: 0, expense: 100 } },
  { month: 8, budget: { frontEnd: 30, middleEnd: 152, stock: 4, backEnd: 0, cashIn: 250, expense: 100 }, actual: { frontEnd: 0, middleEnd: 0, stock: 0, backEnd: 0, cashIn: 0, expense: 100 } },
  { month: 9, budget: { frontEnd: 20, middleEnd: 152, stock: 7, backEnd: 180, cashIn: 400, expense: 100 }, actual: { frontEnd: 0, middleEnd: 0, stock: 0, backEnd: 0, cashIn: 0, expense: 100 } },
  { month: 10, budget: { frontEnd: 20, middleEnd: 114, stock: 10, backEnd: 180, cashIn: 350, expense: 100 }, actual: { frontEnd: 0, middleEnd: 0, stock: 0, backEnd: 0, cashIn: 0, expense: 100 } },
  { month: 11, budget: { frontEnd: 20, middleEnd: 152, stock: 14, backEnd: 180, cashIn: 400, expense: 100 }, actual: { frontEnd: 0, middleEnd: 0, stock: 0, backEnd: 0, cashIn: 0, expense: 100 } },
  { month: 12, budget: { frontEnd: 20, middleEnd: 190, stock: 18, backEnd: 360, cashIn: 600, expense: 100 }, actual: { frontEnd: 0, middleEnd: 0, stock: 0, backEnd: 0, cashIn: 0, expense: 100 } },
  { month: 1, budget: { frontEnd: 10, middleEnd: 114, stock: 22, backEnd: 180, cashIn: 350, expense: 100 }, actual: { frontEnd: 0, middleEnd: 0, stock: 0, backEnd: 0, cashIn: 0, expense: 100 } },
  { month: 2, budget: { frontEnd: 20, middleEnd: 152, stock: 26, backEnd: 180, cashIn: 400, expense: 100 }, actual: { frontEnd: 0, middleEnd: 0, stock: 0, backEnd: 0, cashIn: 0, expense: 100 } },
  { month: 3, budget: { frontEnd: 30, middleEnd: 228, stock: 31, backEnd: 360, cashIn: 700, expense: 100 }, actual: { frontEnd: 0, middleEnd: 0, stock: 0, backEnd: 0, cashIn: 0, expense: 100 } },
  { month: 4, budget: { frontEnd: 30, middleEnd: 152, stock: 36, backEnd: 180, cashIn: 350, expense: 100 }, actual: { frontEnd: 0, middleEnd: 0, stock: 0, backEnd: 0, cashIn: 0, expense: 100 } }
];

const Icon = ({ name, className = "" }) => (
  <i className={`fa-solid ${name} ${className}`} aria-hidden="true"></i>
);

const BrandLogo = () => (
  <div className="w-11 h-11 bg-[#E3182D] rounded-[14px] flex items-center justify-center shadow-sm overflow-hidden relative shrink-0">
    <span
      className="text-white font-black text-[28px] tracking-tighter"
      style={{ transform: "skewX(-15deg) translateX(1px)", fontFamily: 'Impact, "Arial Black", sans-serif' }}
    >
      AI
    </span>
    <div
      className="absolute w-[150%] h-[3px] bg-[#E3182D]"
      style={{ transform: "rotate(-12deg)", top: "62%", left: "-25%" }}
    ></div>
  </div>
);

function App() {
  const [activeTab, setActiveTab] = useState("dashboard");
  const [monthlyData, setMonthlyData] = useState(INITIAL_DATA);
  const [shareId, setShareId] = useState("");
  const [inputId, setInputId] = useState("");
  const [isSaving, setIsSaving] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [copied, setCopied] = useState(false);
  const [message, setMessage] = useState("");
  const [isZoomedOut, setIsZoomedOut] = useState(false);

  const showMessage = (msg) => {
    setMessage(msg);
    setTimeout(() => setMessage(""), 3000);
  };

  const toggleZoom = () => setIsZoomedOut(!isZoomedOut);

  const loadDataById = async (idToLoad) => {
    if (!idToLoad) return;
    setIsLoading(true);
    try {
      const response = await fetch(`/api/plans/${encodeURIComponent(idToLoad.trim())}`);
      if (!response.ok) {
        showMessage("❌ データが見つかりません");
        return;
      }
      const payload = await response.json();
      setMonthlyData(payload.monthlyData || INITIAL_DATA);
      setShareId(payload.shareId || idToLoad.trim());
      showMessage("✅ データを復元しました");
    } catch (e) {
      console.error("Load Error:", e);
      showMessage("❌ 読み込みエラー");
    } finally {
      setIsLoading(false);
    }
  };

  const [lastSavedAt, setLastSavedAt] = useState("");

  const handleSave = async () => {
    setIsSaving(true);
    try {
      const response = await fetch("/api/plans", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ shareId, monthlyData })
      });
      if (!response.ok) {
        const errText = await response.text().catch(() => "");
        console.error("Save failed:", response.status, errText);
        showMessage(`❌ 保存エラー (${response.status})`);
        return;
      }
      const payload = await response.json();
      setShareId(payload.shareId);
      setLastSavedAt(payload.updatedAt || new Date().toISOString());
      // localStorageにもバックアップ
      try {
        localStorage.setItem("ai-gunshi-data", JSON.stringify(monthlyData));
        localStorage.setItem("ai-gunshi-shareId", payload.shareId);
      } catch (_) {}
      showMessage(`✅ 保存完了！ID: ${payload.shareId}`);
    } catch (e) {
      console.error("Save Error:", e);
      showMessage("❌ 通信エラー: " + (e.message || "不明"));
    } finally {
      setIsSaving(false);
    }
  };

  // 起動時にlocalStorageから自動復元
  useEffect(() => {
    try {
      const cached = localStorage.getItem("ai-gunshi-data");
      const cachedId = localStorage.getItem("ai-gunshi-shareId");
      if (cached) {
        setMonthlyData(JSON.parse(cached));
      }
      if (cachedId) {
        setShareId(cachedId);
      }
    } catch (_) {}
  }, []);

  const copyToClipboard = () => {
    if (!shareId) return;
    const textArea = document.createElement("textarea");
    textArea.value = shareId;
    document.body.appendChild(textArea);
    textArea.select();
    try {
      document.execCommand("copy");
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error("Copy failed", err);
    }
    document.body.removeChild(textArea);
  };

  const TARGET_PROFIT = 2000;
  const TARGET_CF = 4000;

  const totals = useMemo(() => {
    let actualRevenue = 0,
      actualExpense = 0,
      actualCashIn = 0;
    let budgetRevenue = 0,
      budgetProfit = 0;

    monthlyData.forEach((data) => {
      const mActualRev =
        Number(data.actual.frontEnd) +
        Number(data.actual.middleEnd) +
        Number(data.actual.stock) +
        Number(data.actual.backEnd);
      actualRevenue += mActualRev;
      actualExpense += Number(data.actual.expense);
      actualCashIn += Number(data.actual.cashIn) || mActualRev;

      const mBudgetRev =
        Number(data.budget.frontEnd) +
        Number(data.budget.middleEnd) +
        Number(data.budget.stock) +
        Number(data.budget.backEnd);
      budgetRevenue += mBudgetRev;
      budgetProfit += mBudgetRev - Number(data.budget.expense);
    });

    const currentProfit = actualRevenue - actualExpense;
    const profitProgress = Math.min(100, Math.max(0, (currentProfit / TARGET_PROFIT) * 100));
    const cfProgress = Math.min(100, Math.max(0, (actualCashIn / TARGET_CF) * 100));

    return { actualRevenue, actualExpense, currentProfit, actualCashIn, profitProgress, cfProgress, budgetProfit };
  }, [monthlyData]);

  const getGunshiMessage = () => {
    const p = totals.profitProgress;
    if (p >= 100) return "目標達成！見事な戦略実行力です。次なる高みへ事業をスケールさせましょう。";
    if (p >= 80) return "目標まであと一息です。最終クォーターのクロージングに注力してください。";
    if (p >= 50) return "計画は順調です。バックエンド商材への引き上げ率をさらに高める施策を打ちましょう。";
    if (p >= 30) return "初期の立ち上げフェーズです。フロントエンドでのリード獲得と信頼構築に集中してください。";
    return "AIを駆使し、最小の労力で最大の利益を。まずは毎月の予算（目標）を確定させましょう。";
  };

  const handleInputChange = (index, type, field, value) => {
    const newData = [...monthlyData];
    newData[index][type][field] = value === "" ? 0 : Number(value);
    setMonthlyData(newData);
  };

  const ProgressRing = ({ progress, label, value, target, colorClass, strokeColor }) => {
    const radius = 60;
    const circumference = 2 * Math.PI * radius;
    const strokeDashoffset = circumference - (progress / 100) * circumference;

    return (
      <div className="flex flex-col items-center justify-center p-6 bg-white rounded-2xl border border-gray-100 shadow-sm relative overflow-hidden transition-all hover:shadow-md">
        <div className={`absolute top-0 w-full h-1.5 bg-gradient-to-r ${colorClass}`}></div>
        <h3 className="text-gray-500 text-sm mb-4 font-bold tracking-wider">{label}</h3>
        <div className="relative flex items-center justify-center">
          <svg className="transform -rotate-90 w-40 h-40 drop-shadow-sm">
            <circle cx="80" cy="80" r={radius} stroke="#f3f4f6" strokeWidth="10" fill="transparent" />
            <circle
              cx="80"
              cy="80"
              r={radius}
              stroke={strokeColor}
              strokeWidth="10"
              fill="transparent"
              strokeDasharray={circumference}
              strokeDashoffset={strokeDashoffset}
              className="transition-all duration-1000 ease-out"
              style={{ strokeLinecap: "round" }}
            />
          </svg>
          <div className="absolute flex flex-col items-center justify-center">
            <span className="text-3xl font-black text-gray-900 tracking-tight">
              {value}
              <span className="text-base font-medium text-gray-500 ml-1">万</span>
            </span>
            <span className="text-xs text-gray-400 mt-1 font-medium">目標: {target}万</span>
          </div>
        </div>
        <div className="mt-5 text-center bg-gray-50 px-4 py-1.5 rounded-full">
          <span className={`text-lg font-black ${progress >= 100 ? "text-red-600" : "text-gray-700"}`}>
            {progress.toFixed(1)}%
          </span>
        </div>
      </div>
    );
  };

  return (
    <div className="bg-[#FAFAFA] text-gray-800 font-sans min-h-screen selection:bg-red-100 selection:text-red-900">
      <div
        style={{ zoom: isZoomedOut ? 0.75 : 1 }}
        className="p-4 md:p-8 transition-all duration-300 origin-top-left max-w-[1600px] mx-auto"
      >
        <header className="mb-8 flex flex-col lg:flex-row justify-between items-start lg:items-center bg-white p-4 rounded-2xl border border-gray-100 shadow-sm gap-4 relative">
          {message && (
            <div className="absolute -top-2 right-4 bg-gray-900 text-white px-4 py-2 rounded-lg shadow-lg text-sm font-bold animate-fade-in z-50 flex items-center gap-2">
              <span className="w-2 h-2 rounded-full bg-green-400"></span> {message}
            </div>
          )}

          <div className="flex items-center gap-4">
            <BrandLogo />
            <div>
              <h1 className="text-2xl font-black text-gray-900 tracking-tight flex items-center gap-2">
                AI-GUNSHI <span className="text-red-600">COMMAND CENTER</span>
              </h1>
              <p className="text-gray-500 mt-0.5 text-xs tracking-widest font-semibold uppercase">Business Strategy Dashboard</p>
            </div>
          </div>

          <div className="flex flex-col xl:flex-row items-end xl:items-center gap-4 w-full lg:w-auto">
            <div className="flex bg-gray-100/80 p-1.5 rounded-xl border border-gray-200 w-full md:w-auto overflow-x-auto shrink-0 gap-1 shadow-inner">
              {[
                { key: "dashboard", label: "ダッシュボード", icon: "fa-table-columns" },
                { key: "input", label: "予実管理", icon: "fa-chart-column" },
                { key: "strategy", label: "戦略図", icon: "fa-bullseye" }
              ].map((tab) => (
                <button
                  key={tab.key}
                  onClick={() => setActiveTab(tab.key)}
                  className={`px-5 py-2.5 rounded-lg font-bold transition-all whitespace-nowrap text-sm flex items-center gap-2 ${
                    activeTab === tab.key
                      ? "bg-red-600 text-white shadow-md"
                      : "bg-transparent text-gray-600 hover:bg-white hover:text-gray-900 hover:shadow-sm"
                  }`}
                >
                  <Icon
                    name={tab.icon}
                    className={activeTab === tab.key ? "text-white" : "text-gray-400"}
                  />
                  {tab.label}
                </button>
              ))}
            </div>

            <div className="flex flex-wrap items-center gap-2 w-full xl:w-auto justify-end">
              <button
                onClick={handleSave}
                disabled={isSaving}
                className="flex items-center justify-center gap-1.5 px-4 py-2 bg-red-600 hover:bg-red-700 text-white font-bold rounded-lg transition-colors disabled:opacity-50 text-sm shadow-sm"
              >
                <Icon name="fa-floppy-disk" />
                {isSaving ? "保存中..." : "状態を保存"}
              </button>

              {shareId && (
                <div className="flex items-center bg-white border border-gray-200 rounded-lg overflow-hidden shadow-sm h-9">
                  <span className="px-3 py-2 text-[10px] font-bold text-gray-500 bg-gray-50 border-r border-gray-200">ID</span>
                  <input
                    type="text"
                    readOnly
                    value={shareId}
                    className="px-2 py-2 text-xs font-mono font-bold text-red-600 outline-none w-24 bg-white"
                    onClick={(e) => e.target.select()}
                  />
                  <button
                    onClick={copyToClipboard}
                    className="px-3 py-2 bg-gray-50 hover:bg-gray-100 text-gray-600 border-l border-gray-200 transition-colors"
                    title="IDをコピー"
                  >
                    {copied ? <Icon name="fa-check" className="text-green-600" /> : <Icon name="fa-copy" />}
                  </button>
                </div>
              )}

              <div className="flex items-center bg-white border border-gray-200 rounded-lg overflow-hidden h-9 shadow-sm">
                <input
                  type="text"
                  placeholder="IDを入力..."
                  value={inputId}
                  onChange={(e) => setInputId(e.target.value)}
                  className="px-3 py-2 text-xs font-mono text-gray-700 outline-none w-28 placeholder:text-gray-400"
                />
                <button
                  onClick={() => loadDataById(inputId)}
                  disabled={isLoading || !inputId.trim()}
                  className="px-3 py-2 flex items-center gap-1.5 bg-gray-50 hover:bg-gray-100 text-gray-700 border-l border-gray-200 transition-colors text-xs font-bold disabled:opacity-50"
                >
                  <Icon name="fa-download" /> 復元
                </button>
              </div>

              <button
                onClick={toggleZoom}
                className={`p-2 rounded-lg transition-colors hidden md:block border ${
                  isZoomedOut
                    ? "bg-red-50 text-red-600 border-red-200"
                    : "bg-white text-gray-600 border-gray-200 hover:bg-gray-50 shadow-sm"
                }`}
                title={isZoomedOut ? "標準サイズに戻す" : "縮小表示（75%）"}
              >
                <Icon name={isZoomedOut ? "fa-magnifying-glass-plus" : "fa-magnifying-glass-minus"} />
              </button>
            </div>
          </div>
        </header>

        <main>
          {activeTab === "dashboard" && (
            <div className="space-y-6 animate-fade-in">
              <div className="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm flex items-center gap-5 relative overflow-hidden">
                <div className="absolute left-0 top-0 bottom-0 w-1.5 bg-red-600"></div>
                <div className="p-3 bg-red-50 rounded-xl flex-shrink-0">
                  <Icon name="fa-bolt" className="text-red-600 text-lg" />
                </div>
                <div className="flex-1">
                  <h2 className="text-sm text-gray-500 font-bold tracking-wider mb-1 flex items-center justify-between">
                    <span>AI-GUNSHI ANALYSIS</span>
                    <span className="text-xs bg-gray-100 px-3 py-1 rounded-full text-gray-600">
                      計画予測利益: {totals.budgetProfit.toLocaleString()}万円
                    </span>
                  </h2>
                  <p className="text-lg font-bold text-gray-900 leading-snug">{getGunshiMessage()}</p>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <ProgressRing
                  progress={totals.profitProgress}
                  label="年間利益 (実績 vs 目標)"
                  value={totals.currentProfit.toLocaleString()}
                  target={TARGET_PROFIT}
                  colorClass="from-red-500 to-rose-600"
                  strokeColor="#e11d48"
                />
                <ProgressRing
                  progress={totals.cfProgress}
                  label="キャッシュフロー (実績 vs 目標)"
                  value={totals.actualCashIn.toLocaleString()}
                  target={TARGET_CF}
                  colorClass="from-gray-700 to-gray-900"
                  strokeColor="#111827"
                />
              </div>

              <div className="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm mt-6">
                <h3 className="text-gray-800 text-base font-bold tracking-wider mb-8 flex items-center gap-2">
                  <Icon name="fa-chart-column" className="text-gray-400" /> 月次売上推移 (予算 vs 実績)
                </h3>
                <div className="h-72 flex items-end gap-2 md:gap-4 px-2">
                  {monthlyData.map((data, idx) => {
                    const budgetRev =
                      Number(data.budget.frontEnd) +
                      Number(data.budget.middleEnd) +
                      Number(data.budget.stock) +
                      Number(data.budget.backEnd);
                    const actualRev =
                      Number(data.actual.frontEnd) +
                      Number(data.actual.middleEnd) +
                      Number(data.actual.stock) +
                      Number(data.actual.backEnd);

                    const maxRev = Math.max(
                      ...monthlyData.map((d) => {
                        const b =
                          Number(d.budget.frontEnd) +
                          Number(d.budget.middleEnd) +
                          Number(d.budget.stock) +
                          Number(d.budget.backEnd);
                        const a =
                          Number(d.actual.frontEnd) +
                          Number(d.actual.middleEnd) +
                          Number(d.actual.stock) +
                          Number(d.actual.backEnd);
                        return Math.max(b, a);
                      }),
                      100
                    );

                    return (
                      <div key={idx} className="flex-1 flex flex-col items-center group relative h-full justify-end">
                        <div className="absolute -top-20 opacity-0 group-hover:opacity-100 transition-opacity bg-gray-900 text-white text-xs py-3 px-4 rounded-lg shadow-xl pointer-events-none z-10 border border-gray-700 whitespace-nowrap text-left">
                          <div className="font-bold text-gray-300 border-b border-gray-700 pb-1.5 mb-1.5">
                            {data.month}月 売上
                          </div>
                          <div className="text-gray-400">
                            予算: <span className="text-white">{budgetRev}万</span> (経費: {data.budget.expense}万)
                          </div>
                          <div className="text-red-400 font-bold mt-1">
                            実績: <span className="text-white">{actualRev}万</span> (経費: {data.actual.expense}万)
                          </div>
                          <div
                            className={`mt-2 pt-1 border-t border-gray-700 font-bold ${
                              actualRev >= budgetRev ? "text-green-400" : "text-yellow-400"
                            }`}
                          >
                            達成率: {budgetRev > 0 ? Math.round((actualRev / budgetRev) * 100) : 0}%
                          </div>
                        </div>

                        <div className="w-full max-w-[40px] flex items-end justify-center gap-0.5" style={{ height: "100%" }}>
                          <div
                            className="w-1/2 bg-gray-200 rounded-t-sm hover:bg-gray-300 transition-colors"
                            style={{ height: `${(budgetRev / maxRev) * 100}%` }}
                          ></div>

                          <div
                            className="w-1/2 bg-gray-50 rounded-t-sm flex flex-col justify-end overflow-hidden"
                            style={{ height: `${(actualRev / maxRev) * 100}%` }}
                          >
                            {actualRev > 0 ? (
                              <>
                                <div className="w-full bg-gray-900" style={{ height: `${(data.actual.backEnd / actualRev) * 100}%` }}></div>
                                <div className="w-full bg-gray-600" style={{ height: `${(data.actual.stock / actualRev) * 100}%` }}></div>
                                <div className="w-full bg-red-600" style={{ height: `${(data.actual.middleEnd / actualRev) * 100}%` }}></div>
                                <div className="w-full bg-rose-400" style={{ height: `${(data.actual.frontEnd / actualRev) * 100}%` }}></div>
                              </>
                            ) : (
                              <div className="w-full h-full bg-transparent"></div>
                            )}
                          </div>
                        </div>
                        <span className="text-xs text-gray-500 mt-3 font-semibold">{data.month}月</span>
                      </div>
                    );
                  })}
                </div>

                <div className="flex flex-wrap justify-center gap-5 mt-8 text-xs text-gray-600 font-medium bg-gray-50 py-3 rounded-lg border border-gray-100">
                  <span className="flex items-center gap-1.5">
                    <div className="w-3 h-3 bg-gray-200 rounded-[2px]"></div>目標(予算)
                  </span>
                  <span className="text-gray-300">|</span>
                  <span className="flex items-center gap-1.5">
                    <div className="w-3 h-3 bg-rose-400 rounded-[2px]"></div>フロント実績
                  </span>
                  <span className="flex items-center gap-1.5">
                    <div className="w-3 h-3 bg-red-600 rounded-[2px]"></div>ミドル実績
                  </span>
                  <span className="flex items-center gap-1.5">
                    <div className="w-3 h-3 bg-gray-600 rounded-[2px]"></div>ストック実績
                  </span>
                  <span className="flex items-center gap-1.5">
                    <div className="w-3 h-3 bg-gray-900 rounded-[2px]"></div>バック実績
                  </span>
                </div>
              </div>
            </div>
          )}

          {activeTab === "input" && (
            <div className="bg-white rounded-2xl border border-gray-100 overflow-hidden shadow-sm animate-fade-in">
              <div className="p-5 bg-white border-b border-gray-100 flex flex-wrap justify-between items-center gap-3">
                <div>
                  <h3 className="text-lg font-black text-gray-900 flex items-center gap-2">予実データ管理</h3>
                  <p className="text-xs text-gray-500 mt-1">
                    上段（グレー）に目標を入力し、下段（白）に実績を入力してください。入力後は必ず「保存」ボタンを押してください。
                  </p>
                  {lastSavedAt && (
                    <p className="text-[11px] text-green-600 font-bold mt-1">
                      <Icon name="fa-circle-check" /> 最終保存: {new Date(lastSavedAt).toLocaleString("ja-JP")}
                    </p>
                  )}
                </div>
                <button
                  onClick={handleSave}
                  disabled={isSaving}
                  className="flex items-center gap-2 px-6 py-3 bg-red-600 hover:bg-red-700 text-white font-black rounded-xl transition-all disabled:opacity-50 shadow-md hover:shadow-lg text-base"
                >
                  <Icon name="fa-floppy-disk" className="text-lg" />
                  {isSaving ? "保存中..." : "データを保存する"}
                </button>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse min-w-[900px]">
                  <thead>
                    <tr className="bg-gray-50 text-xs uppercase text-gray-500 border-b border-gray-200">
                      <th className="p-3 font-bold text-center w-14">月</th>
                      <th className="p-3 font-bold text-center w-16">種別</th>
                      <th className="p-3 font-semibold">
                        フロントエンド<br />
                        <span className="text-[10px] font-normal text-gray-400">(集客・1万〜8万)</span>
                      </th>
                      <th className="p-3 font-semibold">
                        ミドルエンド<br />
                        <span className="text-[10px] font-normal text-gray-400">(HP等・着手金)</span>
                      </th>
                      <th className="p-3 font-semibold">
                        ストック<br />
                        <span className="text-[10px] font-normal text-gray-400">(月額課金)</span>
                      </th>
                      <th className="p-3 font-semibold">
                        バックエンド<br />
                        <span className="text-[10px] font-normal text-gray-400">(コンサル180万)</span>
                      </th>
                      <th className="p-3 font-semibold bg-gray-100/50">
                        キャッシュイン<br />
                        <span className="text-[10px] font-normal text-gray-400">(当月の入金)</span>
                      </th>
                      <th className="p-3 font-semibold">
                        経費<br />
                        <span className="text-[10px] font-normal text-gray-400">(固定費・外注)</span>
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {monthlyData.map((row, idx) => {
                      const budgetTotal = row.budget.frontEnd + row.budget.middleEnd + row.budget.stock + row.budget.backEnd;
                      const actualTotal = row.actual.frontEnd + row.actual.middleEnd + row.actual.stock + row.actual.backEnd;
                      const isAchieved = actualTotal >= budgetTotal && budgetTotal > 0;

                      return (
                        <Fragment key={idx}>
                          <tr className="border-t-[3px] border-gray-100 bg-gray-50/50">
                            <td
                              rowSpan={2}
                              className={`p-2 font-black text-center align-middle border-b border-r border-gray-100 ${
                                isAchieved ? "text-red-600 bg-red-50/50" : "text-gray-800 bg-gray-50"
                              }`}
                            >
                              {row.month}月
                              {isAchieved && <Icon name="fa-check" className="mx-auto mt-1" />}
                            </td>
                            <td className="p-1.5 text-[10px] font-bold text-gray-400 text-center uppercase tracking-wider">Target</td>
                            <td className="p-1.5">
                              <input
                                type="number"
                                value={row.budget.frontEnd}
                                onChange={(e) => handleInputChange(idx, "budget", "frontEnd", e.target.value)}
                                className="w-full bg-white border border-gray-200 rounded px-2 py-1.5 text-right text-sm text-gray-500 focus:border-gray-400 focus:outline-none"
                              />
                            </td>
                            <td className="p-1.5">
                              <input
                                type="number"
                                value={row.budget.middleEnd}
                                onChange={(e) => handleInputChange(idx, "budget", "middleEnd", e.target.value)}
                                className="w-full bg-white border border-gray-200 rounded px-2 py-1.5 text-right text-sm text-gray-500 focus:border-gray-400 focus:outline-none"
                              />
                            </td>
                            <td className="p-1.5">
                              <input
                                type="number"
                                value={row.budget.stock}
                                onChange={(e) => handleInputChange(idx, "budget", "stock", e.target.value)}
                                className="w-full bg-white border border-gray-200 rounded px-2 py-1.5 text-right text-sm text-gray-500 focus:border-gray-400 focus:outline-none"
                              />
                            </td>
                            <td className="p-1.5">
                              <input
                                type="number"
                                value={row.budget.backEnd}
                                onChange={(e) => handleInputChange(idx, "budget", "backEnd", e.target.value)}
                                className="w-full bg-white border border-gray-200 rounded px-2 py-1.5 text-right text-sm text-gray-500 focus:border-gray-400 focus:outline-none"
                              />
                            </td>
                            <td className="p-1.5 bg-gray-100/30">
                              <input
                                type="number"
                                value={row.budget.cashIn}
                                onChange={(e) => handleInputChange(idx, "budget", "cashIn", e.target.value)}
                                className="w-full bg-white border border-gray-200 rounded px-2 py-1.5 text-right text-sm text-gray-500 focus:border-gray-400 focus:outline-none"
                              />
                            </td>
                            <td className="p-1.5">
                              <input
                                type="number"
                                value={row.budget.expense}
                                onChange={(e) => handleInputChange(idx, "budget", "expense", e.target.value)}
                                className="w-full bg-white border border-gray-200 rounded px-2 py-1.5 text-right text-sm text-gray-500 focus:border-gray-400 focus:outline-none"
                              />
                            </td>
                          </tr>
                          <tr className="border-b border-gray-100 bg-white">
                            <td className="p-1.5 text-[10px] font-bold text-red-600 text-center uppercase tracking-wider">Actual</td>
                            <td className="p-1.5">
                              <input
                                type="number"
                                value={row.actual.frontEnd}
                                onChange={(e) => handleInputChange(idx, "actual", "frontEnd", e.target.value)}
                                className="w-full bg-white border border-rose-200 rounded px-2 py-2 text-right font-bold text-gray-900 focus:border-rose-500 focus:ring-1 focus:ring-rose-500 focus:outline-none shadow-inner"
                              />
                            </td>
                            <td className="p-1.5">
                              <input
                                type="number"
                                value={row.actual.middleEnd}
                                onChange={(e) => handleInputChange(idx, "actual", "middleEnd", e.target.value)}
                                className="w-full bg-white border border-red-200 rounded px-2 py-2 text-right font-bold text-gray-900 focus:border-red-500 focus:ring-1 focus:ring-red-500 focus:outline-none shadow-inner"
                              />
                            </td>
                            <td className="p-1.5">
                              <input
                                type="number"
                                value={row.actual.stock}
                                onChange={(e) => handleInputChange(idx, "actual", "stock", e.target.value)}
                                className="w-full bg-white border border-gray-300 rounded px-2 py-2 text-right font-bold text-gray-900 focus:border-gray-500 focus:ring-1 focus:ring-gray-500 focus:outline-none shadow-inner"
                              />
                            </td>
                            <td className="p-1.5">
                              <input
                                type="number"
                                value={row.actual.backEnd}
                                onChange={(e) => handleInputChange(idx, "actual", "backEnd", e.target.value)}
                                className="w-full bg-white border border-gray-400 rounded px-2 py-2 text-right font-bold text-gray-900 focus:border-gray-900 focus:ring-1 focus:ring-gray-900 focus:outline-none shadow-inner"
                              />
                            </td>
                            <td className="p-1.5 bg-gray-50/50">
                              <input
                                type="number"
                                value={row.actual.cashIn}
                                onChange={(e) => handleInputChange(idx, "actual", "cashIn", e.target.value)}
                                className="w-full bg-white border border-gray-300 rounded px-2 py-2 text-right font-black text-gray-900 focus:border-gray-500 focus:ring-1 focus:ring-gray-500 focus:outline-none shadow-inner"
                              />
                            </td>
                            <td className="p-1.5">
                              <input
                                type="number"
                                value={row.actual.expense}
                                onChange={(e) => handleInputChange(idx, "actual", "expense", e.target.value)}
                                className="w-full bg-white border border-gray-200 rounded px-2 py-2 text-right font-bold text-gray-600 focus:border-gray-400 focus:outline-none shadow-inner"
                              />
                            </td>
                          </tr>
                        </Fragment>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {activeTab === "strategy" && (
            <div className="animate-fade-in space-y-8">
              <div className="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm">
                <h2 className="text-xl font-black border-b border-gray-100 pb-4 mb-6 flex items-center gap-2 text-gray-900">
                  <Icon name="fa-shield" className="text-red-600" /> 勝利の方程式 (The Master Plan)
                </h2>

                <div className="grid grid-cols-1 xl:grid-cols-3 gap-6 relative">
                  <div className="bg-sky-50/60 rounded-xl p-6 border border-sky-100 relative shadow-sm">
                    <div className="absolute -top-3 -left-3 w-8 h-8 bg-sky-500 rounded-lg flex items-center justify-center font-black text-white text-sm shadow-sm">
                      01
                    </div>
                    <h3 className="text-sky-900 font-bold text-lg mb-3 text-center">
                      フロントエンド <br />
                      <span className="text-sm font-medium text-sky-600/80">(集客・リスト化)</span>
                    </h3>
                    <p className="text-gray-600 text-xs mb-4 leading-relaxed">
                      決定済みのDM5000通を起点に、圧倒的な提案力でドアノックする。
                    </p>
                    <ul className="space-y-2">
                      <li className="bg-white p-3 rounded-lg border border-sky-100 shadow-sm text-sm">
                        <span className="text-sky-600 font-bold block mb-0.5 text-xs">■不動産・歯医者へ</span>
                        <span className="font-bold text-gray-800">(3) HPのAIO最適化・改善点提示</span> [1万円/回]
                        <br />
                        <span className="text-[10px] text-gray-400">※DMフック商材</span>
                      </li>
                      <li className="bg-white p-3 rounded-lg border border-sky-100 shadow-sm text-sm">
                        <span className="text-sky-600 font-bold block mb-0.5 text-xs">■パン屋・BtoB企業へ</span>
                        <span className="font-bold text-gray-800">(2) AI営業リスト作成アプリ</span> [8万円]
                      </li>
                      <li className="bg-white p-3 rounded-lg border border-sky-100 shadow-sm text-sm">
                        <span className="text-sky-600 font-bold block mb-0.5 text-xs">■市場調査</span>
                        <span className="font-bold text-gray-800">(1) AI市場調査分析</span> [3万円/店舗]
                      </li>
                    </ul>
                  </div>

                  <div className="bg-emerald-50/60 rounded-xl p-6 border border-emerald-100 relative shadow-sm">
                    <div className="absolute -top-3 -left-3 w-8 h-8 bg-emerald-500 rounded-lg flex items-center justify-center font-black text-white text-sm shadow-sm">
                      02
                    </div>
                    <div className="hidden xl:block absolute top-1/2 -left-5 text-gray-300 transform -translate-y-1/2 bg-white rounded-full">
                      <Icon name="fa-chevron-right" />
                    </div>

                    <h3 className="text-emerald-900 font-bold text-lg mb-3 text-center">
                      ミドルエンド <br />
                      <span className="text-sm font-medium text-emerald-600/80">(課題解決・信頼構築)</span>
                    </h3>
                    <p className="text-gray-600 text-xs mb-4 leading-relaxed">
                      フロントで炙り出した課題に対し、自社開発の強力なシステムを導入し現金を確保。
                    </p>
                    <ul className="space-y-2">
                      <li className="bg-white p-3 rounded-lg border border-emerald-200 shadow-sm text-sm relative overflow-hidden">
                        <div className="absolute left-0 top-0 bottom-0 w-1 bg-emerald-400"></div>
                        <span className="text-gray-900 font-bold block mb-0.5">(8) AIO最適化HP作成 [38万]</span>
                        <span className="text-[10px] text-emerald-600 font-bold">※ここで着手金を取りCFを潤沢にする</span>
                      </li>
                      <li className="bg-white p-3 rounded-lg border border-emerald-100 shadow-sm text-sm">
                        <span className="text-gray-800 font-bold block mb-0.5">(4) shikatoru 歯医者予約アプリ</span>
                        <span className="text-xs text-gray-500">初期8万+月0.8万 / SNS初期8万+月0.8万〜</span>
                      </li>
                      <li className="bg-white p-3 rounded-lg border border-emerald-100 shadow-sm text-sm">
                        <span className="text-gray-800 font-bold block mb-0.5">(7)(9) パン屋特化AIシステム</span>
                        <span className="text-xs text-gray-500">最適化 [初期18万+月2.8万]<br />LINE自動化 [初期8万+月0.8万]</span>
                      </li>
                    </ul>
                  </div>

                  <div className="bg-rose-50/60 rounded-xl p-6 border border-rose-100 relative shadow-sm">
                    <div className="absolute -top-3 -left-3 w-8 h-8 bg-red-600 rounded-lg flex items-center justify-center font-black text-white text-sm shadow-sm">
                      03
                    </div>
                    <div className="hidden xl:block absolute top-1/2 -left-5 text-gray-300 transform -translate-y-1/2 bg-white rounded-full">
                      <Icon name="fa-chevron-right" />
                    </div>

                    <h3 className="text-rose-900 font-bold text-lg mb-3 text-center">
                      バックエンド <br />
                      <span className="text-sm font-medium text-rose-600/80">(高額収益・LTV最大化)</span>
                    </h3>
                    <p className="text-gray-600 text-xs mb-4 leading-relaxed">
                      システム導入先へ「経営全体のDX化」として入り込み、利益の柱を構築。
                    </p>
                    <ul className="space-y-3">
                      <li className="bg-white p-4 rounded-lg border-2 border-rose-200 shadow-sm relative overflow-hidden">
                        <div className="absolute right-0 top-0 w-16 h-16 bg-rose-50 rounded-bl-full opacity-80"></div>
                        <span className="text-rose-900 font-black text-lg block mb-1 relative z-10">(6) AIコンサル事業</span>
                        <span className="text-red-600 font-bold block mb-2 text-sm relative z-10">総額 180万円 / 社</span>
                        <p className="text-[10px] text-gray-500 leading-relaxed relative z-10">
                          システムを活かす人材育成と自動化アプリ無料作成をフックに高額契約を巻く。一括前払いでCFを爆発させる。
                        </p>
                      </li>
                      <li className="bg-white p-3 rounded-lg border border-rose-100 shadow-sm text-sm">
                        <span className="text-gray-800 font-bold block mb-1">(5) AI-顧問マッチングサイト</span>
                        <span className="text-[10px] text-gray-500">
                          自社リソースが溢れた際の受け皿。売上の30%を手数料として得るストック資産へ。
                        </span>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>

              <div className="p-5 bg-red-50 border border-red-100 rounded-xl text-center shadow-sm">
                <p className="text-red-900 text-sm font-bold">
                  <strong className="text-red-600 text-base mr-2">【AI-GUNSHI RULE】</strong>
                  カスタマイズ要求は極力断り、8割完成のSaaSとして提供せよ。開発工数を抑えることこそが、利益最大化の最短ルートである。
                </p>
              </div>
            </div>
          )}
        </main>

        {/* フローティング保存ボタン - どのタブからでもアクセス可能 */}
        <button
          onClick={handleSave}
          disabled={isSaving}
          className="fixed bottom-6 right-6 z-40 flex items-center gap-2 px-5 py-4 bg-red-600 hover:bg-red-700 text-white font-black rounded-full shadow-2xl hover:shadow-red-300 transition-all disabled:opacity-50 border-4 border-white"
          title="データを保存"
        >
          <Icon name="fa-floppy-disk" className="text-xl" />
          <span className="hidden sm:inline">{isSaving ? "保存中..." : "保存"}</span>
        </button>
      </div>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
