/**
 * Four-question micro-action / suggestion feedback (chip UI).
 * Submits via MicroActionFormLogic → POST /api/micro-action/feedback.
 */
(function () {
  'use strict';

  const { useState, useEffect, useMemo } = React;

  const EMPTY_FEEDBACK = {
    reason: null,
    reason_text: null,
    system: null,
    helpful: null,
    enjoyment: null
  };

  function buildDefaultUiText(lang) {
    const isZh = lang === 'zh-CN';
    return {
      feedbackTitle: isZh ? '帮助我们持续优化' : 'Help us improve!',
      feedbackSubtitle: isZh
        ? '你的反馈是可选的，但能帮助我们提供更好的建议'
        : 'Your feedback is optional but helps us make better suggestions',
      feedbackQ1Title: isZh ? '1. 这个建议吸引你的原因是什么？' : '1. What appealed to you about this suggestion?',
      feedbackQ1Hint: isZh ? '这能帮助我们理解什么样的建议更适合你' : 'This helps us understand what makes suggestions work for you',
      feedbackQ2Title: isZh ? '2. 你对这些建议整体感觉如何？' : '2. How do you feel about these suggestions?',
      feedbackQ2Hint: isZh ? '你的意见能帮助我们改进建议系统' : 'Your opinion helps us improve the suggestion system',
      feedbackQ3Title: isZh ? '3. 这些建议对你有帮助吗？' : '3. Are these suggestions helpful?',
      feedbackQ3Hint: isZh ? '这些建议是否真的帮助你做决定？' : 'Does this actually help you decide?',
      feedbackQ4Title: isZh ? '4. 到目前为止你对 SylvanFlow 的体验如何？' : '4. How are you enjoying SylvanFlow so far?',
      feedbackQ4Hint: isZh ? '你的整体体验对我们非常重要' : 'Your overall experience matters to us',
      submitFeedback: isZh ? '提交反馈' : 'Submit Feedback',
      skipHint: isZh ? '你可以跳过任意问题，我们感谢你的任何反馈！' : 'You can skip any question - we appreciate whatever you share!',
      feedbackThanks: isZh ? '非常感谢！你的反馈正在帮助我们持续改进 SylvanFlow。' : 'Thank you so much! Your feedback helps us make SylvanFlow better.',
      labelPerfectMatch: isZh ? '非常匹配' : 'Perfect Match',
      labelInteresting: isZh ? '很有意思' : 'Interesting',
      labelConvenient: isZh ? '位置方便' : 'Convenient',
      labelGoodTiming: isZh ? '时机合适' : 'Good Timing',
      labelOther: isZh ? '其他' : 'Other',
      placeholderReasonOther: isZh ? '可选：告诉我们这个建议为什么吸引你…' : 'Optional: Tell us what made this suggestion appealing to you...',
      labelExcellent: isZh ? '非常好' : 'Excellent',
      labelGood: isZh ? '不错' : 'Good',
      labelOkay: isZh ? '一般' : 'Okay',
      labelNeedsWork: isZh ? '仍需改进' : 'Needs Work',
      labelVeryHelpful: isZh ? '非常有帮助' : 'Very Helpful',
      labelSomewhatHelpful: isZh ? '有一点帮助' : 'Somewhat',
      labelNotHelpful: isZh ? '帮助不大' : 'Not Really',
      labelLovingIt: isZh ? '很喜欢' : 'Loving It',
      labelEnjoying: isZh ? '还不错' : 'Enjoying',
      labelNeutral: isZh ? '一般' : 'Neutral',
      labelNotEnjoying: isZh ? '不太喜欢' : 'Not Really',
      contextAbout: isZh ? '关于你最近的选择：' : 'About your recent suggestion:',
      needSelection: isZh
        ? '请先打开一条微行动建议并选择一个地点，或从聊天中的建议链接进入后再提交。'
        : 'Open a suggestion from chat and select a place first, or return here right after choosing one.',
      missingLogic: 'Micro-Action form logic not loaded'
    };
  }

  function Chip({ active, onClick, children }) {
    return (
      <button
        type="button"
        onClick={onClick}
        className={`px-3 py-2 rounded-lg text-sm ${
          active ? 'bg-teal-600 text-white' : 'bg-slate-200 text-slate-700 hover:bg-slate-300'
        }`}
      >
        {children}
      </button>
    );
  }

  function MicroActionSuggestionFeedbackForm({ tabParams, onSubmitted }) {
    const [feedbackData, setFeedbackData] = useState(EMPTY_FEEDBACK);
    const [submitted, setSubmitted] = useState(false);
    const [error, setError] = useState(null);
    const [pending, setPending] = useState(() =>
      typeof window !== 'undefined' && window.SylvanFlowMicroActionFeedbackPending
        ? window.SylvanFlowMicroActionFeedbackPending.read()
        : null
    );

    const languageCode =
      tabParams?.languageCode ||
      (typeof window !== 'undefined' && window.SylvanFlowState?.getLanguage?.()) ||
      'en';

    const [uiText, setUiText] = useState(() => buildDefaultUiText(languageCode));

    useEffect(() => {
      setUiText(buildDefaultUiText(languageCode));
    }, [languageCode]);

    useEffect(() => {
      setPending(
        window.SylvanFlowMicroActionFeedbackPending
          ? window.SylvanFlowMicroActionFeedbackPending.read()
          : null
      );
    }, []);

    const ids = useMemo(() => {
      const microActionId = tabParams?.micro_action_id || pending?.micro_action_id || null;
      const optionId = tabParams?.option_id || pending?.option_id || null;
      const poiName = pending?.poi_name || null;
      return { microActionId, optionId, poiName };
    }, [tabParams, pending]);

    const hasAnyAnswer =
      feedbackData.reason || feedbackData.system || feedbackData.helpful || feedbackData.enjoyment;

    const handleChange = (question, value) => {
      setFeedbackData((prev) => ({ ...prev, [question]: value }));
    };

    const handleSubmit = () => {
      if (!ids.microActionId || !ids.optionId) {
        setError(uiText.needSelection);
        return;
      }
      if (!hasAnyAnswer) return;
      if (!window.MicroActionFormLogic) {
        setError(uiText.missingLogic);
        return;
      }
      setError(null);
      window.MicroActionFormLogic.submitFeedback(
        {
          microActionId: ids.microActionId,
          optionId: ids.optionId,
          feedbackData
        },
        () => {
          setSubmitted(true);
          if (window.SylvanFlowMicroActionFeedbackPending) {
            window.SylvanFlowMicroActionFeedbackPending.clear();
          }
          setPending(null);
          if (typeof onSubmitted === 'function') onSubmitted();
        },
        (msg) => setError(typeof msg === 'string' ? msg : msg?.error || 'Failed to submit feedback')
      );
    };

    if (submitted) {
      return (
        <div className="p-5 bg-teal-50 rounded-xl border border-teal-200 text-center">
          <p className="text-teal-800 font-semibold">✅ {uiText.feedbackThanks}</p>
        </div>
      );
    }

    return (
      <div className="feedback-section space-y-6">
        <div className="p-4 bg-gradient-to-r from-teal-50 to-cyan-50 rounded-xl border border-teal-200">
          <p className="text-slate-800 font-bold text-lg mb-1">💬 {uiText.feedbackTitle}</p>
          <p className="text-slate-600 text-sm">{uiText.feedbackSubtitle}</p>
          {ids.poiName ? (
            <p className="text-slate-700 text-sm mt-2 font-medium">
              {uiText.contextAbout} <span className="text-teal-700">{ids.poiName}</span>
            </p>
          ) : null}
        </div>

        {!ids.optionId ? (
          <p className="text-amber-800 text-sm bg-amber-50 border border-amber-200 rounded-lg p-3">{uiText.needSelection}</p>
        ) : null}

        <div>
          <p className="mb-2 text-slate-700 font-medium">{uiText.feedbackQ1Title}</p>
          <p className="mb-3 text-slate-500 text-sm">{uiText.feedbackQ1Hint}</p>
          <div className="flex flex-wrap gap-2 mb-2">
            <Chip active={feedbackData.reason === 'perfect_match'} onClick={() => handleChange('reason', feedbackData.reason === 'perfect_match' ? null : 'perfect_match')}>✨ {uiText.labelPerfectMatch}</Chip>
            <Chip active={feedbackData.reason === 'interesting'} onClick={() => handleChange('reason', feedbackData.reason === 'interesting' ? null : 'interesting')}>🎯 {uiText.labelInteresting}</Chip>
            <Chip active={feedbackData.reason === 'convenient'} onClick={() => handleChange('reason', feedbackData.reason === 'convenient' ? null : 'convenient')}>📍 {uiText.labelConvenient}</Chip>
            <Chip active={feedbackData.reason === 'good_timing'} onClick={() => handleChange('reason', feedbackData.reason === 'good_timing' ? null : 'good_timing')}>⏰ {uiText.labelGoodTiming}</Chip>
            <Chip active={feedbackData.reason === 'other'} onClick={() => handleChange('reason', feedbackData.reason === 'other' ? null : 'other')}>💭 {uiText.labelOther}</Chip>
          </div>
          {feedbackData.reason === 'other' ? (
            <textarea
              value={feedbackData.reason_text || ''}
              onChange={(e) => handleChange('reason_text', e.target.value.trim() || null)}
              placeholder={uiText.placeholderReasonOther}
              className="w-full mt-2 p-3 bg-slate-100 border border-slate-300 rounded-lg text-slate-700 text-sm min-h-[60px] resize-y"
            />
          ) : null}
        </div>

        <div>
          <p className="mb-2 text-slate-700 font-medium">{uiText.feedbackQ2Title}</p>
          <p className="mb-3 text-slate-500 text-sm">{uiText.feedbackQ2Hint}</p>
          <div className="flex flex-wrap gap-2">
            <Chip active={feedbackData.system === 'excellent'} onClick={() => handleChange('system', feedbackData.system === 'excellent' ? null : 'excellent')}>😍 {uiText.labelExcellent}</Chip>
            <Chip active={feedbackData.system === 'good'} onClick={() => handleChange('system', feedbackData.system === 'good' ? null : 'good')}>😊 {uiText.labelGood}</Chip>
            <Chip active={feedbackData.system === 'okay'} onClick={() => handleChange('system', feedbackData.system === 'okay' ? null : 'okay')}>😐 {uiText.labelOkay}</Chip>
            <Chip active={feedbackData.system === 'needs_work'} onClick={() => handleChange('system', feedbackData.system === 'needs_work' ? null : 'needs_work')}>🤔 {uiText.labelNeedsWork}</Chip>
          </div>
        </div>

        <div>
          <p className="mb-2 text-slate-700 font-medium">{uiText.feedbackQ3Title}</p>
          <p className="mb-3 text-slate-500 text-sm">{uiText.feedbackQ3Hint}</p>
          <div className="flex flex-wrap gap-2">
            <Chip active={feedbackData.helpful === 'very_helpful'} onClick={() => handleChange('helpful', feedbackData.helpful === 'very_helpful' ? null : 'very_helpful')}>✅ {uiText.labelVeryHelpful}</Chip>
            <Chip active={feedbackData.helpful === 'somewhat_helpful'} onClick={() => handleChange('helpful', feedbackData.helpful === 'somewhat_helpful' ? null : 'somewhat_helpful')}>👍 {uiText.labelSomewhatHelpful}</Chip>
            <Chip active={feedbackData.helpful === 'not_helpful'} onClick={() => handleChange('helpful', feedbackData.helpful === 'not_helpful' ? null : 'not_helpful')}>👎 {uiText.labelNotHelpful}</Chip>
          </div>
        </div>

        <div>
          <p className="mb-2 text-slate-700 font-medium">{uiText.feedbackQ4Title}</p>
          <p className="mb-3 text-slate-500 text-sm">{uiText.feedbackQ4Hint}</p>
          <div className="flex flex-wrap gap-2">
            <Chip active={feedbackData.enjoyment === 'loving_it'} onClick={() => handleChange('enjoyment', feedbackData.enjoyment === 'loving_it' ? null : 'loving_it')}>❤️ {uiText.labelLovingIt}</Chip>
            <Chip active={feedbackData.enjoyment === 'enjoying'} onClick={() => handleChange('enjoyment', feedbackData.enjoyment === 'enjoying' ? null : 'enjoying')}>😊 {uiText.labelEnjoying}</Chip>
            <Chip active={feedbackData.enjoyment === 'neutral'} onClick={() => handleChange('enjoyment', feedbackData.enjoyment === 'neutral' ? null : 'neutral')}>😐 {uiText.labelNeutral}</Chip>
            <Chip active={feedbackData.enjoyment === 'not_enjoying'} onClick={() => handleChange('enjoyment', feedbackData.enjoyment === 'not_enjoying' ? null : 'not_enjoying')}>😕 {uiText.labelNotEnjoying}</Chip>
          </div>
        </div>

        {error ? (
          <div className="bg-red-50 border border-red-200 rounded-lg p-3">
            <p className="text-red-800 text-sm">{error}</p>
          </div>
        ) : null}

        <div className="pt-4 border-t border-slate-200">
          <button
            type="button"
            onClick={handleSubmit}
            disabled={!hasAnyAnswer || !ids.optionId}
            className={`w-full px-6 py-4 rounded-xl font-bold text-lg shadow-lg transition-all ${
              hasAnyAnswer && ids.optionId
                ? 'bg-gradient-to-r from-teal-600 to-cyan-600 text-white hover:from-teal-700 hover:to-cyan-700'
                : 'bg-slate-300 text-slate-500 cursor-not-allowed opacity-50'
            }`}
          >
            ✨ {uiText.submitFeedback}
          </button>
          <p className="mt-3 text-center text-slate-500 text-sm">{uiText.skipHint}</p>
        </div>
      </div>
    );
  }

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