/**
 * Menu → Feedback (drawer): suggestion feedback (moved from Micro-Action detail).
 * Hosts MicroActionSuggestionFeedbackForm + session pending bridge after POI select.
 *
 * Product law: keep the four-question MicroAction form, fields, chips, copy,
 * and MicroActionFormLogic → POST /api/micro-action/feedback.
 * Do not wire the generic Message/Category surface on this Menu route.
 *
 * UI: current SylvanFlow app chrome via SYLVAN_TECH_THEME (same scroll/title
 * tokens as Power Up / in-app surfaces). Navigation (approved):
 * - chrome header Back in pages/app.js via sf_feedback_return_view
 * - bottom strip: reuse InternalShellTwinNav (explore | powerup | nuask)
 *   matched to sf_feedback_return_view — no legacy 3-tab shell on Feedback
 * - TwinNav captions: same SYS-resolved logic as live Explore / Power Up / NuAsk
 *   via pages/logic/twin-nav-caption-resolve.js (no hardcoded EN product labels)
 */
(function () {
  'use strict';

  const { useRef, useEffect, useMemo, useState } = React;

  /** Map saved origin view → existing TwinNav variant (no new destinations). */
  function twinVariantFromReturnView(saved) {
    const v = String(saved || '').trim();
    if (v === 'power-up') return 'powerup';
    if (v === 'nu-ask-sylvan') return 'nuask';
    // explore / flow-plan / explore-detail / ask-sylvan / default
    return 'explore';
  }

  /** EN defaults match Explore / Power Up / NuAsk until SYS resolve completes. */
  function fallbackTwinLabels(variant) {
    if (typeof window !== 'undefined' && typeof window.buildTwinNavCaptions === 'function') {
      return window.buildTwinNavCaptions({ variant, language: 'en' });
    }
    if (variant === 'powerup') {
      return { leftLabel: 'Explore', rightLabel: 'NOW WHAT', ariaLabel: 'Explore and NOW WHAT' };
    }
    if (variant === 'nuask') {
      return { leftLabel: 'Profile', rightLabel: 'Explore', ariaLabel: 'Profile and Explore' };
    }
    return { leftLabel: 'Profile', rightLabel: 'NOW WHAT', ariaLabel: 'Profile and NOW WHAT' };
  }

  function FeedbackInApp({ tabParams }) {
    const containerRef = useRef(null);
    const theme =
      typeof window !== 'undefined' && window.SYLVAN_TECH_THEME
        ? window.SYLVAN_TECH_THEME
        : null;

    const origin = useMemo(() => {
      let saved = '';
      try {
        saved = sessionStorage.getItem('sf_feedback_return_view') || '';
      } catch (_) {}
      const variant = twinVariantFromReturnView(saved);
      return { variant, originView: saved || null };
    }, []);

    const [labels, setLabels] = useState(() => fallbackTwinLabels(origin.variant));

    useEffect(() => {
      theme?.ensureKeyframes?.();
    }, [theme]);

    useEffect(() => {
      let cancelled = false;
      const language =
        (typeof window !== 'undefined' && window.SylvanFlowState?.getLanguage?.()) || 'en';
      const resolve =
        typeof window !== 'undefined' ? window.resolveTwinNavCaptionsFromSys : null;
      if (typeof resolve !== 'function') return undefined;
      resolve(origin.variant, language).then((next) => {
        if (!cancelled && next) setLabels(next);
      });
      return () => {
        cancelled = true;
      };
    }, [origin.variant]);

    const title =
      typeof window !== 'undefined' && window.SylvanFlowState?.getLanguage?.() === 'zh-CN'
        ? '反馈'
        : 'Feedback';

    const scrollCanvas =
      theme?.classes?.scrollCanvas || 'flex-1 overflow-y-auto bg-black min-h-0';
    const scrollInner =
      theme?.classes?.scrollInner ||
      'mx-auto w-full max-w-[440px] min-h-full pb-6 text-slate-100';
    const headline =
      theme?.classes?.headline ||
      'text-2xl sm:text-3xl font-bold text-white mb-2 tracking-tight';
    const sectionPad = theme?.layout?.sectionPad || 'px-4 pt-3';

    const TwinNav =
      typeof window !== 'undefined' ? window.InternalShellTwinNav : null;

    return (
      <div
        ref={containerRef}
        className="flex h-full w-full flex-col bg-black"
        data-sf-surface="feedback"
        data-sf-feedback-host="micro-action-suggestion"
        data-sf-feedback-twin-variant={origin.variant}
        data-sf-feedback-twin-origin={origin.originView || ''}
        data-sf-feedback-twin-left={labels.leftLabel || ''}
        data-sf-feedback-twin-right={labels.rightLabel || ''}
      >
        <div className={`${scrollCanvas}`}>
          <div className={`${scrollInner} ${sectionPad}`}>
            <h2 className={headline}>{title}</h2>
            {window.MicroActionSuggestionFeedbackForm ? (
              React.createElement(window.MicroActionSuggestionFeedbackForm, { tabParams })
            ) : (
              <p className="text-sm text-slate-400">Loading feedback form…</p>
            )}
          </div>
        </div>
        {TwinNav
          ? React.createElement(TwinNav, {
              variant: origin.variant,
              leftLabel: labels.leftLabel,
              rightLabel: labels.rightLabel,
              ariaLabel: labels.ariaLabel,
              staticTwinEdge: true,
            })
          : null}
      </div>
    );
  }

  if (typeof window !== 'undefined') {
    window.FeedbackInApp = FeedbackInApp;
  }
})();
