/* ============================================================
   SVLM — Menu -> Category -> Sub-service browsing layer. Ported from
   public/index-legacy.html's openMenuCategoryGrid()/openSubserviceList()
   (real GET /menu-categories?menu_key=X, GET /menu-categories/:id/services,
   GET /menu-categories/:id/subservices) — this is a SEPARATE layer from
   the flat Services/Products tabs on the bottom nav (those are untouched):
   only Home's 4 category tiles drill into this menu_categories taxonomy,
   same as the old app. Most subservices are still Ops-side placeholders
   ("Coming soon") until a real service gets linked to that category.

   Visually matches the design project's SubHub/SubCat (app/subcats.jsx):
   promo hero (real active promotion, not a fabricated one), monochrome
   SvcTile icons (mapped from menu_categories.icon_emoji — DB stores an
   emoji per category, not one of this app's icon names), and a
   "Recommended" strip of the real services actually linked to this
   group's categories, sorted by rating.
   ============================================================ */
const Pmc = window.PALETTE;

// menu_categories.icon_emoji is a literal emoji (Ops-editable); map the ones actually seeded
// to this app's monochrome icon set. Falls back to 'box' for anything unmapped.
const EMOJI_ICON_MAP = {
  '🧹': 'spray', '🧽': 'roller', '❄️': 'snow', '👕': 'washer', '🛋️': 'sofa', '🛏️': 'bed',
  '👶': 'user', '💉': 'shield', '🚘': 'truck',
  '🔌': 'bolt', '🧱': 'building', '🚪': 'home', '🏠': 'home', '🧺': 'washer', '🏗️': 'wrench',
  '💡': 'flame', '🪑': 'sofa', '🚗': 'truck', '🌳': 'plant', '🚿': 'drop', '🔋': 'bolt', '☀️': 'flame',
};
function iconForCategory(c) { return EMOJI_ICON_MAP[c.icon_emoji] || 'box'; }

const PROMO_BADGE_ICON = { cleaning: 'sparkle', handyman: 'wrench', corporate: 'building', products: 'bolt' };

