// 反馈窗口（11E）：文字 + 图片（粘贴 / 拖拽 / 选择，≤3 张 ≤5MB）+ 诊断信息开关。
// 规格见 doc/frontend-design.html 第八章；提交走 multipart POST /v1/feedback。
import { useEffect, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';
import '@dudu/design/styles.css';
import { Button } from '@dudu/design/components/core/Button';
import { Icon } from '@dudu/design/components/core/Icon';
import { Switch } from '@dudu/design/components/forms/Switch';
import { SettingRow } from '@dudu/design/components/forms/SettingRow';
import { invoke } from '../shared/tauri';
import { setThemePref } from '../shared/theme';

const MAX_IMAGES = 3;
const MAX_BYTES = 5 * 1024 * 1024;
const MAX_LEN = 1000;
const OK_TYPES = ['image/jpeg', 'image/png', 'image/webp'];

const ERR_TEXT = {
  NOT_LOGGED_IN: '先登录再反馈',
  FEEDBACK_RATE_LIMITED: '今天反馈次数已达上限',
};

// File → { name, dataUrl, base64 }
function readImage(file) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = () => {
      const dataUrl = reader.result;
      resolve({ name: file.name || 'screenshot.png', dataUrl, base64: dataUrl.split(',')[1] });
    };
    reader.onerror = () => resolve(null);
    reader.readAsDataURL(file);
  });
}

function Thumb({ img, onRemove }) {
  return (
    <div style={{ position: 'relative', width: 64, height: 64, flex: 'none' }}>
      <img src={img.dataUrl} alt={img.name} style={{
        width: 64, height: 64, objectFit: 'cover', borderRadius: 6,
        border: '1px solid var(--border-1)', display: 'block',
      }} />
      <button type="button" onClick={onRemove} aria-label="删除图片" style={{
        position: 'absolute', top: -7, right: -7, width: 20, height: 20,
        borderRadius: '50%', border: 'none', cursor: 'pointer',
        background: 'var(--text-1)', color: 'var(--bg-app)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0,
      }}>
        <Icon name="x" size={10} sw={3} />
      </button>
    </div>
  );
}

function AddBox({ onClick, dragging }) {
  const [hover, setHover] = useState(false);
  const on = hover || dragging;
  return (
    <button type="button" onClick={onClick}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        width: 64, height: 64, flex: 'none', borderRadius: 6, cursor: 'pointer',
        border: `2px dashed ${on ? 'var(--accent)' : 'var(--border-2)'}`,
        background: on ? 'var(--accent-soft)' : 'transparent',
        color: on ? 'var(--accent-text)' : 'var(--text-3)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        transition: 'border-color var(--dur-fast) var(--ease-out)',
      }}>
      <Icon name="imagePlus" size={20} />
    </button>
  );
}

function SuccessView({ onAgain }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, paddingTop: 110 }}>
      <span style={{
        width: 56, height: 56, borderRadius: '50%', background: 'var(--positive-soft)', color: 'var(--positive)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name="check" size={28} sw={2.5} />
      </span>
      <div style={{ fontSize: 17, fontWeight: 'var(--weight-semibold)', color: 'var(--text-1)' }}>已收到 · 谢谢你</div>
      <Button variant="ghost" size="sm" onClick={onAgain}>继续反馈</Button>
    </div>
  );
}

