/* Hearing page — form for banner brief */

const PLATFORM_OPTIONS = [
  { id: "instagram", name: "Instagram" },
  { id: "x", name: "X" },
  { id: "facebook", name: "Facebook" },
  { id: "line", name: "LINE" },
  { id: "tiktok", name: "TikTok" },
  { id: "youtube", name: "YouTube" },
  { id: "google", name: "Google Ads" },
];

const RATIO_OPTIONS = [
  { id: "1:1", label: "1:1", subKey: "ratio_sub_1_1", w: 44, h: 44 },
  { id: "4:5", label: "4:5", subKey: "ratio_sub_4_5", w: 36, h: 44 },
  { id: "9:16", label: "9:16", subKey: "ratio_sub_9_16", w: 26, h: 44 },
  { id: "1.91:1", label: "1.91:1", subKey: "ratio_sub_1_91_1", w: 56, h: 28 },
  { id: "16:9", label: "16:9", subKey: "ratio_sub_16_9", w: 56, h: 32 },
];

const RATIO_SUBS = {
  ja: {
    "ratio_sub_1_1": "Feed / 共通",
    "ratio_sub_4_5": "IG フィード",
    "ratio_sub_9_16": "Story / Reels",
    "ratio_sub_1_91_1": "FB / X",
    "ratio_sub_16_9": "YouTube",
  },
  en: {
    "ratio_sub_1_1": "Feed / Universal",
    "ratio_sub_4_5": "IG Feed",
    "ratio_sub_9_16": "Story / Reels",
    "ratio_sub_1_91_1": "FB / X",
    "ratio_sub_16_9": "YouTube",
  },
};

