/* global React, BrandIntakeTools */
const { useState, useEffect, useRef } = React;

/* ============================================================
   Form configuration — 4 steps, 12 fields ("しっかり")
   ============================================================ */
const TYPE_OPTIONS = [
  { v: "person", label: "個人", sub: "フリーランス・専門家" },
  { v: "business", label: "事業・会社", sub: "店舗・チーム" },
  { v: "service", label: "サービス・商品", sub: "プロダクト" },
];
const TONE_OPTIONS = [
  { v: "trust", label: "誠実・信頼感" },
  { v: "friendly", label: "親しみやすい" },
  { v: "pro", label: "専門的・プロ" },
  { v: "innovative", label: "革新的" },
  { v: "premium", label: "高級感" },
];

const STEPS = [
  {
    name: "基本",
    eyebrow: "STEP 01",
    title: "まず、誰のブランディングですか？",
    desc: "ブランドの土台になる情報です。むずかしく考えず、いまの言葉で大丈夫です。",
    fields: [
      { k: "target_type", type: "choice", label: "ブランディングの対象", options: TYPE_OPTIONS, required: true },
      { k: "name", type: "text", label: "名前・屋号・サービス名", placeholder: "例：山田太郎 / 〇〇デザイン事務所 / アプリ名", required: true },
      { k: "what", type: "textarea", label: "一言でいうと、何をしていますか？", hint: "活動・事業・サービスの内容を短く。", placeholder: "例：中小企業向けに、会計と資金繰りをまるごとサポートしています" },
    ],
  },
  {
    name: "届けたい相手",
    eyebrow: "STEP 02",
    title: "誰に、届けたいですか？",
    desc: "相手がはっきりするほど、メッセージは強くなります。",
    fields: [
      { k: "audience", type: "text", label: "届けたい相手（ターゲット）", placeholder: "例：これから独立する30代の個人事業主", required: true },
      { k: "audience_problem", type: "textarea", label: "その人が抱えている悩み・課題", hint: "相手が「まさにそれ」と感じる困りごと。", placeholder: "例：数字が苦手で、お金まわりが不安なまま事業を続けている" },
      { k: "audience_goal", type: "textarea", label: "その人が本当はどうなりたいか（理想）", placeholder: "例：お金の不安なく、本業に集中できる状態になりたい" },
    ],
  },
  {
    name: "強み・価値",
    eyebrow: "STEP 03",
    title: "あなたの強みと、届けられる価値は？",
    desc: "自慢に聞こえても大丈夫。読み手に合わせて整えます。",
    fields: [
      { k: "strength", type: "textarea", label: "強み（複数あれば改行か「、」で）", hint: "得意なこと・人から褒められること。", placeholder: "例：難しい数字をやさしく翻訳できる、伴走型で寄り添う" },
      { k: "proof", type: "textarea", label: "実績・経験・裏付け", hint: "あれば説得力が増します。なければ空欄でOK。", placeholder: "例：これまで120社を支援、元・銀行の融資担当" },
      { k: "value", type: "text", label: "提供できる価値・もたらす変化", placeholder: "例：お金の不安からの解放と、迷わない経営判断", required: true },
    ],
  },
  {
    name: "らしさ・想い",
    eyebrow: "STEP 04",
    title: "最後に、らしさと想いを。",
    desc: "ここがブランドの「体温」になります。",
    fields: [
      { k: "difference", type: "textarea", label: "他者・競合との違い（差別化）", hint: "「ここだけは負けない」という点。", placeholder: "例：税理士より身近で、コンサルより実務に踏み込む" },
      { k: "belief", type: "textarea", label: "大事にしている価値観・想い", placeholder: "例：お金の話を、もっと安心できるものにしたい" },
      { k: "tone", type: "choice", label: "出したいブランドの印象", options: TONE_OPTIONS, required: true },
    ],
  },
];

/* ============================================================
   LANDING
   ============================================================ */
