(() => {
  window.MamoruApp = window.MamoruApp || {};

  const { useEffect, useState } = React;
  const { C, NS, PRODUCTS, CATEGORIES, Wrap, SectionHeader, TextList, useIsMobile } = window.MamoruApp;

  window.MamoruApp.ProductDetailPage = function ProductDetailPage({ productId, setPage }) {
    const mobile = useIsMobile();
    const product = PRODUCTS.find((p) => String(p.id) === String(productId)) || PRODUCTS[0];
    const category = CATEGORIES.find((c) => c.key === product.cat) || {};
    const related = PRODUCTS.filter((p) => p.id !== product.id && (p.cat === product.cat || p.scene.some((s) => product.scene.includes(s)))).slice(0, 3);
    const reviewStorageKey = `mamoru-reviews-${product.id}`;
    const [reviews, setReviews] = useState([]);
    const [reviewName, setReviewName] = useState("");
    const [reviewRating, setReviewRating] = useState("4|使いやすかった");
    const [reviewBody, setReviewBody] = useState("");
    const [reviewMessage, setReviewMessage] = useState("");
    const pendingReviews = reviews.filter((review) => review.status === "pending");
    const displayReviews = [...(product.seededReviews || [])];

    useEffect(() => {
      try {
        const saved = localStorage.getItem(reviewStorageKey);
        setReviews(saved ? JSON.parse(saved) : []);
      } catch {
        setReviews([]);
      }
      setReviewName("");
      setReviewRating("4|使いやすかった");
      setReviewBody("");
    }, [reviewStorageKey]);

    const saveReviews = (nextReviews) => {
      setReviews(nextReviews);
      try {
        localStorage.setItem(reviewStorageKey, JSON.stringify(nextReviews));
      } catch {}
    };

    const exportPendingReviews = () => {
      if (pendingReviews.length === 0) {
        setReviewMessage("まだ保存された口コミはありません。口コミが届いたらここから書き出せます。");
        return;
      }
      try {
        const payload = {
          productId: product.id,
          productName: product.name,
          exportedAt: new Date().toISOString(),
          reviews: pendingReviews,
        };
        const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = `reviews-${product.id}.json`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        setReviewMessage("非公開口コミを JSON ファイルとして書き出しました。");
      } catch {
        setReviewMessage("書き出しに失敗しました。もう一度お試しください。");
      }
    };

    const specRows = [
      ["価格", product.specs?.price || product.price],
      ["向いているシーン", product.specs?.scene || product.scene.join("・")],
      ["分類", `${product.cat} / ${category.label || ""}`],
      ["短い特徴", product.tagline],
      ["サイズ", product.specs?.size || "商品により異なります"],
      ["電池/充電", product.specs?.power || "商品により異なります"],
    ];

    const renderPurchaseCta = () => (
      product.externalUrl ? (
        <a href={product.externalUrl} target="_blank" rel="noreferrer" className="buy-link-button">
          {product.shopName || "外部サイト"}で確認する
        </a>
      ) : (
        <span className="buy-link-button is-disabled">リンク準備中</span>
      )
    );

    return (
      <div className="page-shell">
      <Wrap className="page-wrap">
        <div className="page-back-links" style={{ marginBottom: mobile ? 22 : 28 }}>
          <button onClick={() => setPage("products")} className="page-back-link">
            ← 商品一覧へ戻る
          </button>
          <button onClick={() => setPage("home")} className="page-back-link">
            トップへ
          </button>
        </div>

        <section className="detail-hero" style={mobile ? { marginBottom: 30 } : undefined}>
          <div className="detail-hero__media-shell" style={mobile ? { padding: 18 } : undefined}>
            {product.imageSrc ? (
              <div className="detail-hero__image-frame">
                <img className="detail-hero__image" src={product.imageSrc} alt={product.imageAlt || product.name} />
              </div>
            ) : (
              <div className="detail-hero__image-frame">
                <img
                  className="detail-hero__image"
                  src="./assets/images/product-fallback-soft.svg"
                  alt={product.imageAlt || `${product.name} のイメージ`}
                />
              </div>
            )}
          </div>
          <div>
            <div className="detail-hero__kicker">
              {product.cat} / {category.label || "分類"}
            </div>
            <h1 className="detail-hero__title">
              {product.name}
            </h1>
            <p className="detail-hero__summary">
              {product.summary || product.desc}
            </p>
            <div className="detail-chip-row">
              {product.scene.map((s) => (
                <span key={s} className="badge badge--soft">{s}</span>
              ))}
              {product.tag && <span className="badge badge--soft">{product.tag}</span>}
            </div>
            <div className="detail-mini-facts">
              <div className="detail-mini-fact">
                <div className="detail-mini-fact__label">おすすめ</div>
                <div className="detail-mini-fact__value">{product.fit}</div>
              </div>
              <div className="detail-mini-fact">
                <div className="detail-mini-fact__label">価格</div>
                <div className="detail-mini-fact__value">{product.price}</div>
              </div>
              <div className="detail-mini-fact">
                <div className="detail-mini-fact__label">分類</div>
                <div className="detail-mini-fact__value">{product.cat} / {category.label || "分類"}</div>
              </div>
            </div>
            <div className="detail-hero__purchase">
              {renderPurchaseCta()}
              <button onClick={() => setPage(`category:${product.cat}`)} className="text-link text-link--subtle" style={{ fontSize: 13 }}>
                この分類を見る →
              </button>
            </div>
            {product.priceNote && <div className="detail-price-note">{product.priceNote}</div>}
          </div>
        </section>

        <div className="detail-content-layout">
          <div className="detail-content-main">
            <section className="detail-section">
              <div className="detail-section__head">
                <div className="detail-section__eyebrow">How To Use</div>
                <h2 className="detail-section__title">具体的な使い方</h2>
              </div>
              <TextList items={product.usage || []} />
            </section>

            <section className="detail-section">
              <div className="detail-section__head">
                <div className="detail-section__eyebrow">Recommended For</div>
                <h2 className="detail-section__title">どんな人におすすめか</h2>
              </div>
              <TextList items={product.recommendedFor || [product.fit]} />
            </section>

            <section className="detail-section">
              <div className="detail-section__head">
                <div className="detail-section__eyebrow">Pros And Cons</div>
                <h2 className="detail-section__title">メリット / デメリット</h2>
              </div>
              <div className="detail-pros-cons">
                <div className="detail-pros-cons__col">
                  <div className="detail-pros-cons__label">メリット</div>
                  <TextList items={product.pros || []} />
                </div>
                <div className="detail-pros-cons__col">
                  <div className="detail-pros-cons__label">デメリット</div>
                  <TextList items={product.cons || []} />
                </div>
              </div>
            </section>

            <section className="detail-section">
              <div className="detail-section__head">
                <div className="detail-section__eyebrow">Reviews</div>
                <h2 className="detail-section__title">口コミ / レビュー要約</h2>
              </div>
              <p style={{ fontSize: 13, fontFamily: NS, color: C.muted, lineHeight: 1.9, marginBottom: 16 }}>{product.reviewSummary}</p>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 16 }}>
                <span className="badge badge--soft">公開表示は固定口コミのみ</span>
                <span className="badge badge--outline">非公開保存 {pendingReviews.length} 件</span>
              </div>
              {displayReviews.length > 0 ? (
                <div className="review-list">
                  {displayReviews.map((review) => (
                    <article key={review.id} className="review-item">
                      <div className="review-item__head">
                        <strong className="review-item__name">{review.name || "匿名"}</strong>
                        <span className="review-item__rating">{review.rating || `${"★".repeat(review.stars || 4)}${"☆".repeat(5 - (review.stars || 4))}`}</span>
                      </div>
                      {review.ratingLabel && <div className="review-item__date" style={{ marginTop: -4 }}>{review.ratingLabel}</div>}
                      <p className="review-item__body">{review.body}</p>
                      <div className="review-item__date">{review.date}</div>
                    </article>
                  ))}
                </div>
              ) : (
                <p style={{ fontSize: 12, fontFamily: NS, color: C.mutedLight, lineHeight: 1.8 }}>
                  まだ口コミはありません。使いやすさや持ち歩きやすさを先に書いておけます。
                </p>
              )}
            </section>

            <section className="detail-section detail-section--soft">
              <div className="review-form__header">
                <div className="detail-section__eyebrow">Write A Review</div>
                <div className="detail-section__title" style={{ marginBottom: 6 }}>口コミを書く</div>
                <p className="review-form__note">届いた口コミはすべて非公開のままこのブラウザに保存します。公開前に、内容を見てから僕たちで判断できる形です。</p>
              </div>
              <form
                className="review-form"
                onSubmit={(e) => {
                  e.preventDefault();
                  if (!reviewBody.trim()) return;
                  const [starsValue, ratingLabel] = reviewRating.split("|");
                  const stars = Math.max(1, Math.min(5, Number(starsValue) || 4));
                  const nextReviews = [
                    {
                      id: `${Date.now()}`,
                      name: reviewName.trim(),
                      stars,
                      rating: `${"★".repeat(stars)}${"☆".repeat(5 - stars)}`,
                      ratingLabel,
                      body: reviewBody.trim(),
                      date: new Date().toLocaleDateString("ja-JP"),
                      status: "pending",
                    },
                    ...reviews,
                  ];
                  saveReviews(nextReviews);
                  setReviewName("");
                  setReviewRating("4|使いやすかった");
                  setReviewBody("");
                  setReviewMessage("口コミを非公開で保存しました。内容を確認してから公開判断できます。");
                }}
              >
                <div className="review-form__grid">
                  <label className="review-field">
                    <span className="review-field__label">名前</span>
                    <input
                      className="review-field__input"
                      type="text"
                      value={reviewName}
                      onChange={(e) => setReviewName(e.target.value)}
                      placeholder="匿名でも大丈夫です"
                    />
                  </label>
                  <label className="review-field">
                    <span className="review-field__label">ひとこと評価</span>
                    <select
                      className="review-field__input"
                      value={reviewRating}
                      onChange={(e) => setReviewRating(e.target.value)}
                    >
                      <option value="5|かなり満足">★★★★★ かなり満足</option>
                      <option value="4|使いやすかった">★★★★☆ 使いやすかった</option>
                      <option value="4|見た目が良かった">★★★★☆ 見た目が良かった</option>
                      <option value="4|持ち歩きやすい">★★★★☆ 持ち歩きやすい</option>
                      <option value="3|比較候補として良い">★★★☆☆ 比較候補として良い</option>
                    </select>
                  </label>
                </div>
                <label className="review-field">
                  <span className="review-field__label">口コミ本文</span>
                  <textarea
                    className="review-field__input review-field__textarea"
                    value={reviewBody}
                    onChange={(e) => setReviewBody(e.target.value)}
                    placeholder="例: バッグに付けやすかった、財布に収まりやすかった、比較しやすかった など"
                  />
                </label>
                <div className="review-form__actions">
                  <button type="submit" className="buy-link-button">口コミを保存する</button>
                  <button type="button" className="text-link text-link--subtle" onClick={exportPendingReviews}>
                    非公開口コミを書き出す
                  </button>
                  <span className="review-form__subnote">今はこの端末だけの保存です。共有の管理画面や全体公開には外部保存の仕組みが必要です。</span>
                </div>
              </form>
            </section>

            <SectionHeader
              eyebrow="Compare"
              title="似た商品・同じカテゴリの商品"
              body="同じ役割や近いシーンの商品と比べると、自分に合う条件を整理しやすくなります。"
              maxWidth={560}
              style={{ marginBottom: 18 }}
            />
            <div className="catalog-grid catalog-grid--compact" style={{ marginBottom: mobile ? 30 : 38 }}>
              {related.map((item) => (
                <button
                  key={item.id}
                  onClick={() => setPage(`product:${item.id}`)}
                  className="detail-related-card"
                  style={{ textAlign: "left" }}
                >
                  <div className="detail-related-card__eyebrow">{item.cat} / {item.scene.join("・")}</div>
                  <div className="detail-related-card__title">{item.name}</div>
                  <div className="detail-related-card__text">{item.tagline}</div>
                  <div className="detail-related-card__link">商品詳細を見る →</div>
                </button>
              ))}
            </div>
          </div>

          <aside className="detail-content-side">
            <section className="detail-aside-card">
              <div className="detail-section__eyebrow">Specs</div>
              <h2 className="detail-section__title">商品情報</h2>
              <div className="data-table">
                {specRows.map(([label, value]) => (
                  <div key={label} className="data-row">
                    <div className="data-row__label">{label}</div>
                    <div className="data-row__value">{value}</div>
                  </div>
                ))}
              </div>
            </section>

            <section className="detail-aside-card detail-aside-card--accent">
              <div className="detail-section__eyebrow">Caution</div>
              <h2 className="detail-section__title">法律・注意点</h2>
              {product.legalPoints && product.legalPoints.length > 0 && (
                <div className="detail-legal-note">
                  <div className="detail-legal-note__title">法律面の確認</div>
                  <TextList items={product.legalPoints} />
                </div>
              )}
              <TextList items={product.cautions || []} />
            </section>

            <section className="detail-aside-card">
              <div className="detail-section__eyebrow">Before You Buy</div>
              <h2 className="detail-section__title">購入前にもう一度確認</h2>
              <p style={{ fontSize: 13, fontFamily: NS, color: C.muted, lineHeight: 1.8, marginBottom: 16 }}>
                価格、在庫、仕様、使用条件は外部サイトの商品ページで確認してください。
              </p>
              {renderPurchaseCta()}
            </section>
          </aside>
        </div>
      </Wrap>
      </div>
    );
  };
})();
