// AiTextInput.jsx — wrap a plain-text <input> with one (or two) AI
// helper chips. Used on the Training item form for Title and Summary.
//
// Modes:
//   "polish" (default) — fix grammar / phrasing of the current value.
//                        Disabled when the value is empty.
//   "summarize-from"   — given a separate source (e.g. the body HTML),
//                        ask the model to write a one-line summary.
//                        Only the Summary field uses this.
//
// Both modes route through the same `rewrite-text` Edge Function that
// powers the QuillEditor body-rewrite. Both show the same Original /
// Suggested preview modal so the admin reviews before replacing.

const AiTextField = ({
  value,
  onChange,
  placeholder,
  multiline,
  rows,
  contextLabel,           // label passed to the model as additional context
  summarizeFrom,          // when set, also renders a "Summarize" chip
  summarizeFromFormat = 'html',
  summarizeAs = 'summary', // 'summary' (default, ~16 words) or 'title' (2–6 words)
  style,
  inputProps,
}) => {
  const [busy, setBusy] = useState(null); // 'polish' | 'summarize' | null
  // { kind, original, suggested, applyTo: 'value' }
  const [preview, setPreview] = useState(null);

  const runPolish = async () => {
    const text = (value || '').trim();
    if (!text) { alert('Type something first, then I can polish it.'); return; }
    setBusy('polish');
    try {
      const { data, error } = await window.supa.functions.invoke('rewrite-text', {
        body: {
          text,
          format: 'plain',
          mode: 'polish',
          context: contextLabel || '',
        },
      });
      if (error) throw error;
      const suggested = (data?.rewritten || '').trim();
      if (!suggested) throw new Error('Empty response');
      setPreview({ kind: 'polish', original: text, suggested });
    } catch (e) {
      console.error('AI polish failed', e);
      alert('AI polish failed — ' + (e?.message || 'unknown error'));
    } finally {
      setBusy(null);
    }
  };

  const runSummarize = async () => {
    const source = (summarizeFrom || '').trim();
    if (!source) { alert('Write the body first; I\'ll summarize from there.'); return; }
    setBusy('summarize');
    try {
      const { data, error } = await window.supa.functions.invoke('rewrite-text', {
        body: {
          text: source,
          format: summarizeFromFormat,
          mode: 'summarize',
          summarizeTarget: summarizeAs,
          context: contextLabel || '',
        },
      });
      if (error) throw error;
      const suggested = (data?.rewritten || '').trim();
      if (!suggested) throw new Error('Empty response');
      setPreview({ kind: 'summarize', original: value || '', suggested });
    } catch (e) {
      console.error('AI summarize failed', e);
      alert('AI summarize failed — ' + (e?.message || 'unknown error'));
    } finally {
      setBusy(null);
    }
  };

  const apply = () => {
    if (!preview) return;
    onChange(preview.suggested);
    setPreview(null);
  };

  const baseChipStyle = (kind) => ({
    display: 'inline-flex', alignItems: 'center', gap: 5,
    padding: '4px 9px', borderRadius: 999,
    background: '#FFFFFF',
    border: '1px solid var(--border-1)',
    color: '#7C3AED',
    fontSize: 11, fontWeight: 600,
    cursor: busy ? 'wait' : 'pointer',
    opacity: busy && busy !== kind ? 0.4 : (busy === kind ? 0.65 : 1),
    boxShadow: '0 1px 2px rgba(0,0,0,0.04)',
  });

  // Padding budget for the two chips at the right edge of the input.
  // Both chips fit in ~85px each thanks to the shorter labels; bump the
  // total to 200px when both are present.
  const chipRoom = summarizeFrom !== undefined ? 200 : 100;

  return (
    <div style={{ position: 'relative', ...style }}>
      {multiline ? (
        <textarea
          value={value || ''}
          onChange={e => onChange(e.target.value)}
          placeholder={placeholder}
          rows={rows || 2}
          className="portal-input"
          style={{ paddingRight: chipRoom }}
          {...(inputProps || {})}
        />
      ) : (
        <input
          value={value || ''}
          onChange={e => onChange(e.target.value)}
          placeholder={placeholder}
          className="portal-input"
          style={{ paddingRight: chipRoom }}
          {...(inputProps || {})}
        />
      )}

      <div style={{
        position: 'absolute',
        top: multiline ? 6 : '50%',
        transform: multiline ? 'none' : 'translateY(-50%)',
        right: 6,
        display: 'inline-flex', gap: 6,
      }}>
        {summarizeFrom !== undefined && (
          <button
            type="button"
            onClick={runSummarize}
            disabled={!!busy}
            title={summarizeAs === 'title'
              ? 'Generate a short title from the body'
              : 'Generate a one-line summary from the body'}
            style={baseChipStyle('summarize')}
          >
            <PIcon name="sparkle" size={11} color="#7C3AED" />
            {busy === 'summarize' ? '…' : 'Summarize'}
          </button>
        )}
        <button
          type="button"
          onClick={runPolish}
          disabled={!!busy}
          title="Polish grammar and clarity"
          style={baseChipStyle('polish')}
        >
          <PIcon name="sparkle" size={11} color="#7C3AED" />
          {busy === 'polish' ? '…' : 'Rewrite'}
        </button>
      </div>

      {preview && (
        <PModal
          open
          onClose={() => setPreview(null)}
          title={preview.kind === 'summarize' ? 'AI summary preview' : 'AI rewrite preview'}
          width={680}
          footer={
            <>
              <PBtn variant="secondary" onClick={() => setPreview(null)}>Cancel</PBtn>
              <PBtn variant="primary" onClick={apply}>Replace with suggestion</PBtn>
            </>
          }
        >
          <div style={{ padding: 16 }}>
            <div style={{ fontSize: 12, color: 'var(--fg-3)', marginBottom: 10 }}>
              {preview.kind === 'summarize'
                ? 'One-line summary generated from the body. Review and replace, or cancel.'
                : 'Same meaning, polished English. Review and replace, or cancel.'}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <PreviewBox label="Current" tone="muted" content={preview.original || '(empty)'} />
              <PreviewBox label="Suggested" tone="accent" content={preview.suggested} />
            </div>
          </div>
        </PModal>
      )}
    </div>
  );
};

const PreviewBox = ({ label, tone, content }) => {
  const accent = tone === 'accent';
  return (
    <div style={{
      border: '1px solid ' + (accent ? '#C7B8F0' : 'var(--border-2)'),
      borderRadius: 10, overflow: 'hidden',
      background: accent ? '#FAF5FF' : '#FBFAF8',
    }}>
      <div style={{
        padding: '6px 12px',
        background: accent ? '#EDE9FE' : 'var(--bg-sunken)',
        fontSize: 10.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase',
        color: accent ? '#5B21B6' : 'var(--fg-3)',
        borderBottom: '1px solid ' + (accent ? '#DDD1F5' : 'var(--border-2)'),
      }}>{label}</div>
      <div style={{
        padding: 12, maxHeight: 280, overflow: 'auto',
        fontSize: 13, lineHeight: 1.55, color: 'var(--fg-1)',
        whiteSpace: 'pre-wrap', wordBreak: 'break-word',
      }}>{content}</div>
    </div>
  );
};

window.AiTextField = AiTextField;