function HearingPage({ form, setForm, onSubmit, onBack, submitState }) {
  const { t, lang } = useI18n();
  const fileInputRef = React.useRef(null);
  const [dragOver, setDragOver] = React.useState(false);

  const previewMode = Boolean(window.__BANNR_DESIGN_PREVIEW__);

  const togglePlatform = (id) => {
    if (previewMode) return;
    setForm((f) => {
      const has = f.platforms.includes(id);
      return { ...f, platforms: has ? f.platforms.filter((p) => p !== id) : [...f.platforms, id] };
    });
  };

  const setRatio = (id) => {
    if (previewMode) return;
    setForm((f) => ({ ...f, ratio: id }));
  };

  const onPickFile = (file) => {
    if (previewMode) return;
    if (!file || !file.type.startsWith("image/")) return;
    if (file.size > 10 * 1024 * 1024) return;
    const reader = new FileReader();
    reader.onload = (e) => setForm((f) => ({ ...f, imageData: e.target.result, imageName: file.name }));
    reader.readAsDataURL(file);
  };

  const onDrop = (e) => {
    e.preventDefault();
    setDragOver(false);
    if (previewMode) return;
    onPickFile(e.dataTransfer.files?.[0]);
  };

  /* Progress / required */
  const required = [
    form.platforms.length > 0,
    !!form.ratio,
    form.name.trim().length > 0,
    form.desc.trim().length > 0,
    !!form.imageData,
    form.target.trim().length > 0,
  ];
  const filled = required.filter(Boolean).length;
  const total = required.length;
  const pct = Math.round((filled / total) * 100);
  const ready = filled === total;
  const isSending = submitState?.status === "sending";
  const isSent = submitState?.status === "sent";
  const submitError = submitState?.status === "error" ? submitState.error : "";

  return (
    <main className="hearing-wrap fade-in">
      <div className="container">
        <div className="page-head">
          <div className="page-head__eyebrow">{t("hearing_eyebrow")}</div>
          <h1 className="page-head__title">{t("hearing_title")}</h1>
          <p className="page-head__lede">{previewMode ? "現在はデザイン確認用の公開版です。入力・画像生成は準備中のため、フォームは操作できません。" : t("hearing_lede")}</p>
          {previewMode && (
            <div className="preview-notice" role="status">
              DESIGN PREVIEW · 入力/生成機能はまだ無効です
            </div>
          )}
        </div>

        <div className="hearing-layout">
          {/* LEFT: form */}
          <div>
            {/* Platforms */}
            <section className="form-block">
              <div className="form-block__label">
                <h3>
                  <span className="step-chip">01</span>
                  {t("field_platforms")}
                  <span className="required">*</span>
                </h3>
                <small>{t("field_platforms_hint")}</small>
              </div>
              <div className="platform-grid">
                {PLATFORM_OPTIONS.map((p) => (
                  <div
                    key={p.id}
                    className="platform-card"
                    data-active={form.platforms.includes(p.id)}
                    onClick={() => togglePlatform(p.id)}
                    aria-disabled={previewMode}
                  >
                    <div className="platform-card__icon" style={{ background: PLATFORM_COLORS[p.id] }}>
                      <PlatformIcon id={p.id} size={15} />
                    </div>
                    <div className="platform-card__name">{p.name}</div>
                  </div>
                ))}
              </div>
            </section>

            {/* Ratio */}
            <section className="form-block">
              <div className="form-block__label">
                <h3>
                  <span className="step-chip">02</span>
                  {t("field_ratio")}
                  <span className="required">*</span>
                </h3>
                <small>{t("field_ratio_hint")}</small>
              </div>
              <div className="ratio-grid">
                {RATIO_OPTIONS.map((r) => (
                  <div
                    key={r.id}
                    className="ratio-card"
                    data-active={form.ratio === r.id}
                    onClick={() => setRatio(r.id)}
                    aria-disabled={previewMode}
                  >
                    <div className="ratio-card__viz" style={{ width: r.w, height: r.h }} />
                    <div>
                      <div className="ratio-card__ratio">{r.label}</div>
                      <div className="ratio-card__sub">{RATIO_SUBS[lang][r.subKey]}</div>
                    </div>
                  </div>
                ))}
              </div>
            </section>

            {/* Name */}
            <section className="form-block">
              <div className="form-block__label">
                <h3>
                  <span className="step-chip">03</span>
                  {t("field_name")}
                  <span className="required">*</span>
                </h3>
              </div>
              <input
                className="input"
                placeholder={t("field_name_placeholder")}
                value={form.name}
                onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
                maxLength={60}
                disabled={previewMode}
              />
            </section>

            {/* Description / URL */}
            <section className="form-block">
              <div className="form-block__label">
                <h3>
                  <span className="step-chip">04</span>
                  {t("field_desc")}
                  <span className="required">*</span>
                </h3>
                <small>{t("field_desc_hint")}</small>
              </div>
              <textarea
                className="textarea"
                placeholder={t("field_desc_placeholder")}
                value={form.desc}
                onChange={(e) => setForm((f) => ({ ...f, desc: e.target.value }))}
                rows={5}
                disabled={previewMode}
              />
            </section>

            {/* Image */}
            <section className="form-block">
              <div className="form-block__label">
                <h3>
                  <span className="step-chip">05</span>
                  {t("field_image")}
                  <span className="required">*</span>
                </h3>
              </div>
              <div
                className={"dropzone " + (form.imageData ? "dropzone--has-img" : "")}
                data-drag={dragOver}
                onClick={() => !previewMode && fileInputRef.current && fileInputRef.current.click()}
                onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
                onDragLeave={() => setDragOver(false)}
                onDrop={onDrop}
              >
                {form.imageData && (
                  <React.Fragment>
                    <div className="dropzone__preview" style={{ backgroundImage: `url(${form.imageData})` }} />
                    <button
                      type="button"
                      className="dropzone__remove"
                      onClick={(e) => {
                        e.stopPropagation();
                        if (!previewMode) setForm((f) => ({ ...f, imageData: null, imageName: "" }));
                      }}
                    >
                      <Close size={12} />
                    </button>
                  </React.Fragment>
                )}
                {!form.imageData && (
                  <React.Fragment>
                    <div className="dropzone__icon">
                      <Upload size={22} />
                    </div>
                    <div className="dropzone__title">{t("field_image_drop")}</div>
                    <div className="dropzone__sub">{t("field_image_or")}</div>
                  </React.Fragment>
                )}
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  style={{ display: "none" }}
                  onChange={(e) => onPickFile(e.target.files?.[0])}
                  disabled={previewMode}
                />
              </div>
            </section>

            {/* Target */}
            <section className="form-block">
              <div className="form-block__label">
                <h3>
                  <span className="step-chip">06</span>
                  {t("field_target")}
                  <span className="required">*</span>
                </h3>
                <small>{t("field_target_hint")}</small>
              </div>
              <textarea
                className="textarea"
                placeholder={t("field_target_placeholder")}
                value={form.target}
                onChange={(e) => setForm((f) => ({ ...f, target: e.target.value }))}
                rows={3}
                disabled={previewMode}
              />
            </section>

            {/* Submit */}
            <div className="submit-row">
              <button className="btn btn--ghost" onClick={onBack}>{t("submit_back")}</button>
              <div style={{ display: "flex", alignItems: "center", gap: 14, marginLeft: "auto" }}>
                {!previewMode && !ready && (
                  <span className="dim-2" style={{ fontSize: 13 }}>
                    {t("submit_warn", { n: total - filled })}
                  </span>
                )}
                {previewMode && (
                  <span className="dim-2" style={{ fontSize: 13 }}>
                    デザイン確認中 · 入力はまだできません
                  </span>
                )}
                <button
                  className="btn btn--primary btn--lg"
                  onClick={onSubmit}
                  disabled={previewMode || !ready || isSending || isSent}
                  style={{ opacity: !previewMode && ready && !isSending && !isSent ? 1 : 0.45, pointerEvents: !previewMode && ready && !isSending && !isSent ? "auto" : "none" }}
                >
                  <Sparkles size={16} />
                  {previewMode ? "準備中" : isSending ? "生成中…" : isSent ? "生成済み" : t("submit_button")}
                </button>
              </div>
              {isSent && (
                <div className="ai-submit-status ai-submit-status--ok" role="status">
生成が完了しました。監査済みの画像だけを結果画面に表示します。
                </div>
              )}
              {submitError && (
                <div className="ai-submit-status ai-submit-status--error" role="alert">
                  AIへの送信に失敗しました: {submitError}
                </div>
              )}
            </div>
          </div>

          {/* RIGHT: summary */}
          <aside className="hearing-side">
            <div className="summary-card">
              <h4>{t("summary_title")}</h4>
              <div className="progress-track">
                <div className="progress-bar" style={{ width: pct + "%" }} />
              </div>
              <div className="dim-2" style={{ fontSize: 12, marginBottom: 12 }}>
                {t("progress_label")} · {filled}/{total}
              </div>

              <div className="summary-row">
                <div className="summary-row__key">{t("summary_platforms")}</div>
                <div className="summary-row__val">
                  {form.platforms.length === 0 ? <span className="dim-2">{t("summary_none")}</span> : (
                    <div style={{ display: "inline-flex", gap: 4, justifyContent: "flex-end", flexWrap: "wrap" }}>
                      {form.platforms.map((p) => (
                        <span key={p} title={p} style={{
                          width: 18, height: 18, borderRadius: 4, display: "inline-grid", placeItems: "center",
                          background: PLATFORM_COLORS[p], color: "#fff",
                        }}>
                          <PlatformIcon id={p} size={10} />
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              </div>

              <div className="summary-row">
                <div className="summary-row__key">{t("summary_ratio")}</div>
                <div className="summary-row__val">
                  {form.ratio || <span className="dim-2">{t("summary_none")}</span>}
                </div>
              </div>

              <div className="summary-row">
                <div className="summary-row__key">{t("summary_name")}</div>
                <div className="summary-row__val">
                  {form.name || <span className="dim-2">{t("summary_none")}</span>}
                </div>
              </div>

              <div className="summary-row">
                <div className="summary-row__key">{t("summary_image")}</div>
                <div className="summary-row__val">
                  {form.imageData ? (
                    <div style={{
                      width: 28, height: 28, borderRadius: 4, display: "inline-block",
                      backgroundImage: `url(${form.imageData})`, backgroundSize: "cover", backgroundPosition: "center",
                      verticalAlign: "middle",
                    }} />
                  ) : <span className="dim-2">{t("summary_none")}</span>}
                </div>
              </div>

              <div className="summary-row">
                <div className="summary-row__key">{t("summary_target")}</div>
                <div className="summary-row__val">
                  {form.target ? (form.target.length > 32 ? form.target.slice(0, 32) + "…" : form.target) : <span className="dim-2">{t("summary_none")}</span>}
                </div>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { HearingPage });
