// Feedback layer for the AEI Explorer.
// Gated behind the "feedback" tweak. Three affordances, all opening one modal:
//   • a per-tab pill (general feedback on the current view)
//   • a per-pillar button inside the pillar info panel
//   • a per-indicator dot inside the methodology weights table
// Submitting POSTs to the public endpoint /api/public/aei/feedback (same origin
// as this static drop) and then shows the confirmation. See aei_drop/DROP.md.

const { useState: useStateFb } = React;

const FB = {
  accent: PALETTE.darkMoss,   // #327067
  light: PALETTE.lightMoss,   // #74B2A7
  bg: '#F1F8F6',
  bgHover: '#E6F2EF',
  border: '#CBE3DE',
};

// `value` is the enum submitted to the backend (kept English); `key` is the
// i18n key for the visible label, resolved via tr() at render.
const FB_CATEGORIES = [
  { value: 'Pillars & framework', key: 'feedback.category.pillars' },
  { value: 'Indicators & data sources', key: 'feedback.category.indicators' },
  { value: 'Calculation method', key: 'feedback.category.calculation' },
  { value: 'Country scores & rankings', key: 'feedback.category.scores' },
  { value: 'Other', key: 'feedback.category.other' },
];

// Small chat-bubble glyph.
function SpeechIcon({ size = 14, color = FB.accent, strokeWidth = 2 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color}
      strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
      <path d="M21 11.5a8.5 8.5 0 0 1-12.3 7.6L3 21l1.9-5.7A8.5 8.5 0 1 1 21 11.5z" />
    </svg>
  );
}

// Pill (nav) + block (pillar panel) feedback buttons share this base.
function FeedbackButton({ label, variant = 'pill', onClick }) {
  const [hov, setHov] = useStateFb(false);
  const morpho = useSkin() === 'morphosis';
  const base = {
    fontFamily: 'inherit', cursor: 'pointer', display: 'inline-flex', alignItems: 'center',
    gap: 8, color: FB.accent, fontWeight: 600,
    background: hov ? FB.bgHover : FB.bg,
    border: '1px solid ' + (hov ? FB.light : FB.border),
    transition: 'background .15s, border-color .15s',
  };
  const variants = {
    pill: { ...base, alignSelf: 'center', flexShrink: 0, padding: '7px 14px', borderRadius: morpho ? 6 : 20, fontSize: 13, whiteSpace: 'nowrap' },
    block: { ...base, justifyContent: 'center', width: '100%', padding: '12px 14px', borderRadius: morpho ? 6 : 9, fontSize: 14 },
    row: { ...base, padding: '5px 12px', borderRadius: morpho ? 6 : 20, fontSize: 13, whiteSpace: 'nowrap' },
  };
  return (
    <button onClick={onClick} onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)} style={variants[variant]}>
      <SpeechIcon size={variant === 'block' ? 15 : 14} />
      {label}
    </button>
  );
}

// Tiny icon-only affordance for dense rows (methodology indicators).
function FeedbackDot({ onClick, title }) {
  const [hov, setHov] = useStateFb(false);
  return (
    <button onClick={(e) => { e.stopPropagation(); onClick(e); }} title={title}
      onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      style={{
        flexShrink: 0, width: 22, height: 22, borderRadius: '50%', cursor: 'pointer', padding: 0,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        border: '1px solid ' + (hov ? FB.light : FB.border),
        background: hov ? FB.bgHover : FB.bg, transition: 'background .15s, border-color .15s',
      }}>
      <SpeechIcon size={12} />
    </button>
  );
}

