// Home page — composes Hero, LINE 代購, Products, Shipping, Editorial, CTA
const { useState: useStateH, useEffect: useEffectH } = React;

function LineDemoSection({ t, onNav }) {
  const defaultQuery = 'GUNZE T恤專用內搭';
  const [query, setQuery] = useStateH('');
  const [chat, setChat] = useStateH({
    status: 'idle',
    mode: 'keyword',
    query: '',
    quote: null,
    recommendation: null,
    selectedOptions: {},
    error: '',
  });

  const product = chat.quote?.product || null;
  const pricing = chat.quote ? calculateQuotePricing(chat.quote.pricing, 1, chat.selectedOptions, chat.quote.product) : null;
  const candidate = chat.recommendation?.recommendation || chat.recommendation?.candidates?.[0] || null;
  const quoteUrl = product?.sourceUrl || candidate?.url || (isLikelyProductUrl(chat.query) ? chat.query : '');
  const productSummary = product ? (optionSummary(product, chat.selectedOptions) || product.subtitle || product.brand || product.sourceLabel) : '';
  const isLoading = chat.status === 'loading';
  const hasConversation = chat.status !== 'idle';

  const handleSend = async () => {
    const nextQuery = String(query || '').trim() || defaultQuery;
    const mode = isLikelyProductUrl(nextQuery) ? 'url' : 'keyword';
    setQuery('');
    setChat({
      status: 'loading',
      mode,
      query: nextQuery,
      quote: null,
      recommendation: null,
      selectedOptions: {},
      error: '',
    });
    try {
      const result = await window.jafunProductSearch.resolve(nextQuery, {
        preferredMode: mode,
        quantity: 1,
        selections: {},
        urlEntryPoint: 'line_demo_url_search',
        keywordEntryPoint: 'line_demo_keyword_search',
        fallbackEntryPoint: 'line_demo_url_ai_fallback',
        fallbackToRecommend: false,
      });
      const quote = result.quote || null;
      setChat({
        status: 'done',
        mode: result.mode,
        query: nextQuery,
        quote,
        recommendation: result.recommendation || null,
        selectedOptions: quote ? (quote.selectedOptions || defaultSelections(quote.product.options)) : {},
        error: '',
      });
    } catch (error) {
      setChat({
        status: 'error',
        mode,
        query: nextQuery,
        quote: null,
        recommendation: null,
        selectedOptions: {},
        error: error.message || '目前無法完成自動報價，請稍後再試或改用 LINE 人工確認。',
      });
    }
  };

  const reset = () => {
    setQuery('');
    setChat({
      status: 'idle',
      mode: 'keyword',
      query: '',
      quote: null,
      recommendation: null,
      selectedOptions: {},
      error: '',
    });
  };

  const openQuote = () => {
    if (quoteUrl) {
      onNav('line', { url: quoteUrl });
      return;
    }
    onNav('line');
  };

  return (
    <section className="section line-section" data-screen-label="01 Home — LINE 代購">
      <div className="section-narrow">
        <div className="section-head">
          <div className="left">
            <div className="section-eyebrow">{t.line.eyebrow}</div>
            <h2 className="section-title">{t.line.title}</h2>
            <div className="section-jp">{t.line.jp}</div>
          </div>
          <a className="section-link" onClick={() => onNav('line')}>了解更多 <span>→</span></a>
        </div>

        <div className="line-grid">
          <div className="line-demo">
            <div className="line-demo-head">
              <div className="dot">JF</div>
              <div>
                <div className="line-demo-title">JaFun 代購助理</div>
                <div className="line-demo-status">線上 · 平均回覆 2 分鐘</div>
              </div>
            </div>
            <div className="line-demo-body">
              <div className="line-msg bot">您好！把想買的日本商品網址貼給我，也可以直接輸入「想買什麼」。我會幫您搜尋與報價 🇯🇵</div>
              {hasConversation && (
                <div className="line-msg user">{chat.query}</div>
              )}
              {isLoading && (
                <div className="line-msg bot is-typing">{chat.mode === 'url' ? '正在讀取商品頁與價格...' : '正在用 AI 比對日本平台商品...'}</div>
              )}
              {chat.status === 'done' && product && pricing && (
                <>
                  <div className="line-msg bot">已為您解析商品，以下是即時報價：</div>
                  <div className="line-msg product">
                    <div className="pimg"><img src={product.image} alt={product.title} /></div>
                    <div className="pmeta">{product.sourceLabel} · {product.brand || product.source}</div>
                    <div className="pname">{product.title}</div>
                    {productSummary && <div className="psub">{productSummary}</div>}
                    <div className="price-list">
                      <div className="price-row">
                        <span>商品價格</span>
                        <strong>¥{pricing.itemSubtotalJPY.toLocaleString()}</strong>
                      </div>
                      <div className="price-row">
                        <span>國際運費（估）</span>
                        <strong>NT$ {pricing.internationalShippingEstimateTWD.toLocaleString()}</strong>
                      </div>
                      <div className="price-row">
                        <span>代購手續費 {Math.round(pricing.serviceFeeRate * 100)}%</span>
                        <strong>NT$ {pricing.serviceFeeTWD.toLocaleString()}</strong>
                      </div>
                    </div>
                    <div className="price-row total"><span>總計（含稅）</span><span>NT$ {pricing.totalTWD.toLocaleString()}</span></div>
                    <button onClick={openQuote}>確認下單</button>
                  </div>
                </>
              )}
              {chat.status === 'done' && !product && candidate && (
                <>
                  <div className="line-msg bot">我先找到接近的日本商品，您可以開啟確認，或交給 LINE 客服協助報價。</div>
                  <div className="line-msg product candidate">
                    <div className="pmeta">{candidate.sourceLabel || '日本平台'}</div>
                    <div className="pname">{candidate.title || chat.query}</div>
                    <div className="psub">{candidate.reason || chat.recommendation?.intentSummary || '建議先確認商品頁規格與庫存。'}</div>
                    <div className="candidate-actions">
                      {candidate.url && <a href={candidate.url} target="_blank" rel="noreferrer">開啟商品</a>}
                      <button onClick={() => window.openLineOfficial?.()}>傳給 LINE</button>
                    </div>
                  </div>
                </>
              )}
              {chat.status === 'error' && (
                <>
                  <div className="line-msg bot error">{chat.error}</div>
                  <div className="line-demo-fallback">
                    <button onClick={() => window.openLineOfficial?.()}>改用 LINE 人工確認</button>
                    <button onClick={() => onNav('line', isLikelyProductUrl(chat.query) ? { url: chat.query } : {})}>前往報價頁</button>
                  </div>
                </>
              )}
            </div>
            <div className="line-input">
              <input value={query} onChange={e => setQuery(e.target.value)} placeholder="貼商品網址或輸入想買的東西…" onKeyDown={e => e.key === 'Enter' && handleSend()} disabled={isLoading} />
              <button onClick={handleSend} title="送出" disabled={isLoading}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" /></svg>
              </button>
              {chat.status !== 'idle' && <button onClick={reset} title="重置" className="line-reset">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 12a9 9 0 1015 -6.7L21 8M21 3v5h-5" /></svg>
              </button>}
            </div>
          </div>

          <div className="line-copy">
            <h3>{t.line.head}</h3>
            <p>{t.line.sub}</p>
            <div className="line-steps">
              {['step1', 'step2', 'step3'].map((k, i) => (
                <div key={k} className="line-step">
                  <div className="num">0{i + 1}</div>
                  <div>
                    <h4>{t.line[k].t}</h4>
                    <p>{t.line[k].d}</p>
                  </div>
                </div>
              ))}
            </div>
            <button className="btn btn-line" style={{ marginTop: 36 }} onClick={() => window.openLineOfficial?.()}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M19.365 9.863c.349 0 .63.285.63.631 0 .345-.281.63-.63.63H17.61v1.125h1.755c.349 0 .63.283.63.63 0 .344-.281.629-.63.629h-2.386c-.345 0-.627-.285-.627-.629V8.108c0-.345.282-.63.63-.63h2.386c.346 0 .628.285.628.63 0 .349-.281.63-.63.63H17.61v1.125h1.755zm-3.855 3.016c0 .27-.174.51-.432.596-.064.021-.133.031-.199.031-.211 0-.391-.09-.51-.25l-2.443-3.317v2.94c0 .344-.279.629-.631.629-.346 0-.626-.285-.626-.629V8.108c0-.27.173-.51.43-.595.06-.023.135-.033.199-.033.195 0 .375.104.495.254l2.462 3.33V8.108c0-.345.282-.63.63-.63.345 0 .63.285.63.63v4.771zm-5.741 0c0 .344-.282.629-.631.629-.345 0-.627-.285-.627-.629V8.108c0-.345.282-.63.63-.63.346 0 .628.285.628.63v4.771zm-2.466.629H4.917c-.345 0-.63-.285-.63-.629V8.108c0-.345.285-.63.63-.63.348 0 .63.285.63.63v4.141h1.756c.348 0 .629.283.629.63 0 .344-.282.629-.629.629M24 10.314C24 4.943 18.615.572 12 .572S0 4.943 0 10.314c0 4.811 4.27 8.842 10.035 9.608.391.082.923.258 1.058.59.12.301.079.766.038 1.08l-.164 1.02c-.045.301-.24 1.186 1.049.645 1.291-.539 6.916-4.078 9.436-6.975C23.176 14.393 24 12.458 24 10.314" /></svg>
              {t.cta.line}
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

function ProductsSection({ t, onNav }) {
  const [tab, setTab] = useStateH(0);
  const hasTag = (product, pattern) => (product.tags || []).some(tag => pattern.test(tag)) || pattern.test(product.name || '');
  const allProducts = window.PRODUCTS || [];
  const featuredProducts = allProducts.filter(product => product.featured);
  const homepageProducts = (featuredProducts.length ? featuredProducts : allProducts).slice(0, 10);
  // tab 依後台分類（categorySlugs）過濾，無對應分類時用標籤關鍵字補抓
  const byCategory = (slug, pattern) => allProducts.filter(p =>
    (p.categorySlugs || []).includes(slug) || hasTag(p, pattern)).slice(0, 10);
  const productGroups = [
    homepageProducts,
    byCategory('souvenirs', /伴手禮|名物|菓子/),
    byCategory('lifestyle', /生活雜貨|雜貨|日本製/),
    byCategory('toys-models', /玩具|模型|周邊/),
  ];
  // 沒有商品的分類 tab 不顯示
  const visibleTabs = t.shop.tabs
    .map((label, index) => ({ label, index }))
    .filter(({ index }) => productGroups[index]?.length);
  const shownProducts = productGroups[tab]?.length ? productGroups[tab] : homepageProducts;
  return (
    <section className="section products-section" data-screen-label="01 Home — Products">
      <div className="section-narrow">
        <div className="section-head">
          <div className="left">
            <div className="section-eyebrow">{t.shop.eyebrow}</div>
            <h2 className="section-title">{t.shop.title}</h2>
            <div className="section-jp">{t.shop.jp}</div>
            <p className="section-sub" style={{ marginTop: 16 }}>{t.shop.sub}</p>
          </div>
          <a className="section-link" onClick={() => onNav('shop')}>{t.shop.more} <span>→</span></a>
        </div>

        <div className="product-tabs">
          {visibleTabs.map(({ label, index }) => (
            <span key={index} className={tab === index ? 'active' : ''} onClick={() => setTab(index)}>{label}</span>
          ))}
        </div>

        <div className="product-grid">
          {shownProducts.map(p => (
            <ProductCard key={p.id} product={p} onClick={() => onNav('product', { product: p })} />
          ))}
        </div>
      </div>
    </section>
  );
}

function ShipSection({ t, onNav }) {
  const features = ['f1', 'f2', 'f3', 'f4'];
  const icons = [
    <svg key="1" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 7l9-4 9 4v10l-9 4-9-4V7z" /><path d="M3 7l9 4 9-4M12 11v10" /></svg>,
    <svg key="2" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" /></svg>,
    <svg key="3" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 3l8 4v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V7l8-4z" /><path d="M9 12l2 2 4-4" /></svg>,
    <svg key="4" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M21 12c0 4.5-4 8-9 8-1.4 0-2.7-.3-3.9-.8L3 20l1.2-4.2C3.4 14.5 3 13.3 3 12c0-4.5 4-8 9-8s9 3.5 9 8z" /></svg>,
  ];
  return (
    <section className="section ship-section" data-screen-label="01 Home — Shipping">
      <div className="section-narrow">
        <div className="section-head">
          <div className="left">
            <div className="section-eyebrow">{t.ship.eyebrow}</div>
            <h2 className="section-title" style={{ whiteSpace: 'pre-line' }}>{t.ship.title}</h2>
            <div className="section-jp">{t.ship.jp}</div>
            <p className="section-sub" style={{ marginTop: 16 }}>{t.ship.sub}</p>
          </div>
          <a className="section-link" onClick={() => onNav('ship')}>{t.ship.cta} <span>→</span></a>
        </div>
        <div className="ship-grid">
          <div className="ship-image">
            <img src="https://images.unsplash.com/photo-1566576912321-d58ddd7a6088?w=1200&q=80" alt="warehouse" />
          </div>
          <div className="ship-features">
            {features.map((k, i) => (
              <div key={k} className="ship-feat">
                <div className="ico">{icons[i]}</div>
                <div>
                  <h4>{t.ship[k].t}</h4>
                  <p>{t.ship[k].d}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function EditorialSection({ t, onNav }) {
  return (
    <section className="section" style={{ background: 'var(--jf-paper-2)' }} data-screen-label="01 Home — Editorial">
      <div className="section-narrow">
        <div className="section-head">
          <div className="left">
            <div className="section-eyebrow">{t.learn.eyebrow}</div>
            <h2 className="section-title">{t.learn.title}</h2>
            <div className="section-jp">{t.learn.jp}</div>
            <p className="section-sub" style={{ marginTop: 16 }}>{t.learn.sub}</p>
          </div>
          <a className="section-link" onClick={() => onNav('learn')}>所有文章 <span>→</span></a>
        </div>
        <div className="edit-grid">
          {window.EDITORIALS.map((e, i) => (
            <div key={e.id || e.slug || i} className={`edit-card ${e.featured ? 'featured' : ''}`} onClick={() => {
              if (e.content) onNav('article', { article: e });
              else if (e.slug || e.id) onNav('article', { articleSlug: e.slug || e.id });
              else onNav('learn');
            }}>
              <div className="pic">
                <img
                  src={imageVariantUrl(e.imageSizes, 'card', e.img)}
                  srcSet={imageVariantSrcSet(e.imageSizes)}
                  sizes="(max-width: 760px) 100vw, 33vw"
                  alt={e.imageAlt || e.title}
                  loading="lazy"
                  decoding="async"
                />
              </div>
              <div className="meta"><span>{e.tag}</span><span>{e.read}</span></div>
              <h3>{e.title}</h3>
              <p>{e.desc}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function CtaBanner({ t, onNav }) {
  return (
    <section className="cta-banner" data-screen-label="01 Home — CTA">
      <div className="stamp-jp">{t.cta.stamp}</div>
      <h2 style={{ whiteSpace: 'pre-line' }}>{t.cta.title}</h2>
      <p>{t.cta.sub}</p>
      <div className="btns">
        <button className="btn btn-line" onClick={() => window.openLineOfficial?.()}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M24 10.314C24 4.943 18.615.572 12 .572S0 4.943 0 10.314c0 4.811 4.27 8.842 10.035 9.608c1.291-.539 6.916-4.078 9.436-6.975C23.176 14.393 24 12.458 24 10.314" /></svg>
          {t.cta.line}
        </button>
        <button className="btn btn-ghost" onClick={() => onNav('shop')}>{t.cta.shop}</button>
      </div>
    </section>
  );
}

function isLikelyProductUrl(value) {
  return window.jafunProductSearch?.looksLikeProductUrl(value) || false;
}

async function requestKeywordRecommendation(query) {
  return window.jafunProductSearch.recommend(query, { entryPoint: 'home_keyword_search' });
}

function homeQuoteCartItem(quote, pricing, selectedOptions) {
  if (!quote || !pricing) return null;
  const summary = optionSummary(quote.product, selectedOptions);
  return {
    id: quote.product.productId,
    cartId: `home-quote-${quote.product.source}-${quote.product.productId}-${Object.values(selectedOptions || {}).join('-')}`,
    region: `首頁快速報價 · ${quote.product.sourceLabel}`,
    name: quote.product.title,
    jname: quote.product.subtitle,
    price: pricing.totalTWD,
    jpy: pricing.itemSubtotalJPY,
    img: quote.product.image,
    optionSummary: summary,
    sourceLabel: quote.product.sourceLabel,
    sourceUrl: quote.product.sourceUrl,
    sourceType: quote.product.source,
    selectedOptions,
    feeIncluded: true,
    shippingIncluded: true,
    quotePricing: pricing,
  };
}

function homeEstimateNumber(value) {
  const text = String(value || 'JAFUN');
  const seed = Array.from(text).reduce((sum, char) => sum + char.charCodeAt(0), 0);
  return String((seed % 9000) + 1000).padStart(4, '0');
}

function homeEstimateTimestamp() {
  const date = new Date();
  const pad = value => String(value).padStart(2, '0');
  return `${date.getFullYear()}.${pad(date.getMonth() + 1)}.${pad(date.getDate())} ・ ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}

function HomeKeywordEstimate({
  state,
  quote,
  pricing,
  recommendation,
  selectedOptions,
  candidates,
  sourceUrl,
  searchLinks,
  added,
  importRestrictionNotice,
  requiresManualReview,
  onCheckout,
  onAddToCart,
  onNav,
}) {
  const estimateNo = homeEstimateNumber(`${state.query} ${quote?.product?.productId || recommendation?.searchQuery || ''}`);
  const product = quote?.product;
  const canOrder = Boolean(quote && pricing && !requiresManualReview);
  const rows = quote && pricing ? [
    ['商品價格', `¥${pricing.itemSubtotalJPY.toLocaleString()}`, `NT$ ${pricing.itemSubtotalTWD.toLocaleString()}`],
    [`JaFun 服務費 ${Math.round(pricing.serviceFeeRate * 100)}%`, '最低 NT$ 80', `NT$ ${pricing.serviceFeeTWD.toLocaleString()}`],
    ['國際運費預估', quoteShippingDetailLabel(pricing), `NT$ ${pricing.internationalShippingEstimateTWD.toLocaleString()}`],
  ] : [];
  return (
    <div className="home-keyword-estimate">
      <div className="home-keyword-redline">
        <div className="home-keyword-number">
          <span>NO.</span>
          <strong>{estimateNo}</strong>
        </div>
        <div className="home-keyword-title">
          <span>JAFUN AI ・ 商品見積書</span>
          <h2>{quote ? '已為您找到 1 件最佳商品' : `已為您找到 ${Math.max(candidates.length, 1)} 件候選商品`}</h2>
          <time>{homeEstimateTimestamp()}</time>
        </div>
        <div className={`home-keyword-stamp ${canOrder ? '' : 'is-pending'}`}>{canOrder ? '可下單' : '待確認'}</div>
      </div>

      <div className="home-keyword-sheet">
        <section className="home-keyword-section">
          <div className="home-keyword-section-title">
            <span>01</span>
            <strong>搜尋意圖 | SEARCH INTENT</strong>
          </div>
          <div className="home-keyword-intent">
            <strong>「{recommendation?.searchQuery || state.query}」</strong>
            <p>{recommendation?.intentSummary || `尋找「${state.query}」語意接近的日本平台商品。`}</p>
            {recommendation?.recommendedReason && <p>{recommendation.recommendedReason}</p>}
          </div>
        </section>

        {importRestrictionNotice && (
          <div className="import-restriction-alert home-keyword-alert">
            <strong>{importRestrictionNotice.title}</strong>
            <span>{importRestrictionNotice.message}</span>
          </div>
        )}

        <div className="home-keyword-detail-grid">
          <section className="home-keyword-section">
            <div className="home-keyword-section-title">
              <span>02</span>
              <strong>商品明細 | PRODUCT</strong>
            </div>
            {product ? (
              <article className="home-keyword-product">
                <img src={product.image} alt="" />
                <div className="home-keyword-product-copy">
                  <span>{product.sourceLabel} ・ {product.brand}</span>
                  <h3>{product.title}</h3>
                  <p>{optionSummary(product, selectedOptions) || product.subtitle}</p>
                </div>
              </article>
            ) : (
              <div className="home-keyword-candidates">
                {candidates.map(candidate => (
                  <a key={candidate.url} href={candidate.url} target="_blank" rel="noreferrer">
                    <span>{candidate.sourceLabel}</span>
                    <strong>{candidate.title}</strong>
                    <small>{candidate.reason || '日本平台候選商品'}</small>
                  </a>
                ))}
              </div>
            )}
          </section>

          <section className="home-keyword-section">
            <div className="home-keyword-section-title">
              <span>03</span>
              <strong>預估費用 | ESTIMATE</strong>
            </div>
            {quote && pricing ? (
              <div className="home-keyword-estimate-card">
                {rows.map(row => (
                  <div className="home-keyword-price-row" key={row[0]}>
                    <div>
                      <strong>{row[0]}</strong>
                      <span>{row[1]}</span>
                    </div>
                    <em>{row[2]}</em>
                  </div>
                ))}
                <div className="home-keyword-sum-label">合　計</div>
                <div className="home-keyword-total">
                  <span>預估總額</span>
                  <small>含商品 / 服務費 / 國際運費</small>
                  <strong>NT$ {pricing.totalTWD.toLocaleString()}</strong>
                </div>
              </div>
            ) : (
              <div className="home-keyword-estimate-card is-empty">
                <p>目前尚未取得可直接估價的商品，請開啟候選商品或交由 LINE 人工確認。</p>
              </div>
            )}
          </section>
        </div>

        <div className="home-keyword-actions">
          {quote && pricing ? (
            requiresManualReview ? (
              <>
                <button className="btn btn-line" onClick={() => window.openLineOfficial?.()}>改用 LINE 人工確認</button>
                <button className="btn btn-ghost" onClick={() => onNav('ship')}>查看禁運說明</button>
                <button className="btn btn-ghost" onClick={() => onNav('line', { url: quote.product.sourceUrl })}>調整規格</button>
              </>
            ) : (
              <>
                <button className="btn btn-primary" onClick={onCheckout}>用推薦商品下單</button>
                <button className="btn btn-ghost" onClick={onAddToCart}>{added ? '已加入購物車' : '加入購物車'}</button>
                <button className="btn btn-ghost" onClick={() => onNav('line', { url: quote.product.sourceUrl })}>調整規格</button>
              </>
            )
          ) : (
            <>
              {searchLinks.map(link => (
                <a key={link.source} className="btn btn-ghost" href={link.url} target="_blank" rel="noreferrer">開啟 {link.sourceLabel}</a>
              ))}
              <button className="btn btn-line" onClick={() => window.openLineOfficial?.()}>傳給 LINE 估價</button>
            </>
          )}
          {sourceUrl && <a className="home-source-link" href={sourceUrl} target="_blank" rel="noreferrer">查看日本原站</a>}
        </div>
      </div>
    </div>
  );
}

function HomeSearchModal({ state, pricing, selectedOptions, added, onClose, onCheckout, onAddToCart, onNav }) {
  const [shareCopied, setShareCopied] = useStateH(false);
  const [shareMenuOpen, setShareMenuOpen] = useStateH(false);
  if (!state.open) return null;
  const quote = state.quote;
  const recommendation = state.recommendation;
  const isKeyword = state.mode === 'keyword';
  const hasError = !state.loading && Boolean(state.error);
  const sourceUrl = quote?.product?.sourceUrl || recommendation?.recommendation?.url || '';
  const searchLinks = recommendation?.searchLinks || [];
  const candidates = recommendation?.candidates || [];
  const importRestrictionNotice = quote?.importRestrictionNotice || recommendation?.importRestrictionNotice || null;
  const requiresManualReview = importRestrictionNotice?.severity === 'manual_review';
  const errorMessage = readableSearchError(state.error);
  const headingText = hasError
    ? (isKeyword ? 'AI 搜尋需要人工確認' : '商品估價需要人工確認')
    : (isKeyword ? 'AI 已整理日本商品推薦' : '商品總報價已估算完成');
  const badgeText = state.loading ? '處理中' : (hasError ? '需確認' : (quote ? '可下單' : '待確認'));
  const sharePayload = buildHomeSharePayload({ state, quote, pricing, recommendation, sourceUrl });
  const handleShare = async (channel = 'native') => {
    const shared = await shareHomeSearchResult(sharePayload, channel);
    if (shared === 'copied') {
      setShareCopied(true);
      window.setTimeout(() => setShareCopied(false), 1800);
    }
    if (shared !== 'cancelled') setShareMenuOpen(false);
  };

  const shareControls = (
    <div className="home-share-wrap">
      <button className="btn btn-ghost" onClick={() => setShareMenuOpen(current => !current)}>
        {shareCopied ? '已複製分享內容' : '分享商品'}
      </button>
      {shareMenuOpen && (
        <div className="home-share-menu" role="menu" aria-label="選擇分享平台">
          <button type="button" onClick={() => handleShare('line')}>LINE</button>
          <button type="button" onClick={() => handleShare('facebook')}>Facebook</button>
          <button type="button" onClick={() => handleShare('x')}>X</button>
          <button type="button" onClick={() => handleShare('copy')}>複製連結</button>
        </div>
      )}
    </div>
  );

  return (
    <div className="home-search-modal" onClick={onClose}>
      <div className={`home-search-dialog ${hasError ? 'is-error-state' : ''}`} onClick={event => event.stopPropagation()}>
        <button className="home-search-close" onClick={onClose} aria-label="關閉">×</button>
        <div className="home-search-head">
          <div>
            <div className="section-eyebrow">{isKeyword ? 'AI PRODUCT SEARCH' : 'URL QUICK QUOTE'}</div>
            <h2>{headingText}</h2>
          </div>
          <span className={`home-search-badge ${state.loading ? 'loading' : ''} ${hasError ? 'is-error' : ''}`}>{badgeText}</span>
        </div>

        {state.loading && (
          <div className="home-search-loading">
            <div className="home-search-spinner" />
            <div>
              <strong>{isKeyword ? 'AI 正在判斷需求並比對相近商品' : '正在解析商品頁並計算運費與服務費'}</strong>
              <span>這裡會直接帶回商品、運費預估與可結帳入口。</span>
            </div>
          </div>
        )}

        {!state.loading && state.error && (
          <div className="home-search-error">
            <strong>目前無法完成自動評估</strong>
            <span>{errorMessage}</span>
            <div className="home-search-actions">
              <button className="btn btn-line" onClick={() => window.openLineOfficial?.()}>改用 LINE 人工確認</button>
              <button className="btn btn-ghost" onClick={() => onNav('ship')}>查看禁運說明</button>
              <button className="btn btn-ghost" onClick={() => onNav('line', isLikelyProductUrl(state.query) ? { url: state.query } : {})}>前往完整報價頁</button>
            </div>
          </div>
        )}

        {!state.loading && !state.error && isKeyword && recommendation && (
          <div className="home-ai-summary">
            <div>
              <span>AI 搜尋意圖</span>
              <strong>「{recommendation.searchQuery || state.query}」</strong>
            </div>
            <p>{recommendation.intentSummary || `尋找「${state.query}」語意接近的日本平台商品。`}</p>
            {recommendation.recommendedReason && <small>{recommendation.recommendedReason}</small>}
          </div>
        )}

        {!state.loading && !state.error && importRestrictionNotice && (
          <div className="import-restriction-alert">
            <strong>{importRestrictionNotice.title}</strong>
            <span>{importRestrictionNotice.message}</span>
          </div>
        )}

        {!state.loading && !state.error && quote && pricing && (
          <div className="home-quote-grid">
            <div className="home-quote-product">
              <img src={quote.product.image} alt="" />
              <div>
                <div className="home-quote-source">{quote.product.sourceLabel} · {quote.product.brand}</div>
                <h3>{quote.product.title}</h3>
                <p>{optionSummary(quote.product, selectedOptions) || quote.product.subtitle}</p>
              </div>
            </div>
            <div className="home-quote-price">
              {[
                ['商品價格', `¥${pricing.itemSubtotalJPY.toLocaleString()}`, `NT$ ${pricing.itemSubtotalTWD.toLocaleString()}`],
                [`JaFun 服務費 ${Math.round(pricing.serviceFeeRate * 100)}%`, '最低 NT$ 80', `NT$ ${pricing.serviceFeeTWD.toLocaleString()}`],
                ['國際運費預估', quoteShippingDetailLabel(pricing), `NT$ ${pricing.internationalShippingEstimateTWD.toLocaleString()}`],
              ].map(row => (
                <div key={row[0]}>
                  <span>{row[0]}</span>
                  <span>{row[1]}</span>
                  <strong>{row[2]}</strong>
                </div>
              ))}
              <div className="home-quote-total">
                <span>預估總額</span>
                <strong>NT$ {pricing.totalTWD.toLocaleString()}</strong>
              </div>
            </div>
          </div>
        )}

        {!state.loading && !state.error && !quote && candidates.length > 0 && (
          <div className="home-candidate-list">
            {candidates.map(candidate => (
              <a key={candidate.url} href={candidate.url} target="_blank" rel="noreferrer">
                <span>{candidate.sourceLabel}</span>
                <strong>{candidate.title}</strong>
                <small>{candidate.reason || '日本平台候選商品'}</small>
              </a>
            ))}
          </div>
        )}

        {!state.loading && !state.error && (
          <div className="home-search-actions">
            {quote && pricing ? (
              requiresManualReview ? (
                <>
                  {shareControls}
                  <button className="btn btn-line" onClick={() => window.openLineOfficial?.()}>改用 LINE 人工確認</button>
                  <button className="btn btn-ghost" onClick={() => onNav('ship')}>查看禁運說明</button>
                  <button className="btn btn-ghost" onClick={() => onNav('line', { url: quote.product.sourceUrl })}>調整規格</button>
                </>
              ) : (
                <>
                  <button className="btn btn-primary" onClick={onCheckout}>{isKeyword ? '用推薦商品下單' : '確認下單'}</button>
                  <button className="btn btn-ghost" onClick={onAddToCart}>{added ? '已加入購物車' : '加入購物車'}</button>
                  {shareControls}
                  <button className="btn btn-ghost" onClick={() => onNav('line', { url: quote.product.sourceUrl })}>調整規格</button>
                </>
              )
            ) : (
              <>
                {shareControls}
                {searchLinks.map(link => (
                  <a key={link.source} className="btn btn-ghost" href={link.url} target="_blank" rel="noreferrer">開啟 {link.sourceLabel}</a>
                ))}
                <button className="btn btn-line" onClick={() => window.openLineOfficial?.()}>傳給 LINE 估價</button>
              </>
            )}
            {sourceUrl && <a className="home-source-link" href={sourceUrl} target="_blank" rel="noreferrer">查看日本原站</a>}
          </div>
        )}
      </div>
    </div>
  );
}

function buildHomeSharePayload({ state, quote, pricing, recommendation, sourceUrl }) {
  const productTitle = quote?.product?.title || recommendation?.recommendation?.title || state.query || '日本商品';
  const url = sourceUrl || `${window.location.origin}/`;
  const priceLine = pricing ? `預估總額 NT$ ${pricing.totalTWD.toLocaleString()}` : '';
  const queryLine = state.query ? `搜尋：${state.query}` : '';
  const text = [
    `我在 JaFun 找到這個日本商品：${productTitle}`,
    priceLine,
    queryLine,
    '貼上日本商品網址或輸入想買的東西，JaFun 會協助整理報價。',
  ].filter(Boolean).join('\n');
  return {
    title: `JaFun 日本商品推薦｜${productTitle}`,
    text,
    url,
  };
}

async function shareHomeSearchResult(payload, channel = 'native') {
  const shareText = `${payload.text}\n${payload.url}`;
  const encodedUrl = encodeURIComponent(payload.url);
  const encodedText = encodeURIComponent(payload.text);
  try {
    if (channel === 'line') {
      window.open(`https://social-plugins.line.me/lineit/share?url=${encodedUrl}`, '_blank', 'noopener,noreferrer');
      return 'shared';
    }
    if (channel === 'facebook') {
      window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`, '_blank', 'noopener,noreferrer');
      return 'shared';
    }
    if (channel === 'x') {
      window.open(`https://twitter.com/intent/tweet?text=${encodedText}&url=${encodedUrl}`, '_blank', 'noopener,noreferrer');
      return 'shared';
    }
    if (navigator.share && channel === 'native') {
      await navigator.share(payload);
      return 'shared';
    }
    if (navigator.clipboard?.writeText) {
      await navigator.clipboard.writeText(shareText);
      return 'copied';
    }
  } catch (error) {
    if (error?.name === 'AbortError') return 'cancelled';
  }
  window.prompt('複製分享內容', shareText);
  return 'copied';
}

function readableSearchError(message) {
  return window.jafunProductSearch?.readableError(message)
    || '商品資料無法解析，請改用 LINE 人工確認或重新輸入商品需求。';
}

function HomePage({ t, onNav, onAddToCart, authSession }) {
  const [searchState, setSearchState] = useStateH({
    open: false,
    mode: 'url',
    query: '',
    loading: false,
    quote: null,
    recommendation: null,
    error: '',
  });
  const [selectedOptions, setSelectedOptions] = useStateH({});
  const [quoteCheckoutOpen, setQuoteCheckoutOpen] = useStateH(false);
  const [quoteAdded, setQuoteAdded] = useStateH(false);
  const [quoteOrderDone, setQuoteOrderDone] = useStateH(false);
  const pricing = searchState.quote ? calculateQuotePricing(searchState.quote.pricing, 1, selectedOptions, searchState.quote.product) : null;

  const runSearch = async (rawValue, preferredMode = 'url') => {
    const query = String(rawValue || '').trim();
    if (!query) return;
    const mode = isLikelyProductUrl(query) ? 'url' : preferredMode === 'keyword' ? 'keyword' : 'keyword';
    setQuoteAdded(false);
    setQuoteOrderDone(false);
    setSelectedOptions({});
    setSearchState({ open: true, mode, query, loading: true, quote: null, recommendation: null, error: '' });
    try {
      const result = await window.jafunProductSearch.resolve(query, {
        preferredMode: mode,
        quantity: 1,
        selections: {},
        urlEntryPoint: 'home_url_search',
        keywordEntryPoint: 'home_keyword_search',
        fallbackEntryPoint: 'home_url_ai_fallback',
        fallbackToRecommend: false,
      });
      const quote = result.quote || null;
      const recommendation = result.recommendation || null;
      setSelectedOptions(quote ? (quote.selectedOptions || defaultSelections(quote.product.options)) : {});
      setSearchState({
        open: true,
        mode: result.mode || mode,
        sourceMode: result.sourceMode || '',
        query,
        loading: false,
        quote,
        recommendation,
        error: '',
      });
    } catch (error) {
      setSearchState({
        open: true,
        mode,
        query,
        loading: false,
        quote: null,
        recommendation: null,
        error: readableSearchError(error.message || '搜尋失敗，請稍後再試。'),
      });
    }
  };

  const addCurrentQuoteToCart = () => {
    const item = homeQuoteCartItem(searchState.quote, pricing, selectedOptions);
    if (!item) return;
    onAddToCart?.(item, 1);
    setQuoteAdded(true);
  };

  useEffectH(() => {
    const runPendingSearch = (payload) => {
      const query = String(payload?.query || '').trim();
      if (!query) return;
      runSearch(query, payload?.mode || 'keyword');
    };
    try {
      const raw = window.sessionStorage.getItem('jafun-pending-home-search');
      if (raw) {
        window.sessionStorage.removeItem('jafun-pending-home-search');
        runPendingSearch(JSON.parse(raw));
      }
    } catch (error) {}
    const onRequest = (event) => runPendingSearch(event.detail);
    window.addEventListener('jafun:home-search-request', onRequest);
    return () => window.removeEventListener('jafun:home-search-request', onRequest);
  }, []);

  return (
    <div data-screen-label="01 Home">
      <HeroSection t={t} onNav={onNav} onSearchSubmit={runSearch} searchBusy={searchState.loading} />
      <HomeSearchModal
        state={searchState}
        pricing={pricing}
        selectedOptions={selectedOptions}
        added={quoteAdded}
        onClose={() => setSearchState(current => ({ ...current, open: false }))}
        onCheckout={() => {
          setSearchState(current => ({ ...current, open: false }));
          setQuoteCheckoutOpen(true);
        }}
        onAddToCart={addCurrentQuoteToCart}
        onNav={onNav}
      />
      {quoteCheckoutOpen && searchState.quote && pricing && (
        <QuoteOrderModal
          quote={searchState.quote}
          pricing={pricing}
          quantity={1}
          selectedOptions={selectedOptions}
          cartItem={homeQuoteCartItem(searchState.quote, pricing, selectedOptions)}
          authSession={authSession}
          onNav={onNav}
          onClose={() => setQuoteCheckoutOpen(false)}
          onAddToCart={() => { addCurrentQuoteToCart(); setQuoteCheckoutOpen(false); }}
          onDone={() => {
            setQuoteOrderDone(true);
            setQuoteCheckoutOpen(false);
          }}
        />
      )}
      {quoteOrderDone && (
        <div className="home-search-toast">
          代購需求已建立，下單前 JaFun 會重新確認日本官網價格與庫存。
        </div>
      )}
      <LineDemoSection t={t} onNav={onNav} />
      <ProductsSection t={t} onNav={onNav} />
      <ShipSection t={t} onNav={onNav} />
      <EditorialSection t={t} onNav={onNav} />
      <CtaBanner t={t} onNav={onNav} />
    </div>
  );
}

Object.assign(window, { HomePage });
