/* Main App — view routing + tweaks + state */

function App() {
  const allowedViews = window.__BANNR_DESIGN_PREVIEW__ ? ["top", "hearing", "result"] : ["top", "hearing", "result", "funnel"];
  const initialHash = window.location.hash.replace("#", "");
  const initialView = allowedViews.includes(initialHash) ? initialHash : "top";
  const [view, setView] = React.useState(initialView); // top | hearing | result | funnel
  const [form, setForm] = React.useState({
    platforms: [],
    ratio: "",
    name: "",
    desc: "",
    imageData: null,
    imageName: "",
    target: "",
  });
  const [aiSubmitState, setAiSubmitState] = React.useState({ status: "idle", error: "", response: null });
  const [generatedBanner, setGeneratedBanner] = React.useState(null);
  const [tweaks, setTweak] = useTweaks(window.__TWEAKS__ || {
    accent: "indigo",
    topHero: "kinetic",
    bannerTemplate: "split",
  });

  /* Apply accent tweak globally */
  React.useEffect(() => {
    const root = document.documentElement;
    const accents = {
      indigo:  { a: "#818cf8", a2: "#a78bfa", a3: "#6366f1", soft: "rgba(129,140,248,0.14)", glow: "rgba(129,140,248,0.35)" },
      emerald: { a: "#34d399", a2: "#6ee7b7", a3: "#10b981", soft: "rgba(52,211,153,0.14)", glow: "rgba(52,211,153,0.35)" },
      rose:    { a: "#fb7185", a2: "#fda4af", a3: "#e11d48", soft: "rgba(251,113,133,0.14)", glow: "rgba(251,113,133,0.35)" },
      amber:   { a: "#fbbf24", a2: "#fcd34d", a3: "#d97706", soft: "rgba(251,191,36,0.14)", glow: "rgba(251,191,36,0.35)" },
    };
    const p = accents[tweaks.accent] || accents.indigo;
    root.style.setProperty("--accent", p.a);
    root.style.setProperty("--accent-2", p.a2);
    root.style.setProperty("--accent-3", p.a3);
    root.style.setProperty("--accent-soft", p.soft);
    root.style.setProperty("--accent-glow", p.glow);
    root.style.setProperty("--border-focus", p.a);
  }, [tweaks.accent]);

  const goto = (v) => {
    setView(v);
    window.history.replaceState(null, "", `#${v}`);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  React.useEffect(() => {
    setAiSubmitState((s) => {
      if (s.status === "idle" || s.status === "sending") return s;
      setGeneratedBanner(null);
      return { status: "idle", error: "", response: null };
    });
  }, [form]);

  const handleBannerSubmit = async () => {
    if (window.__BANNR_DESIGN_PREVIEW__) {
      setAiSubmitState({
        status: "idle",
        error: "現在はデザイン確認用の公開版です。入力・生成機能は準備中です。",
        response: null,
      });
      return;
    }
    if (aiSubmitState.status === "sending" || aiSubmitState.status === "sent") return;
    setAiSubmitState({ status: "sending", error: "", response: null });
    try {
      const lang = document.documentElement.lang || "ja";
      const response = await window.submitBannerBriefToAI(form, lang);
      setAiSubmitState({ status: "sent", error: "", response });
      if (response?.image) {
        setGeneratedBanner(response);
        goto("result");
      }
    } catch (e) {
      console.error("[BANNR] AI submit failed:", e);
      setAiSubmitState({ status: "error", error: e.message || String(e), response: null });
    }
  };

  return (
    <I18nProvider>
      <div className="app-shell">
        <HeaderWithI18n onNav={goto} current={view} />
        {view === "top" && <TopPage onStart={() => goto("hearing")} />}
        {view === "hearing" && (
          <HearingPage
            form={form}
            setForm={setForm}
            onSubmit={handleBannerSubmit}
            submitState={aiSubmitState}
            onBack={() => goto("top")}
          />
        )}
        {view === "result" && (
          <ResultPage
            form={form}
            generatedBanner={generatedBanner}
            onBack={() => goto("hearing")}
            onOpenFunnel={() => goto("funnel")}
          />
        )}
        {view === "funnel" && (
          <FunnelLabPage
            form={form}
            onBack={() => goto("result")}
          />
        )}
        <Footer />
        <BannrTweaks tweaks={tweaks} setTweak={setTweak} />
      </div>
    </I18nProvider>
  );
}

/* Header needs to be inside I18nProvider; wrap it */
function HeaderWithI18n(props) {
  return <Header {...props} />;
}

/* Tweaks panel content */
function BannrTweaks({ tweaks, setTweak }) {
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Brand">
        <TweakColor
          label="Accent color"
          value={tweaks.accent}
          options={["indigo", "emerald", "rose", "amber"]}
          colorMap={{
            indigo: "#818cf8",
            emerald: "#34d399",
            rose: "#fb7185",
            amber: "#fbbf24",
          }}
          onChange={(v) => setTweak("accent", v)}
        />
      </TweakSection>
      <TweakSection label="Result page">
        <TweakRadio
          label="Default template"
          value={tweaks.bannerTemplate}
          options={[
            { value: "split", label: "Split" },
            { value: "overlay", label: "Overlay" },
            { value: "minimal", label: "Minimal" },
          ]}
          onChange={(v) => setTweak("bannerTemplate", v)}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

/* Custom TweakColor wrapper using the swatch approach the docs mention,
   but rendered as named-option swatches keyed off our colorMap */
function TweakColor({ label, value, options, colorMap, onChange }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      <div style={{ fontSize: 12, color: "var(--text-2)", fontWeight: 500 }}>{label}</div>
      <div style={{ display: "flex", gap: 8 }}>
        {options.map((opt) => (
          <button
            key={opt}
            onClick={() => onChange(opt)}
            title={opt}
            style={{
              width: 32, height: 32, borderRadius: 8, cursor: "pointer",
              background: colorMap[opt],
              border: value === opt ? "2px solid #fff" : "2px solid transparent",
              outline: value === opt ? "1px solid rgba(255,255,255,0.4)" : "1px solid var(--border)",
              outlineOffset: 0,
              padding: 0,
            }}
          />
        ))}
      </div>
    </div>
  );
}

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