/* global React, window */
// Drums Lab — floating feedback widget.
//
// Mirrors src/features/practice/ui/feedback-widget.jsx but writes to the
// drums_feedback table via window.DrumsLab.db.submitFeedback.

(function () {
  'use strict';
  window.DrumsLab = window.DrumsLab || {};
  window.DrumsLab.ui = window.DrumsLab.ui || {};

  const FeedbackWidget = function (props) {
    const [open, setOpen] = React.useState(false);
    const [rating, setRating] = React.useState(null);
    const [comment, setComment] = React.useState('');
    const [submitting, setSubmitting] = React.useState(false);
    const [submitted, setSubmitted] = React.useState(false);
    const [error, setError] = React.useState(null);

    function reset() {
      setRating(null);
      setComment('');
      setSubmitting(false);
      setSubmitted(false);
      setError(null);
    }

    function handleOpen() { reset(); setOpen(true); }
    function handleClose() {
      setOpen(false);
      setTimeout(reset, 200);
    }

    async function handleSubmit() {
      if (!rating) { setError('Pick thumbs up or down first.'); return; }
      setError(null);
      setSubmitting(true);
      const exerciseContext = (typeof props.getContext === 'function') ? props.getContext() : null;
      const res = await window.DrumsLab.db.submitFeedback({
        rating: rating,
        comment: comment,
        exerciseType: props.exerciseType || null,
        exerciseContext: exerciseContext,
      });
      setSubmitting(false);
      if (res && res.ok) {
        setSubmitted(true);
        setTimeout(handleClose, 1400);
      } else {
        setError((res && res.error) || 'Failed to submit. Try again.');
      }
    }

    return (
      <>
        <button
          onClick={handleOpen}
          aria-label="Give feedback"
          style={{
            position: 'fixed',
            right: 22,
            bottom: 22,
            zIndex: 50,
            padding: '12px 20px',
            borderRadius: 999,
            border: 'none',
            background: 'oklch(35% 0.16 265)',
            color: '#fff',
            fontSize: 13,
            fontWeight: 700,
            cursor: 'pointer',
            fontFamily: "'Plus Jakarta Sans', sans-serif",
            boxShadow: '0 8px 24px rgba(0,0,0,0.18)',
            display: 'flex',
            alignItems: 'center',
            gap: 8,
          }}
        >
          <svg aria-hidden="true" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
          </svg>
          Give feedback
        </button>

        {open && (
          <div
            onClick={handleClose}
            style={{
              position: 'fixed',
              inset: 0,
              background: 'rgba(15, 18, 30, 0.45)',
              zIndex: 60,
              display: 'flex',
              alignItems: 'flex-end',
              justifyContent: 'flex-end',
              padding: 20,
            }}
          >
            <div
              onClick={function (e) { e.stopPropagation(); }}
              style={{
                width: '100%',
                maxWidth: 380,
                background: '#fff',
                borderRadius: 16,
                padding: 20,
                boxShadow: '0 24px 60px rgba(0,0,0,0.25)',
                fontFamily: "'Plus Jakarta Sans', sans-serif",
              }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
                <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: 'oklch(18% 0.03 265)' }}>How was that?</h3>
                <button
                  onClick={handleClose}
                  aria-label="Close"
                  style={{ background: 'transparent', border: 'none', color: 'oklch(55% 0.04 265)', fontSize: 22, lineHeight: 1, cursor: 'pointer', padding: 0 }}
                >×</button>
              </div>
              <div style={{ fontSize: 12, color: 'oklch(55% 0.04 265)', marginBottom: 14 }}>Quick beta feedback — even a single thumbs up/down helps.</div>

              {submitted ? (
                <div style={{ padding: '14px 0', textAlign: 'center', fontSize: 14, fontWeight: 600, color: 'oklch(35% 0.16 145)' }}>Thanks — got it.</div>
              ) : (
                <>
                  <div style={{ display: 'flex', gap: 10, marginBottom: 12 }}>
                    <button
                      onClick={function () { setRating('thumbs_up'); }}
                      style={{
                        flex: 1,
                        padding: '12px 0',
                        borderRadius: 10,
                        border: '1px solid ' + (rating === 'thumbs_up' ? 'oklch(45% 0.16 145)' : 'oklch(88% 0.02 265)'),
                        background: rating === 'thumbs_up' ? 'oklch(94% 0.07 145)' : '#fff',
                        color: rating === 'thumbs_up' ? 'oklch(28% 0.14 145)' : 'oklch(28% 0.05 265)',
                        fontSize: 13, fontWeight: 700, cursor: 'pointer',
                        fontFamily: "'Plus Jakarta Sans', sans-serif",
                      }}
                    >Thumbs up</button>
                    <button
                      onClick={function () { setRating('thumbs_down'); }}
                      style={{
                        flex: 1,
                        padding: '12px 0',
                        borderRadius: 10,
                        border: '1px solid ' + (rating === 'thumbs_down' ? 'oklch(45% 0.18 25)' : 'oklch(88% 0.02 265)'),
                        background: rating === 'thumbs_down' ? 'oklch(95% 0.07 25)' : '#fff',
                        color: rating === 'thumbs_down' ? 'oklch(32% 0.16 25)' : 'oklch(28% 0.05 265)',
                        fontSize: 13, fontWeight: 700, cursor: 'pointer',
                        fontFamily: "'Plus Jakarta Sans', sans-serif",
                      }}
                    >Thumbs down</button>
                  </div>

                  <textarea
                    placeholder="What worked, what didn’t? (optional)"
                    value={comment}
                    onChange={function (e) { setComment(e.target.value.slice(0, 2000)); }}
                    rows={4}
                    style={{
                      width: '100%',
                      padding: '10px 12px',
                      borderRadius: 10,
                      border: '1px solid oklch(88% 0.02 265)',
                      fontSize: 13,
                      fontFamily: "'Plus Jakarta Sans', sans-serif",
                      resize: 'vertical',
                      boxSizing: 'border-box',
                      marginBottom: 8,
                    }}
                  />

                  {props.exerciseType && (
                    <div style={{ fontSize: 11, color: 'oklch(55% 0.04 265)', marginBottom: 10 }}>
                      Current exercise: <strong style={{ fontWeight: 700 }}>{String(props.exerciseType).replace(/_/g, ' ')}</strong>
                    </div>
                  )}

                  {error && (
                    <div style={{ fontSize: 12, color: 'oklch(38% 0.18 25)', marginBottom: 10 }}>{error}</div>
                  )}

                  <div style={{ display: 'flex', gap: 8 }}>
                    <button
                      onClick={handleClose}
                      style={{
                        flex: 1,
                        padding: '11px 0',
                        borderRadius: 10,
                        border: '1px solid oklch(88% 0.02 265)',
                        background: '#fff',
                        color: 'oklch(40% 0.04 265)',
                        fontSize: 13, fontWeight: 600, cursor: 'pointer',
                        fontFamily: "'Plus Jakarta Sans', sans-serif",
                      }}
                    >Cancel</button>
                    <button
                      onClick={handleSubmit}
                      disabled={submitting || !rating}
                      style={{
                        flex: 1,
                        padding: '11px 0',
                        borderRadius: 10,
                        border: 'none',
                        background: (submitting || !rating) ? 'oklch(75% 0.03 265)' : 'oklch(35% 0.16 265)',
                        color: '#fff',
                        fontSize: 13, fontWeight: 700,
                        cursor: (submitting || !rating) ? 'not-allowed' : 'pointer',
                        fontFamily: "'Plus Jakarta Sans', sans-serif",
                      }}
                    >{submitting ? 'Sending…' : 'Send'}</button>
                  </div>
                </>
              )}
            </div>
          </div>
        )}
      </>
    );
  };

  window.DrumsLab.ui.FeedbackWidget = FeedbackWidget;
})();