function Landing({ onStart, hasDraft }) {
  return (
    <div className="landing fade-in">
      <div className="landing-top">
        <div className="brandmark">
          <div className="mark">B</div>
          <div className="wordmark">Branding Studio</div>
        </div>
        <div className="nav-note">3ステップ・約5分</div>
      </div>
      <div className="landing-body">
        <div className="kicker on-navy">個人 ・ 事業 ・ サービスのためのブランド設計</div>
        <h1>
          あなたの価値を、<br />
          <span className="accent">伝わる言葉</span>に。
        </h1>
        <p className="landing-lead">
          いくつかの質問に答えるだけ。あなたの強み・想い・届けたい相手を整理し、
          そのまま使えるブランドメッセージとストーリーにまとめます。
        </p>
        <div className="landing-cta">
          <button className="btn btn-gold" onClick={onStart}>
            {hasDraft ? "続きから始める" : "はじめる"} <span className="btn-arrow">→</span>
          </button>
          <span className="time-note">登録不要 ・ 入力は自動保存されます</span>
        </div>
        <div className="steps-strip">
          <div className="cell">
            <div className="num">① HEARING</div>
            <div className="t">ヒアリング</div>
            <div className="d">誰に・何を・どんな強みで届けるかを入力します。</div>
          </div>
          <div className="cell">
            <div className="num">② COMPOSE</div>
            <div className="t">整理・生成</div>
            <div className="d">入力をもとに、方向性とストーリーを組み立てます。</div>
          </div>
          <div className="cell">
            <div className="num">③ OUTPUT</div>
            <div className="t">ブランド出力</div>
            <div className="d">そのまま使える成果物を確認・PDF保存できます。</div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   HEARING (stepped form)
   ============================================================ */
function getSpeechRecognition() {
  return window.SpeechRecognition || window.webkitSpeechRecognition || null;
}

function VoiceControl({ label, onTranscript }) {
  const [status, setStatus] = useState("");
  const [listening, setListening] = useState(false);
  const recognitionRef = useRef(null);

  const startVoice = () => {
    const SpeechRecognition = getSpeechRecognition();
    if (!SpeechRecognition) {
      setStatus("このブラウザは音声入力に対応していません。日本語キーボード入力で続けられます。");
      return;
    }

    if (listening && recognitionRef.current) {
      recognitionRef.current.stop();
      return;
    }

    const recognition = new SpeechRecognition();
    recognition.lang = "ja-JP";
    recognition.interimResults = false;
    recognition.continuous = false;
    recognition.onstart = () => {
      setListening(true);
      setStatus("音声入力中です。日本語で話してください。");
    };
    recognition.onerror = () => {
      setListening(false);
      setStatus("音声入力を使えませんでした。手入力で続けられます。");
    };
    recognition.onend = () => setListening(false);
    recognition.onresult = (event) => {
      const transcript = Array.from(event.results)
        .map((result) => result[0]?.transcript || "")
        .join("");
      if (transcript.trim()) {
        onTranscript(transcript.trim());
        setStatus("音声入力を反映しました。");
      }
    };
    recognitionRef.current = recognition;
    recognition.start();
  };

  return (
    <div className="voice-control" data-voice-control>
      <button
        className={"voice-button" + (listening ? " is-listening" : "")}
        type="button"
        data-action="voice-input"
        aria-label={`${label}を音声入力`}
        title={`${label}を音声入力`}
        onClick={startVoice}
      >
        {listening ? "■" : "🎙"}
      </button>
      <span className="voice-status" aria-live="polite">{status}</span>
    </div>
  );
}

function QuickThreeQuestionMode({ onApply }) {
  const [quick, setQuick] = useState({ who: "", help: "", change: "" });
  const [status, setStatus] = useState("");
  const setQuickField = (key, value) => setQuick((prev) => ({ ...prev, [key]: value }));
  const complete = quick.who.trim() && quick.help.trim() && quick.change.trim();
  const apply = () => {
    if (!complete) {
      setStatus("3問すべてに答えると詳細入力へ反映できます。");
      return;
    }
    const synth = BrandIntakeTools.synthesizeFromQuick(quick);
    onApply(quick);
    setStatus(`${Object.keys(synth.fields).length}項目の下書きを作りました。`);
  };

  return (
    <section className="quick-mode" data-intake-quick-mode="3-question" aria-labelledby="quick-mode-title">
      <div className="quick-mode__header">
        <span className="quick-mode__eyebrow">簡易 3問モード</span>
        <h2 id="quick-mode-title">まず3問だけで下書きを作る</h2>
        <p>短く答えるだけで、通常ヒアリングの主要項目へ仮反映します。</p>
      </div>
      <div className="quick-mode__grid">
        <label className="field">
          <span>1. あなたは誰ですか？</span>
          <textarea value={quick.who} onChange={(e) => setQuickField("who", e.target.value)} placeholder="例：資金繰りを支える会計パートナー" />
          <VoiceControl label="あなたは誰ですか" onTranscript={(text) => setQuickField("who", text)} />
        </label>
        <label className="field">
          <span>2. 誰を助けたいですか？</span>
          <textarea value={quick.help} onChange={(e) => setQuickField("help", e.target.value)} placeholder="例：数字が苦手な個人事業主" />
          <VoiceControl label="誰を助けたいですか" onTranscript={(text) => setQuickField("help", text)} />
        </label>
        <label className="field">
          <span>3. その人をどう変えますか？</span>
          <textarea value={quick.change} onChange={(e) => setQuickField("change", e.target.value)} placeholder="例：お金の不安なく本業に集中できる状態へ導く" />
          <VoiceControl label="その人をどう変えますか" onTranscript={(text) => setQuickField("change", text)} />
        </label>
      </div>
      <div className="quick-mode__actions">
        <button className="btn btn-primary" type="button" disabled={!complete} onClick={apply}>3問から下書き反映</button>
        <span className="voice-status" aria-live="polite">{status}</span>
      </div>
    </section>
  );
}

function QuickDraftPage({ onApply }) {
  return (
    <div className="hearing quick-draft-page">
      <div className="hearing-head">
        <div className="hearing-head-inner">
          <div className="hh-brand">
            <div className="mark">B</div>
            <span>Branding Studio</span>
          </div>
          <div className="hh-step-label">
            PAGE <b>01</b> / QUICK
          </div>
        </div>
        <div className="progress-track">
          <div className="progress-fill" style={{ width: "33.333%" }} />
        </div>
      </div>

      <div className="hearing-body">
        <QuickThreeQuestionMode onApply={onApply} />
      </div>
    </div>
  );
}

function Field({ def, value, onChange }) {
  if (def.type === "choice") {
    return (
      <div className="field">
        <label>{def.label}{!def.required && <span className="opt">任意</span>}</label>
        {def.hint && <div className="hint">{def.hint}</div>}
        <div className="choice-grid">
          {def.options.map((o) => {
            const sel = value === o.v;
            return (
              <button
                key={o.v}
                type="button"
                className={"choice" + (sel ? " sel" : "")}
                onClick={() => onChange(o.v)}
              >
                <span className="tick">{sel ? "✓" : ""}</span>
                <span>{o.label}{o.sub && <span style={{ opacity: .6, fontWeight: 500, marginLeft: 6, fontSize: 12 }}>{o.sub}</span>}</span>
              </button>
            );
          })}
        </div>
      </div>
    );
  }
  return (
    <div className="field">
      <label>{def.label}{!def.required && <span className="opt">任意</span>}</label>
      {def.hint && <div className="hint">{def.hint}</div>}
      {def.type === "textarea" ? (
        <>
          <textarea
            value={value || ""}
            placeholder={def.placeholder}
            onChange={(e) => onChange(e.target.value)}
          />
          <VoiceControl label={def.label} onTranscript={(text) => onChange([value, text].filter(Boolean).join("\n"))} />
        </>
      ) : (
        <>
          <input
            type="text"
            value={value || ""}
            placeholder={def.placeholder}
            onChange={(e) => onChange(e.target.value)}
          />
          <VoiceControl label={def.label} onTranscript={(text) => onChange([value, text].filter(Boolean).join(" "))} />
        </>
      )}
    </div>
  );
}

function Hearing({ form, setForm, step, setStep, onComplete, onExit }) {
  const topRef = useRef(null);
  useEffect(() => {
    if (topRef.current) topRef.current.scrollTop = 0;
    window.scrollTo(0, 0);
  }, [step]);

  const cfg = STEPS[step];
  const setField = (k, v) => setForm((prev) => ({ ...prev, [k]: v }));

  const requiredMissing = cfg.fields
    .filter((f) => f.required)
    .some((f) => !String(form[f.k] || "").trim());

  const pct = ((step + (requiredMissing ? 0 : 1)) / STEPS.length) * 100;
  const isLast = step === STEPS.length - 1;

  return (
    <div className="hearing" ref={topRef}>
      <div className="hearing-head">
        <div className="hearing-head-inner">
          <div className="hh-brand">
            <div className="mark">B</div>
            <span>Branding Studio</span>
          </div>
          <div className="hh-step-label">
            STEP <b>{String(step + 1).padStart(2, "0")}</b> / {String(STEPS.length).padStart(2, "0")}
          </div>
        </div>
        <div className="progress-track">
          <div className="progress-fill" style={{ width: ((step + 1) / STEPS.length) * 100 + "%" }} />
        </div>
      </div>

      <div className="hearing-stepper">
        {STEPS.map((s, i) => (
          <div
            key={i}
            className={"step-pill" + (i === step ? " active" : i < step ? " done" : "")}
          >
            <span className="dot">{i < step ? "✓" : i + 1}</span>
            <span className="step-name">{s.name}</span>
          </div>
        ))}
      </div>

      <div className="hearing-body">
        <div className="form-card fade-in" key={step}>
          <div className="form-card-head">
            <div className="eyebrow">{cfg.eyebrow}</div>
            <h2>{cfg.title}</h2>
            <p>{cfg.desc}</p>
          </div>
          {cfg.fields.map((def) => (
            <Field key={def.k} def={def} value={form[def.k]} onChange={(v) => setField(def.k, v)} />
          ))}

          <div className="form-nav">
            {step === 0 ? (
              <button className="btn-quiet" onClick={onExit}>← 簡易3問に戻る</button>
            ) : (
              <button className="btn btn-ghost" onClick={() => setStep(step - 1)}>← 戻る</button>
            )}
            <div className="right">
              <span className="save-hint"><span className="dot" />自動保存済み</span>
              {isLast ? (
                <button className="btn btn-gold" disabled={requiredMissing} onClick={onComplete}>
                  ブランドを生成する <span className="btn-arrow">→</span>
                </button>
              ) : (
                <button className="btn btn-primary" disabled={requiredMissing} onClick={() => setStep(step + 1)}>
                  次へ <span className="btn-arrow">→</span>
                </button>
              )}
            </div>
          </div>
          {requiredMissing && (
            <div style={{ marginTop: 14, fontSize: 13, color: "var(--muted)", textAlign: "right" }}>
              必須項目を入力すると次へ進めます
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   GENERATING
   ============================================================ */
const GEN_TASKS = [
  "入力内容を読み解いています",
  "強み・差別化ポイントを抽出しています",
  "ターゲットとポジショニングを整理しています",
  "ブランドメッセージを練り上げています",
  "ストーリーと出力をまとめています",
];
function Generating({ onDone }) {
  const [active, setActive] = useState(0);
  useEffect(() => {
    const each = 620;
    const timers = GEN_TASKS.map((_, i) => setTimeout(() => setActive(i + 1), each * (i + 1)));
    const done = setTimeout(onDone, each * GEN_TASKS.length + 700);
    return () => { timers.forEach(clearTimeout); clearTimeout(done); };
  }, []);
  return (
    <div className="generating fade-in">
      <div className="gen-orbit">
        <div className="ring" />
        <div className="ring spin" />
        <div className="core">B</div>
      </div>
      <h2>ブランドを組み立てています</h2>
      <div className="gen-sub">あなたの言葉から、伝わるかたちへ。</div>
      <div className="gen-tasks">
        {GEN_TASKS.map((task, i) => {
          const state = i < active ? "done" : i === active ? "active" : "";
          return (
            <div key={i} className={"gen-task " + state}>
              <span className="gt-ico">{i < active ? "✓" : i + 1}</span>
              <span>{task}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { STEPS, Landing, QuickDraftPage, Hearing, Generating, Field });