// Feedback panel — content for the shared AnchoredModal (positioned beside the
// control that opened it; no dim backdrop). `target` = { scope, label, sub, category }.
function FeedbackPanel({ target, onClose }) {
  const [cat, setCat] = useStateFb(target ? (target.category || FB_CATEGORIES[0].value) : FB_CATEGORIES[0].value);
  const [text, setText] = useStateFb('');
  const [name, setName] = useStateFb('');
  const [sent, setSent] = useStateFb(false);
  const [sending, setSending] = useStateFb(false);
  const [err, setErr] = useStateFb('');

  React.useEffect(() => {
    if (target) {
      // Default the category to the trigger only for a FRESH draft. An
      // in-progress draft (text/name) is PRESERVED so an accidental click-away
      // (or ×/Esc) doesn't lose it — it's purged only on Cancel or a successful
      // send. (Panel stays mounted, so its state survives close/reopen.)
      if (!text.trim()) setCat(target.category || FB_CATEGORIES[0].value);
      setSent(false); setSending(false); setErr('');
    }
  }, [target]);

  const clearDraft = () => { setText(''); setName(''); setCat(FB_CATEGORIES[0].value); };

  // POST to the public embed endpoint (same origin as this static drop, so no
  // CORS). Only the message is required; name is optional. There is no email
  // field in the form yet (coming in a future drop) — the API accepts an
  // optional `email` and stores null until then. On success we flip to the
  // confirmation view; on failure we keep the form and show an inline error.
  const submit = async () => {
    if (!text.trim() || sending) return;
    setSending(true); setErr('');
    try {
      const res = await fetch('/api/public/aei/feedback', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          version: (typeof window !== 'undefined' && window.AEI_EMBED_VERSION) || '',
          category: cat,
          scope: target.scope || '',
          target_label: target.label || '',
          message: text.trim(),
          name: name.trim(),
        }),
      });
      if (!res.ok) throw new Error('HTTP ' + res.status);
      setSent(true);
      clearDraft();  // submitted → purge the draft (confirmation view shows next)
    } catch (e) {
      setErr(tr('feedback.error.send'));
    } finally {
      setSending(false);
    }
  };

  return (
    <AnchoredModal open={!!target} onClose={onClose}>
        {!sent ? (
          <React.Fragment>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 14 }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, letterSpacing: '0.12em', textTransform: 'uppercase', color: FB.accent, fontWeight: 700, fontSize: 12 }}>
                  <SpeechIcon size={13} /> {tr('feedback.eyebrow')}
                </div>
                <h2 style={{ fontFamily: 'Poppins, sans-serif', fontWeight: 500, fontSize: 24, lineHeight: 1.2, color: PALETTE.darkGrey, margin: '8px 0 0' }}>{tr('feedback.title')}</h2>
              </div>
              <button onClick={onClose} aria-label={tr('common.close')} style={{ border: 'none', background: 'none', fontSize: 26, lineHeight: 1, cursor: 'pointer', color: PALETTE.lightGrey, padding: 0, marginTop: -2 }}>×</button>
            </div>

            <p style={{ fontSize: 14, lineHeight: 1.55, color: PALETTE.midGrey, margin: '14px 0 18px' }}>
              {(() => {
                // The mailto link is spliced back in at the {email} token so
                // translators can position it wherever grammar requires.
                const parts = tr('feedback.intro').split('{email}');
                const link = <a href={`mailto:${INQUIRY_EMAIL}`} style={{ color: PALETTE.midGrey, textDecoration: 'underline' }}>{INQUIRY_EMAIL}</a>;
                return <React.Fragment>{parts[0]}{parts.length > 1 ? link : null}{parts.slice(1).join('')}</React.Fragment>;
              })()}
            </p>

            <div style={{ fontSize: 12, letterSpacing: '0.08em', textTransform: 'uppercase', color: PALETTE.lightGrey, fontWeight: 700, marginBottom: 9 }}>{tr('feedback.about_label')}</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 20 }}>
              {FB_CATEGORIES.map((c) => {
                const on = c.value === cat;
                return (
                  <button key={c.value} onClick={() => setCat(c.value)} style={{
                    fontFamily: 'inherit', fontSize: 13, fontWeight: 500, cursor: 'pointer',
                    padding: '6px 13px', borderRadius: 20,
                    border: '1px solid ' + (on ? FB.accent : '#DADBE1'),
                    background: on ? FB.accent : '#fff', color: on ? '#fff' : PALETTE.midGrey,
                    transition: 'background .12s, border-color .12s',
                  }}>{tr(c.key)}</button>
                );
              })}
            </div>

            <label style={{ display: 'block', fontSize: 12, letterSpacing: '0.08em', textTransform: 'uppercase', color: PALETTE.lightGrey, fontWeight: 700, marginBottom: 9 }}>{tr('feedback.message_label')}</label>
            <textarea value={text} onChange={(e) => setText(e.target.value)} rows={5}
              placeholder={tr('feedback.message_placeholder')}
              style={{
                width: '100%', boxSizing: 'border-box', fontFamily: 'inherit', fontSize: 14, lineHeight: 1.5,
                color: PALETTE.darkGrey, padding: '11px 13px', border: '1px solid #DADBE1', borderRadius: 9,
                outline: 'none', resize: 'vertical', background: '#fff',
              }} />

            <input value={name} onChange={(e) => setName(e.target.value)} placeholder={tr('feedback.name_placeholder')}
              style={{
                width: '100%', boxSizing: 'border-box', fontFamily: 'inherit', fontSize: 14,
                color: PALETTE.darkGrey, padding: '10px 13px', border: '1px solid #DADBE1', borderRadius: 9,
                outline: 'none', background: '#fff', marginTop: 12,
              }} />

            {err ? (
              <p style={{ fontSize: 13, lineHeight: 1.5, color: '#B23A48', margin: '14px 0 0' }}>{err}</p>
            ) : null}

            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 20 }}>
              <button onClick={submit} disabled={!text.trim() || sending} style={{
                fontFamily: 'inherit', fontSize: 14, fontWeight: 600, cursor: (text.trim() && !sending) ? 'pointer' : 'not-allowed',
                padding: '11px 22px', borderRadius: 9, border: 'none',
                background: (text.trim() && !sending) ? FB.accent : '#D3DCD9', color: '#fff', transition: 'background .15s',
              }}>{sending ? tr('feedback.submit_sending') : tr('feedback.submit')}</button>
              <button onClick={() => { clearDraft(); onClose(); }} style={{
                fontFamily: 'inherit', fontSize: 14, fontWeight: 600, cursor: 'pointer',
                padding: '11px 16px', borderRadius: 9, border: 'none', background: 'none', color: PALETTE.lightGrey,
              }}>{tr('common.cancel')}</button>
            </div>
          </React.Fragment>
        ) : (
          <div style={{ textAlign: 'center', padding: '18px 4px 10px' }}>
            <div style={{ width: 52, height: 52, borderRadius: '50%', background: FB.bg, border: '1px solid ' + FB.border, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 }}>
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke={FB.accent} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5" /></svg>
            </div>
            <h2 style={{ fontFamily: 'Poppins, sans-serif', fontWeight: 500, fontSize: 24, color: PALETTE.darkGrey, margin: '0 0 8px' }}>{tr('feedback.success.title')}</h2>
            <p style={{ fontSize: 14, lineHeight: 1.55, color: PALETTE.midGrey, maxWidth: 320, margin: '0 auto 22px' }}>
              {tr('feedback.success.body')}
            </p>
            <button onClick={onClose} style={{
              fontFamily: 'inherit', fontSize: 14, fontWeight: 600, cursor: 'pointer',
              padding: '11px 24px', borderRadius: 9, border: 'none', background: FB.accent, color: '#fff',
            }}>{tr('common.done')}</button>
          </div>
        )}
    </AnchoredModal>
  );
}

Object.assign(window, { FeedbackButton, FeedbackDot, SpeechIcon, FeedbackPanel, FB_CATEGORIES });
