// Monitor conditions, application form, and footer.

const { CTAButton, ImgFrame, Ornament, SafetyNotice } = window;

const priceOptions = {
  trial3: ["500円未満", "500〜980円", "980〜1,280円", "1,280円以上でも内容次第", "価格次第では試さない"],
  trial10: ["1,500円未満", "1,500〜2,480円", "2,480〜2,980円", "2,980円以上でも内容次第", "10包は不要"],
  set: ["3,980円未満", "3,980〜4,980円", "4,980〜5,980円", "5,980〜6,980円", "セットではなくトリートメント単品がよい"]
};

const agreementItems = [
  "入力内容をモニター選考および連絡のために使用することに同意します。",
  "使用後アンケートに協力できる場合のみ応募してください。",
  "商品は開発中であり、仕様・内容が変更になる可能性があることを確認しました。",
  "使用中または使用後に異常を感じた場合は使用を中止することを確認しました。"
];

const MonitorConditions = () => {
  const conditions = [
    { label: "対象", body: "30代・40代女性で、サウナをご利用いただける方" },
    { label: "お悩み", body: "サウナ後の髪のパサつき、広がり、きしみが気になる方" },
    { label: "ご協力内容", body: "使用感・香り・洗い流しやすさ等のアンケート" },
    { label: "人数", body: "先行モニター 10〜20名限定／選考のうえご連絡" }
  ];

  return (
    <section className="pad-mobile" style={{ padding: "96px 56px", background: "#fff" }} aria-labelledby="conditions-title">
      <div className="grid-2" style={{ display: "grid", gridTemplateColumns: "minmax(0,.95fr) minmax(0,1.05fr)", gap: 46, alignItems: "center", maxWidth: 1050, margin: "0 auto" }}>
        <div>
          <p className="latin" style={{ fontSize: 11, color: "var(--mocha)", letterSpacing: ".3em", margin: "0 0 12px" }}>MONITOR CONDITIONS</p>
          <h2 id="conditions-title" className="mincho" style={{ fontSize: 28, fontWeight: 500, margin: "0 0 18px", lineHeight: 1.5 }}>
            先行モニター募集要項
          </h2>
          <div style={{ height: 1, width: 48, background: "var(--mocha)", opacity: .55, margin: "0 0 22px" }} />
          <p style={{ fontSize: 13, color: "var(--ink-soft)", lineHeight: 2, margin: 0 }}>
            開発中のサウナ前ヘアケア「SAUNA HAIR VEIL」を、実際のサウナ習慣の中でお試しいただける方を募集しています。
          </p>
        </div>
        <ImgFrame src="assets/lifestyle-sauna-bag.jpg" alt="サウナバッグに入ったヘアケア用品のイメージ" frameClass="img-frame--wide" tag="LIFESTYLE" />
      </div>
      <div className="grid-4" style={{ maxWidth: 1000, margin: "54px auto 0", display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
        {conditions.map((condition, index) => (
          <article key={condition.label} style={{ background: "var(--ivory-2)", border: "1px solid var(--line-soft)", padding: "22px 20px", borderRadius: 4 }}>
            <p className="latin" style={{ fontSize: 11, color: "var(--mocha)", letterSpacing: ".24em", margin: "0 0 6px" }}>NO. 0{index + 1}</p>
            <h3 className="mincho" style={{ fontSize: 13, margin: "0 0 6px" }}>{condition.label}</h3>
            <p style={{ fontSize: 12, color: "var(--ink-soft)", lineHeight: 1.85, margin: 0 }}>{condition.body}</p>
          </article>
        ))}
      </div>
    </section>
  );
};

const RequiredBadge = ({ required }) => (
  <span style={{ fontSize: 9, padding: "2px 6px", background: required ? "var(--mocha)" : "#fff", color: required ? "#fff" : "var(--ink-mute)", border: required ? "0" : "1px solid var(--line)", letterSpacing: ".1em", borderRadius: 2 }}>
    {required ? "必須" : "任意"}
  </span>
);

const FormRow = ({ id, label, required = false, full = false, children }) => (
  <div className={`form-row ${full ? "full" : ""}`}>
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <label htmlFor={id} className="mincho" style={{ fontSize: 13, color: "var(--ink)", fontWeight: 500 }}>{label}</label>
      <RequiredBadge required={required} />
    </div>
    <div>{children}</div>
  </div>
);

const TextInput = ({ id, name, type = "text", placeholder, required = false }) => (
  <input className="field" id={id} name={name} type={type} placeholder={placeholder} required={required} />
);

const Select = ({ id, name, options, placeholder, required = false }) => (
  <select className="field" id={id} name={name} defaultValue="" required={required}>
    <option value="" disabled>{placeholder}</option>
    {options.map((option) => <option key={option} value={option}>{option}</option>)}
  </select>
);

const RadioGroup = ({ name, options, required = false }) => (
  <div className="radio-stack" role="radiogroup">
    {options.map((option, index) => {
      const id = `${name}-${index}`;
      return (
        <label key={option} htmlFor={id}>
          <input id={id} name={name} type="radio" value={option} required={required && index === 0} />
          <span>{option}</span>
        </label>
      );
    })}
  </div>
);

const CheckboxGroup = ({ name, options }) => (
  <div className="radio-stack">
    {options.map((option, index) => {
      const id = `${name}-${index}`;
      return (
        <label key={option} htmlFor={id}>
          <input id={id} name={name} type="checkbox" value={option} />
          <span>{option}</span>
        </label>
      );
    })}
  </div>
);

const AgreementChecks = ({ values, onChange }) => (
  <div className="check-list">
    {agreementItems.map((item, index) => {
      const id = `agreement-${index}`;
      return (
        <label key={item} htmlFor={id}>
          <input
            id={id}
            name="agreements"
            value={item}
            type="checkbox"
            checked={values[index]}
            onChange={(event) => onChange(index, event.target.checked)}
            required
          />
          <span>{item}</span>
        </label>
      );
    })}
  </div>
);

const collectFormData = (form) => {
  const formData = new FormData(form);
  const values = {};

  for (const [key, value] of formData.entries()) {
    if (values[key]) {
      values[key] = Array.isArray(values[key]) ? [...values[key], value] : [values[key], value];
    } else {
      values[key] = value;
    }
  }

  return values;
};

const MonitorForm = ({ onSubmit }) => {
  const [agreements, setAgreements] = React.useState(agreementItems.map(() => false));
  const [status, setStatus] = React.useState("");
  const allAgreed = agreements.every(Boolean);

  const updateAgreement = (index, checked) => {
    setAgreements((current) => current.map((value, itemIndex) => itemIndex === index ? checked : value));
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    const form = event.currentTarget;

    if (!allAgreed) {
      setStatus("同意項目をすべて確認してください。");
      return;
    }

    if (!form.reportValidity()) return;

    const payload = collectFormData(form);
    const result = await onSubmit(payload);

    if (result?.ok) {
      setStatus("仮受付が完了しました。選考のうえ、後日メールにてご連絡します。");
      form.reset();
      setAgreements(agreementItems.map(() => false));
    } else {
      setStatus(result?.message || "送信内容を確認してください。");
    }
  };

  return (
    <section id="entry" className="pad-mobile" style={{ padding: "96px 56px", background: "var(--ivory-2)" }} aria-labelledby="form-title">
      <div style={{ textAlign: "center", marginBottom: 40 }}>
        <p className="latin" style={{ fontSize: 11, color: "var(--mocha)", letterSpacing: ".3em", margin: "0 0 10px" }}>APPLICATION FORM</p>
        <h2 id="form-title" className="mincho" style={{ fontSize: 26, fontWeight: 500, margin: 0 }}>応募フォーム</h2>
      </div>

      <form onSubmit={handleSubmit} style={{ maxWidth: 940, margin: "0 auto", background: "#fff", border: "1px solid var(--line-soft)", borderRadius: 4, padding: "34px 42px", boxShadow: "0 24px 50px -32px rgba(82,68,52,.22)" }}>
        <div className="sr-only" aria-hidden="true">
          <label htmlFor="company-name">会社名</label>
          <input id="company-name" name="companyName" tabIndex="-1" autoComplete="off" />
        </div>

        <div className="form-grid">
          <FormRow id="name" label="お名前" required>
            <TextInput id="name" name="name" placeholder="例）山田 花子" required />
          </FormRow>
          <FormRow id="age" label="年代" required>
            <Select id="age" name="age" placeholder="選択してください" required options={["20代", "30代前半", "30代後半", "40代前半", "40代後半", "50代以上"]} />
          </FormRow>
          <FormRow id="email" label="メールアドレス" required full>
            <TextInput id="email" name="email" type="email" placeholder="例）sample@example.com" required />
          </FormRow>
          <FormRow id="sauna-frequency" label="サウナ頻度" required>
            <Select id="sauna-frequency" name="saunaFrequency" placeholder="選択してください" required options={["週2回以上", "週1回程度", "月2〜3回", "月1回程度", "まれに"]} />
          </FormRow>
          <FormRow id="hair-length" label="髪の長さ" required>
            <Select id="hair-length" name="hairLength" placeholder="選択してください" required options={["ショート", "ボブ", "ミディアム", "セミロング", "ロング"]} />
          </FormRow>
          <FormRow id="hair-history" label="カラー・パーマ等" full>
            <CheckboxGroup name="hairHistory" options={["カラー", "白髪染め", "パーマ", "縮毛矯正", "ヘナ・ヘアマニキュア", "とくになし"]} />
          </FormRow>
          <FormRow id="hair-concerns" label="髪のお悩み" full>
            <CheckboxGroup name="hairConcerns" options={["パサつき", "広がり", "うねり", "カラー後の乾燥", "切れ毛・枝毛", "ツヤ不足", "その他"]} />
          </FormRow>
          <FormRow id="public-use" label="公共サウナでの使用" required full>
            <RadioGroup name="publicUse" required options={["施設ルールを確認して使いたい", "施設によって判断したい", "自宅や宿泊施設などで試したい"]} />
          </FormRow>
          <FormRow id="price-3" label="3包の価格感" required full>
            <RadioGroup name="priceTrial3" required options={priceOptions.trial3} />
          </FormRow>
          <FormRow id="price-10" label="10包の価格感" required full>
            <RadioGroup name="priceTrial10" required options={priceOptions.trial10} />
          </FormRow>
          <FormRow id="price-set" label="ハット付きセット" required full>
            <RadioGroup name="priceSet" required options={priceOptions.set} />
          </FormRow>
          <FormRow id="instagram" label="Instagram">
            <TextInput id="instagram" name="instagram" placeholder="@your_handle（任意）" />
          </FormRow>
        </div>

        <div style={{ marginTop: 22, padding: "16px 18px", background: "var(--ivory-2)", borderRadius: 3 }}>
          <p style={{ fontSize: 12, color: "var(--ink-soft)", lineHeight: 1.8, margin: "0 0 12px" }}>
            ご入力いただいた情報は、モニター選考およびご連絡の目的にのみ使用します。
          </p>
          {/* TODO: プライバシーポリシーページURLを設定 */}
          <p style={{ fontSize: 11, color: "var(--ink-mute)", lineHeight: 1.8, margin: "0 0 14px" }}>
            プライバシーポリシー: <a href="#" aria-label="プライバシーポリシー 未設定">未設定</a>
          </p>
          <AgreementChecks values={agreements} onChange={updateAgreement} />
        </div>

        <div style={{ marginTop: 30, display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
          <CTAButton type="submit" label="モニター募集に申し込む" section="form" disabled={!allAgreed} />
          {status && <p role="status" aria-live="polite" style={{ color: "var(--ink-soft)", fontSize: 13, lineHeight: 1.8, margin: 0 }}>{status}</p>}
        </div>
      </form>
    </section>
  );
};

const FinalCTA = ({ onCta }) => (
  <section className="pad-mobile" style={{ padding: "92px 56px", textAlign: "center", background: "linear-gradient(180deg, var(--ivory) 0%, var(--ivory-3) 100%)" }} aria-labelledby="final-title">
    <Ornament />
    <p className="latin" style={{ fontSize: 11, color: "var(--mocha-dark)", letterSpacing: ".34em", margin: "18px 0 16px" }}>JOIN THE PRE-LAUNCH MONITOR</p>
    <h2 id="final-title" className="mincho" style={{ fontSize: 32, fontWeight: 500, margin: "0 0 18px", lineHeight: 1.5 }}>あなたの声を、商品づくりに。</h2>
    <p style={{ fontSize: 14, color: "var(--ink-soft)", margin: "0 0 34px", lineHeight: 2 }}>
      SAUNA HAIR VEILの先行モニターにご協力ください。
    </p>
    <CTAButton onClick={onCta} label="先行モニターに応募する" section="final" size="lg" />
  </section>
);

const Footer = () => (
  <footer style={{ padding: "42px 56px 58px", background: "var(--ivory-3)", borderTop: "1px solid var(--line)" }}>
    <SafetyNotice />
    <div style={{ marginTop: 28, paddingTop: 20, borderTop: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 18, flexWrap: "wrap", maxWidth: 1000, marginLeft: "auto", marginRight: "auto" }}>
      <div className="latin" style={{ fontSize: 13, color: "var(--ink)", fontWeight: 500, letterSpacing: ".2em" }}>SAUNA&nbsp;HAIR&nbsp;VEIL</div>
      <div className="latin" style={{ fontSize: 10, color: "var(--ink-mute)", letterSpacing: ".16em" }}>© 2026 SAUNA HAIR VEIL</div>
    </div>
  </footer>
);

Object.assign(window, { MonitorConditions, MonitorForm, FinalCTA, Footer, collectFormData });