function MenuCategoryGrid({ app, params }) {
  const { menuKey } = params;
  const [categories, setCategories] = React.useState(null);
  const [recommended, setRecommended] = React.useState(null);

  React.useEffect(() => {
    setCategories(null); setRecommended(null);
    api(`/menu-categories?menu_key=${menuKey}`).then(cats => {
      setCategories(cats);
      // Aggregate the real services linked to every category in this group, for the
      // "Recommended" strip — same real GET /menu-categories/:id/services each subcategory
      // tile itself uses, just merged across all of them.
      Promise.all(cats.map(c => api(`/menu-categories/${c.id}/services`))).then(lists => {
        const merged = lists.flat().map(mapServiceSummary);
        const seen = new Set();
        const unique = merged.filter(s => (seen.has(s.id) ? false : (seen.add(s.id), true)));
        unique.sort((a, b) => Number(b.rating) - Number(a.rating));
        setRecommended(unique.slice(0, 5));
      });
    });
  }, [menuKey]);

  // Real active promotion, shown in the same visual slot the design's fabricated "20% off"
  // hero occupies. Scoped to this category: the banner is headed "<Category> Promotion", so
  // showing the first promo in the list regardless of scope advertised, say, an aircon code on the
  // Move House page — a code the customer would then enter at checkout and watch discount nothing,
  // since computeDiscount only applies it to matching lines. appliesTo holds the service group ids
  // a code is limited to (menu_key and group_id are the same vocabulary), empty meaning everything.
  const promo = app.promotions.find(
    p => !p.appliesTo || p.appliesTo.length === 0 || p.appliesTo.includes(menuKey)
  );

  return (
    <div style={{ paddingBottom: 30 }}>
      <AppHeader onBack={app.back} title={app.t(`cat_${menuKey}`) || menuKey} />

      {promo && (
        <div style={{ padding: '4px 20px 0' }}>
          <div style={{ borderRadius: 18, padding: 18, marginBottom: 20, position: 'relative', overflow: 'hidden',
            background: `linear-gradient(135deg, ${Pmc.navy} 0%, #8a4a10 55%, ${Pmc.primary} 130%)` }}>
            <div style={{ position: 'absolute', right: -26, top: -26, width: 120, height: 120, borderRadius: 99, background: 'rgba(255,255,255,0.06)' }} />
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: 'rgba(255,255,255,0.16)', borderRadius: 99, padding: '5px 11px', fontSize: 11, fontWeight: 700, color: '#fff', marginBottom: 10 }}>
              <Icon name={PROMO_BADGE_ICON[menuKey] || 'sparkle'} size={13} color="#fff" /> {app.t(`cat_${menuKey}`)} {app.lang === 'th' ? 'โปรโมชั่น' : 'Promotion'}
            </div>
            <div style={{ fontSize: 19, fontWeight: 800, color: '#fff', letterSpacing: -0.3, lineHeight: 1.25, maxWidth: 240 }}>
              {promo.kind === 'percent' ? `${promo.value}% off` : `${baht(promo.value)} off`} — {app.pick(promo.en, promo.th)}
            </div>
            <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.8)', margin: '6px 0 12px' }}>
              {app.lang === 'th' ? `ใช้โค้ด ${promo.id} ตอนชำระเงิน` : `Use code ${promo.id} at checkout`}
            </div>
            <Btn size="sm" variant="mint" icon="sparkle" onClick={() => app.go('tab-services')}>{app.t('book_now') || 'Book now'}</Btn>
          </div>
        </div>
      )}

      {/* The tile row is skipped when a menu has only one sub-category, as Move House does. That
          lone tile led to a filtered list identical to the Recommended strip directly beneath it —
          a tap that changed nothing, and a screen the customer had to get past to reach the
          services they came for. Menus with a real choice of sub-categories keep the grid. */}
      <div style={{ padding: '4px 20px' }}>
        <div style={{ display: categories && categories.length > 1 ? 'grid' : 'none', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
          {categories === null ? null : categories.map(c => (
            <button key={c.id} onClick={() => app.go('subservice-list', { categoryId: c.id, categoryName: app.pick(c.name_en, c.name_th) })}
              style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit' }}>
              <SvcTile name={iconForCategory(c)} size={58} on />
              <span style={{ fontSize: 12, fontWeight: 700, color: Pmc.ink, textAlign: 'center', lineHeight: 1.25 }}>{app.pick(c.name_en, c.name_th)}</span>
            </button>
          ))}
        </div>
        {categories !== null && categories.length === 0 && (
          <div style={{ textAlign: 'center', padding: '50px 0', color: Pmc.faint }}>
            <Icon name="grid" size={42} color={Pmc.line} />
            <div style={{ marginTop: 12, fontSize: 14, fontWeight: 600 }}>{app.lang === 'th' ? 'ยังไม่มีหมวดหมู่ในส่วนนี้' : 'No categories here yet'}</div>
          </div>
        )}
      </div>

      {recommended && recommended.length > 0 && (
        <div style={{ padding: '22px 20px 0' }}>
          <SectionHead title={app.lang === 'th' ? 'บริการแนะนำ' : 'Recommended services'} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {recommended.map(s => (
              <Card key={s.id} pad={14} onClick={() => app.go('detail', { id: s.id })} style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
                <SvcTile name={s.icon} size={48} on />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <span style={{ fontWeight: 700, fontSize: 14.5, color: Pmc.ink, lineHeight: 1.3 }}>{app.pick(s.en, s.th)}</span>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 11.5, color: Pmc.star, fontWeight: 700 }}><Icon name="star" size={12} color={Pmc.star} fill={Pmc.star} sw={0} />{s.rating}</span>
                  </div>
                  <div style={{ fontSize: 12, color: Pmc.faint, margin: '2px 0 4px', lineHeight: 1.3 }}>{app.pick(s.tagEn, s.tagTh)}</div>
                  <div style={{ fontSize: 12.5, color: Pmc.muted }}><ServicePrice app={app} s={s} /></div>
                </div>
                <div style={{ width: 30, height: 30, borderRadius: 9, background: Pmc.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="chevR" size={17} color={Pmc.primary} sw={2.2} /></div>
              </Card>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function SubserviceList({ app, params }) {
  const { categoryId, categoryName } = params;
  const [state, setState] = React.useState(null); // { kind: 'services'|'subservices', items }
  const [comingSoon, setComingSoon] = React.useState(null);

  React.useEffect(() => {
    api(`/menu-categories/${categoryId}/services`).then(realServices => {
      if (realServices.length > 0) {
        setState({ kind: 'services', items: realServices.map(mapServiceSummary) });
      } else {
        api(`/menu-categories/${categoryId}/subservices`).then(subservices => setState({ kind: 'subservices', items: subservices }));
      }
    });
  }, [categoryId]);

  return (
    <div>
      <AppHeader onBack={app.back} title={categoryName} />
      <div style={{ padding: '0 20px 30px' }}>
        {state === null ? null : state.kind === 'services' ? (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {state.items.map(s => <ServiceCard key={s.id} app={app} s={s} />)}
          </div>
        ) : (
          <Card pad={0}>
            {state.items.map((s, i) => (
              <div key={s.id} onClick={() => setComingSoon(app.pick(s.name_en, s.name_th))}
                style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px', borderBottom: i < state.items.length - 1 ? `1px solid ${Pmc.lineSoft}` : 'none', cursor: 'pointer' }}>
                <span style={{ fontSize: 14, fontWeight: 600, color: Pmc.ink }}>{app.pick(s.name_en, s.name_th)}</span>
                <Icon name="chevR" size={16} color={Pmc.faint} />
              </div>
            ))}
          </Card>
        )}
      </div>
      {comingSoon && (
        <div onClick={() => setComingSoon(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100, padding: 24 }}>
          <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 20, padding: 22, maxWidth: 320, width: '100%', textAlign: 'center' }}>
            <div style={{ fontWeight: 800, fontSize: 16, color: Pmc.ink, marginBottom: 8 }}>{comingSoon}</div>
            <p style={{ fontSize: 13, color: Pmc.muted, margin: '0 0 18px' }}>{t('customer', 'subservice_coming_soon') || 'This service is coming soon — check back later.'}</p>
            <Btn size="sm" onClick={() => setComingSoon(null)}>OK</Btn>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { MenuCategoryGrid, SubserviceList });