function FeedbackApp() {
  const [content, setContent] = useState('');
  const [images, setImages] = useState([]);
  const [diag, setDiag] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [done, setDone] = useState(false);
  const [err, setErr] = useState('');
  const [dragging, setDragging] = useState(false);
  const [loggedIn, setLoggedIn] = useState(true);
  const fileRef = useRef(null);
  const closeTimer = useRef(null);

  const refreshLogin = () => {
    invoke('get_settings').then((s) => {
      if (s) { setThemePref(s.theme); setLoggedIn(!!s.token); }
    });
  };
  useEffect(() => {
    refreshLogin();
    window.addEventListener('focus', refreshLogin);
    return () => window.removeEventListener('focus', refreshLogin);
  }, []);

  const addFiles = async (files) => {
    setErr('');
    const list = Array.from(files).filter((f) => OK_TYPES.includes(f.type));
    if (!list.length) return;
    const room = MAX_IMAGES - images.length;
    if (room <= 0) { setErr(`最多 ${MAX_IMAGES} 张图片`); return; }
    const next = [];
    for (const f of list.slice(0, room)) {
      if (f.size > MAX_BYTES) { setErr('单张图片不超过 5MB'); continue; }
      const img = await readImage(f);
      if (img) next.push(img);
    }
    if (next.length) setImages((cur) => [...cur, ...next].slice(0, MAX_IMAGES));
  };

  // 粘贴截图（Cmd+V）
  useEffect(() => {
    const onPaste = (e) => {
      const files = Array.from(e.clipboardData?.items || [])
        .filter((it) => it.kind === 'file').map((it) => it.getAsFile()).filter(Boolean);
      if (files.length) addFiles(files);
    };
    document.addEventListener('paste', onPaste);
    return () => document.removeEventListener('paste', onPaste);
  });

  const submit = async () => {
    setSubmitting(true);
    setErr('');
    try {
      const r = await invoke('submit_feedback', {
        content: content.trim(),
        images: images.map((i) => ({ name: i.name, data: i.base64 })),
        includeDiagnostics: diag,
      });
      if (r && r.feedback_id) {
        setDone(true);
        setContent(''); setImages([]);
        closeTimer.current = setTimeout(() => invoke('close_feedback'), 1800);
      } else {
        setErr('提交失败，请稍后再试');
      }
    } catch (e) {
      setErr(ERR_TEXT[String(e)] || '提交失败，请稍后再试');
    } finally {
      setSubmitting(false);
    }
  };

  const frame = (children) => (
    <div
      onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
      onDragLeave={() => setDragging(false)}
      onDrop={(e) => { e.preventDefault(); setDragging(false); addFiles(e.dataTransfer.files); }}
      style={{
        fontFamily: 'var(--font-sans)', background: 'var(--bg-app)', minHeight: '100vh',
        boxSizing: 'border-box', padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 12,
      }}>
      {children}
    </div>
  );

  if (done) {
    return frame(<SuccessView onAgain={() => { clearTimeout(closeTimer.current); setDone(false); }} />);
  }

  if (!loggedIn) {
    return frame(
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, paddingTop: 130 }}>
        <div style={{ fontSize: 17, fontWeight: 'var(--weight-semibold)', color: 'var(--text-1)' }}>先登录再反馈</div>
        <div style={{ fontSize: 'var(--text-sm)', color: 'var(--text-2)' }}>登录后我们才能跟进你的问题</div>
        <Button variant="primary" onClick={() => invoke('open_login')}>微信登录</Button>
      </div>,
    );
  }

  const count = [...content].length;
  return frame(
    <>
      <div style={{ fontSize: 17, fontWeight: 'var(--weight-semibold)', color: 'var(--text-1)' }}>告诉我们哪里不对</div>
      <div style={{ position: 'relative' }}>
        <textarea
          value={content}
          maxLength={MAX_LEN}
          onChange={(e) => setContent(e.target.value)}
          placeholder="说说遇到的问题或建议"
          style={{
            width: '100%', height: 170, resize: 'none', boxSizing: 'border-box',
            padding: '10px 12px 26px', borderRadius: 'var(--radius-md)',
            border: '1px solid var(--border-1)', background: 'var(--surface-card)',
            color: 'var(--text-1)', fontSize: 'var(--text-base)', fontFamily: 'var(--font-sans)',
            lineHeight: 1.6, outline: 'none',
          }} />
        <span style={{ position: 'absolute', right: 12, bottom: 10, fontSize: 12, color: 'var(--text-3)' }}>
          {count} / {MAX_LEN}
        </span>
      </div>
      <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
        {images.map((img, i) => (
          <Thumb key={`${img.name}-${i}`} img={img} onRemove={() => setImages(images.filter((_, j) => j !== i))} />
        ))}
        {images.length < MAX_IMAGES && <AddBox dragging={dragging} onClick={() => fileRef.current?.click()} />}
        <input ref={fileRef} type="file" accept="image/jpeg,image/png,image/webp" multiple
          style={{ display: 'none' }}
          onChange={(e) => { addFiles(e.target.files); e.target.value = ''; }} />
      </div>
      <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-3)' }}>
        粘贴截图、拖进来或点击添加 · 最多 3 张 · 单张不超过 5MB
      </div>
      <SettingRow label="附带诊断信息" description="版本、系统、设备标识">
        <Switch checked={diag} onChange={setDiag} />
      </SettingRow>
      {err && <div style={{ fontSize: 'var(--text-sm)', color: 'var(--danger)' }}>{err}</div>}
      <div style={{ marginTop: 'auto' }}>
        <Button variant="primary" block disabled={!content.trim() || submitting} onClick={submit}>
          {submitting ? '提交中' : '提交'}
        </Button>
      </div>
    </>,
  );
}

createRoot(document.getElementById('root')).render(<FeedbackApp />);
