// Screens - Home, Detail, Upload, Me

// Category icons
function CategoryIcon({ kind, color }) {
  const common = { stroke: color, strokeWidth: 1.5, fill: 'none', strokeLinecap: 'round', strokeLinejoin: 'round' };
  if (kind === 'portrait') {
    return (
      <svg width="18" height="18" viewBox="0 0 18 18">
        <rect x="2.5" y="2.5" width="13" height="13" rx="2.5" {...common} />
        <circle cx="9" cy="7.3" r="2" {...common} />
        <path d="M4.8 13.5c1-2 2.5-3 4.2-3s3.2 1 4.2 3" {...common} />
      </svg>
    );
  }
  if (kind === 'chat') {
    return (
      <svg width="18" height="18" viewBox="0 0 18 18">
        <path d="M2.5 4.5a1.5 1.5 0 011.5-1.5h6a1.5 1.5 0 011.5 1.5v4A1.5 1.5 0 0110 10H6l-2.5 2V10a1 1 0 01-1-1V4.5z" {...common} />
        <path d="M7.5 12.5v.5a1.5 1.5 0 001.5 1.5h3l2 1.5v-1.5a1 1 0 001-1v-3a1.5 1.5 0 00-1.5-1.5h-1.2" {...common} />
      </svg>
    );
  }
  if (kind === 'story') {
    return (
      <svg width="18" height="18" viewBox="0 0 18 18">
        <path d="M2.5 4.2c2-.8 4-.8 6.5.4 2.5-1.2 4.5-1.2 6.5-.4v9c-2-.8-4-.8-6.5.4-2.5-1.2-4.5-1.2-6.5-.4v-9z" {...common} />
        <path d="M9 4.6v9" {...common} />
      </svg>
    );
  }
  if (kind === 'fav') {
    return (
      <svg width="18" height="18" viewBox="0 0 18 18">
        <path d="M9 14.5s-5-3.2-5-7A2.8 2.8 0 019 5a2.8 2.8 0 015 2.5c0 3.8-5 7-5 7z" {...common} />
      </svg>
    );
  }
  if (kind === 'emoji') {
    return (
      <svg width="18" height="18" viewBox="0 0 18 18">
        <circle cx="9" cy="9" r="6.5" {...common} />
        <circle cx="6.8" cy="7.8" r="0.8" fill={color} stroke="none" />
        <circle cx="11.2" cy="7.8" r="0.8" fill={color} stroke="none" />
        <path d="M6.5 11c.8 1.2 2.2 1.8 2.5 1.8s1.7-.6 2.5-1.8" {...common} />
      </svg>
    );
  }
  if (kind === 'photo') {
    return (
      <svg width="18" height="18" viewBox="0 0 18 18">
        <rect x="2" y="3.5" width="14" height="11" rx="2" {...common} />
        <circle cx="6" cy="7" r="1.5" {...common} />
        <path d="M2 12.5l4-3.5 3 2.5 3-2 4 3" {...common} />
      </svg>
    );
  }
  if (kind === 'pixel') {
    return (
      <svg width="18" height="18" viewBox="0 0 18 18">
        <rect x="3" y="3" width="4" height="4" fill={color} stroke="none" />
        <rect x="7" y="3" width="4" height="4" fill={color} stroke="none" opacity="0.6" />
        <rect x="11" y="3" width="4" height="4" fill={color} stroke="none" opacity="0.3" />
        <rect x="3" y="7" width="4" height="4" fill={color} stroke="none" opacity="0.6" />
        <rect x="7" y="7" width="4" height="4" fill={color} stroke="none" />
        <rect x="11" y="7" width="4" height="4" fill={color} stroke="none" opacity="0.6" />
        <rect x="3" y="11" width="4" height="4" fill={color} stroke="none" opacity="0.3" />
        <rect x="7" y="11" width="4" height="4" fill={color} stroke="none" opacity="0.6" />
        <rect x="11" y="11" width="4" height="4" fill={color} stroke="none" />
      </svg>
    );
  }
  return null;
}

function IconChip({ active, onClick, icon }) {
  const c = active ? '#FFFFFF' : 'rgba(60,60,67,0.75)';
  return (
    <div onClick={onClick} style={{
      flexShrink: 0, width: 42, height: 42, borderRadius: 21,
      background: active ? '#1C1C1E' : 'rgba(255,255,255,0.8)',
      boxShadow: active
        ? '0 8px 20px -6px rgba(28,28,30,0.35)'
        : '0 1px 2px rgba(60,60,67,0.04), 0 3px 10px -3px rgba(60,60,67,0.06)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      cursor: 'pointer',
      transition: 'all 0.25s cubic-bezier(0.22, 1, 0.36, 1)',
    }}>
      <CategoryIcon kind={icon} color={c} />
    </div>
  );
}

// Home header with category filter
function HomeHeader({ filter, setFilter }) {
  return (
    <div style={{ padding: '0 0 6px' }}>
      <div style={{ padding: '18px 22px 24px', paddingLeft: 68 }}>
        <div style={{
          fontFamily: 'Caveat, cursive',
          fontSize: 30, fontWeight: 800, color: 'rgb(57, 48, 48)',
          lineHeight: 1.3, letterSpacing: '-2px',
          textAlign: 'left', margin: 0, padding: 0,
        }}>
          Anomaly Gallery
        </div>
      </div>

      {/* category filter - scrollable */}
      <div style={{
        display: 'flex', gap: 10, padding: '0 22px',
        justifyContent: 'center',
        overflowX: 'auto', scrollbarWidth: 'none',
        WebkitOverflowScrolling: 'touch',
      }}>
        {CATEGORIES.map(cat => (
          <IconChip
            key={cat.key}
            active={filter === cat.key}
            onClick={() => setFilter(filter === cat.key ? null : cat.key)}
            icon={cat.icon}
          />
        ))}
      </div>
    </div>
  );
}

// Home / Gallery screen
function HomeScreen({ onOpenItem }) {
  const { items, loading, fetchItems } = useGallery();
  const [filter, setFilter] = React.useState(null);
  const [editMode, setEditMode] = React.useState(false);
  const [selected, setSelected] = React.useState({});
  const [deleting, setDeleting] = React.useState(false);

  const filtered = items.filter(it => {
    if (!filter) return true;
    if (filter === 'fav') return it.fav || it.cat === 'fav';
    return it.cat === filter;
  });

  const onRandom = () => {
    if (items.length === 0) return;
    const pick = items[Math.floor(Math.random() * items.length)];
    onOpenItem(pick);
  };

  const toggleSelect = (id) => {
    setSelected(prev => ({ ...prev, [id]: !prev[id] }));
  };

  const selectAll = () => {
    const allSelected = {};
    filtered.forEach(it => { allSelected[it.id] = true; });
    setSelected(allSelected);
  };

  const deleteSelected = async () => {
    const ids = Object.keys(selected).filter(k => selected[k]);
    if (ids.length === 0) return;
    setDeleting(true);
    try {
      await Promise.all(ids.map(id => fetch(`/api/images/${id}`, { method: 'DELETE' })));
      await fetchItems();
      setSelected({});
      setEditMode(false);
    } catch (e) {
      console.error('Delete failed:', e);
    } finally {
      setDeleting(false);
    }
  };

  // Masonry layout
  const colA = [], colB = [];
  let hA = 0, hB = 0;
  filtered.forEach(it => {
    if (hA <= hB) { colA.push(it); hA += (it.aspect || 1.3); }
    else { colB.push(it); hB += (it.aspect || 1.3); }
  });

  const renderCard = (it) => (
    <div key={it.id} style={{ position: 'relative' }}>
      {editMode && (
        <div onClick={(e) => { e.stopPropagation(); toggleSelect(it.id); }} style={{
          position: 'absolute', top: 8, left: 8, zIndex: 10,
          width: 24, height: 24, borderRadius: 12,
          background: selected[it.id] ? '#1C1C1E' : 'rgba(255,255,255,0.85)',
          border: selected[it.id] ? 'none' : '2px solid rgba(60,60,67,0.3)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
          boxShadow: '0 2px 6px rgba(0,0,0,0.15)',
        }}>
          {selected[it.id] && <svg width="12" height="12" viewBox="0 0 12 12"><path d="M2 6l3 3 5-5" stroke="#fff" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>}
        </div>
      )}
      <Card item={it} onClick={(e) => editMode ? toggleSelect(it.id) : onOpenItem(it, e.currentTarget)} />
    </div>
  );

  return (
    <div style={{ position: 'relative' }}>
      <HomeHeader filter={filter} setFilter={setFilter} />

      {loading && (
        <div style={{
          textAlign: 'center', padding: '60px 20px',
          fontFamily: '"Cormorant Garamond", serif',
          fontSize: 18, color: 'rgba(60,60,67,0.5)',
        }}>loading...</div>
      )}

      {!loading && filtered.length === 0 && (
        <div style={{
          textAlign: 'center', padding: '60px 20px',
          fontFamily: '"Cormorant Garamond", serif',
          fontSize: 18, color: 'rgba(60,60,67,0.5)',
        }}>
          {items.length === 0 ? '画廊还是空的，去上传第一张吧' : '这个分类下还没有图片'}
        </div>
      )}

      <div style={{ padding: '14px 18px 100px', display: 'flex', gap: 10 }}>
        <div style={{ flex: 1 }}>
          {colA.map(it => renderCard(it))}
        </div>
        <div style={{ flex: 1 }}>
          {colB.map(it => renderCard(it))}
        </div>
      </div>

      {/* Edit mode top-right action buttons */}
      {editMode && (
        <div style={{
          position: 'absolute', top: 14, right: 66, zIndex: 20,
          display: 'flex', gap: 8,
        }}>
          <div onClick={selectAll} style={{
            padding: '8px 14px', borderRadius: 99,
            background: 'rgba(255,255,255,0.85)', backdropFilter: 'blur(12px)',
            boxShadow: '0 2px 8px rgba(60,60,67,0.12)',
            fontSize: 12, fontWeight: 500, cursor: 'pointer', color: '#1C1C1E',
          }}>全选</div>
          <div onClick={deleteSelected} style={{
            padding: '8px 14px', borderRadius: 99,
            background: deleting ? 'rgba(224,107,143,0.4)' : 'oklch(0.65 0.2 20)',
            boxShadow: '0 2px 8px rgba(224,107,143,0.25)',
            fontSize: 12, fontWeight: 500, color: '#fff',
            cursor: deleting ? 'default' : 'pointer',
            opacity: Object.values(selected).some(v => v) ? 1 : 0.4,
          }}>删除</div>
        </div>
      )}

      {/* floating edit button - top left */}
      <div onClick={() => { setEditMode(!editMode); setSelected({}); }} title="编辑模式" style={{
        position: 'absolute', top: 14, left: 18,
        width: 40, height: 40, borderRadius: 20,
        background: editMode ? '#1C1C1E' : 'rgba(255,255,255,0.7)',
        backdropFilter: 'blur(12px)',
        WebkitBackdropFilter: 'blur(12px)',
        border: '1px solid rgba(60,60,67,0.08)',
        boxShadow: '0 1px 2px rgba(60,60,67,0.04), 0 8px 24px -8px rgba(60,60,67,0.15)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        cursor: 'pointer', zIndex: 20,
        transition: 'all 0.2s cubic-bezier(0.22, 1, 0.36, 1)',
      }}>
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
          <path d="M11.5 1.5l3 3-9 9H2.5v-3l9-9z" stroke={editMode ? '#fff' : '#1C1C1E'} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </div>

      {/* floating wand - random pick */}
      <div onClick={onRandom} title="随机抽一张" style={{
        position: 'absolute', top: 14, right: 18,
        width: 40, height: 40, borderRadius: 20,
        background: 'rgba(255,255,255,0.7)',
        backdropFilter: 'blur(12px)',
        WebkitBackdropFilter: 'blur(12px)',
        border: '1px solid rgba(60,60,67,0.08)',
        boxShadow: '0 1px 2px rgba(60,60,67,0.04), 0 8px 24px -8px rgba(60,60,67,0.15)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        cursor: 'pointer', zIndex: 20,
        transition: 'transform 0.2s cubic-bezier(0.22, 1, 0.36, 1)',
      }}
      onMouseDown={e => e.currentTarget.style.transform = 'scale(0.92)'}
      onMouseUp={e => e.currentTarget.style.transform = 'scale(1)'}
      onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
      >
        <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
          <line x1="4.2" y1="13.8" x2="11.5" y2="6.5" stroke="#1C1C1E" strokeWidth="1.4" strokeLinecap="round"/>
          <path d="M12.8 3.2l0.6 1.5 1.5 0.6-1.5 0.6-0.6 1.5-0.6-1.5-1.5-0.6 1.5-0.6z" fill="#1C1C1E"/>
          <path d="M15.2 8.6l0.25 0.7 0.7 0.25-0.7 0.25-0.25 0.7-0.25-0.7-0.7-0.25 0.7-0.25z" fill="#1C1C1E" opacity="0.5"/>
        </svg>
      </div>
    </div>
  );
}

// Detail screen - real image, real comments, comment form
function DetailScreen({ item, onBack }) {
  const { addComment, fetchItems } = useGallery();
  const c = CHARACTERS[item.char] || CHARACTERS.ning;
  const [commentText, setCommentText] = React.useState('');
  const [commentAuthor, setCommentAuthor] = React.useState('Avenil');
  const [submitting, setSubmitting] = React.useState(false);
  const [editing, setEditing] = React.useState(false);
  const [editTitle, setEditTitle] = React.useState(item.title);
  const [editStory, setEditStory] = React.useState(item.story || '');
  const [editChar, setEditChar] = React.useState(item.char);
  const [editCat, setEditCat] = React.useState(item.cat);
  const [editDate, setEditDate] = React.useState(item.date ? item.date.replace(/\./g, '-') : '');
  const [saving, setSaving] = React.useState(false);
  const comments = item.comments || [];
  const catLabel = CATEGORIES.find(x => x.key === item.cat)?.label || item.cat;

  const handleSubmitComment = async () => {
    if (!commentText.trim() || submitting) return;
    setSubmitting(true);
    // Use the gallery context but pass author
    try {
      const res = await fetch(`/api/images/${item.id}/comments`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text: commentText.trim(), author: commentAuthor }),
      });
      if (res.ok) {
        await fetchItems();
      }
    } catch (e) { console.error(e); }
    setCommentText('');
    setSubmitting(false);
  };

  const handleSaveEdit = async () => {
    setSaving(true);
    try {
      const res = await fetch(`/api/images/${item.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: editTitle,
          story: editStory,
          character: editChar,
          category: editCat,
          date: editDate,
        }),
      });
      if (res.ok) {
        await fetchItems();
        setEditing(false);
      }
    } catch (e) { console.error(e); }
    setSaving(false);
  };

  const formatTimestamp = (ts) => {
    if (!ts) return '';
    const d = new Date(ts);
    const pad = (n) => String(n).padStart(2, '0');
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
  };

  return (
    <div style={{ paddingBottom: 40 }}>
      {/* Hero image */}
      <div style={{
        position: 'relative', width: '100%',
        paddingTop: '100%',
        background: c.tint,
      }}>
        <ImageDisplay item={item} size="detail" />
        {/* top gradient */}
        <div style={{
          position: 'absolute', left: 0, right: 0, top: 0, height: 100,
          background: 'linear-gradient(to bottom, rgba(255,255,255,0.4) 0%, transparent 100%)',
        }} />
        {/* back button */}
        <div onClick={onBack} style={{
          position: 'absolute', top: 16, left: 16,
          width: 40, height: 40, borderRadius: 20,
          background: 'rgba(255,255,255,0.72)',
          backdropFilter: 'blur(16px) saturate(180%)',
          WebkitBackdropFilter: 'blur(16px) saturate(180%)',
          boxShadow: '0 2px 8px rgba(60,60,67,0.1)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
        }}>
          <svg width="10" height="16" viewBox="0 0 10 16"><path d="M8 1L1 8l7 7" stroke="#1C1C1E" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </div>
        {/* edit button */}
        <div onClick={() => setEditing(!editing)} style={{
          position: 'absolute', top: 16, right: 16,
          width: 40, height: 40, borderRadius: 20,
          background: editing ? '#1C1C1E' : 'rgba(255,255,255,0.72)',
          backdropFilter: 'blur(16px) saturate(180%)',
          WebkitBackdropFilter: 'blur(16px) saturate(180%)',
          boxShadow: '0 2px 8px rgba(60,60,67,0.1)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
        }}>
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
            <path d="M11.5 1.5l3 3-9 9H2.5v-3l9-9z" stroke={editing ? '#fff' : '#1C1C1E'} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
      </div>

      {/* Meta card */}
      <div style={{
        margin: '-22px 16px 0', position: 'relative', zIndex: 2,
        borderRadius: 22, background: '#FFFFFF',
        boxShadow: '0 1px 2px rgba(60,60,67,0.05), 0 20px 40px -12px rgba(60,60,67,0.12)',
        padding: '20px 22px', overflow: 'hidden',
      }}>
        {!editing ? (
          <>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '3px 9px 3px 7px', borderRadius: 99,
              background: c.tint,
              fontFamily: 'ui-monospace, "SF Mono", monospace', fontSize: 9,
              color: c.ink, letterSpacing: 1.5, textTransform: 'uppercase',
              fontWeight: 600,
            }}>
              <span style={{
                width: 7, height: 7, borderRadius: 4,
                background: c.dual
                  ? `conic-gradient(from 180deg, oklch(0.82 0.12 85), oklch(0.70 0.14 300), oklch(0.82 0.12 85))`
                  : c.dot,
              }} />
              {c.en} · {item.date}
            </div>
            <div style={{
              fontFamily: '"Cormorant Garamond", "Songti SC", serif',
              fontSize: 32, fontWeight: 500, color: '#1C1C1E',
              lineHeight: 1.1, marginTop: 10, letterSpacing: 0.2,
            }}>{item.title}</div>
            {item.story && (
              <div style={{
                marginTop: 18, fontSize: 14.5, lineHeight: 1.7,
                color: 'rgba(28,28,30,0.82)', textWrap: 'pretty',
              }}>{item.story}</div>
            )}
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 18 }}>
              <Tag>#{catLabel}</Tag>
              {(item.tags || []).map(t => <Tag key={t}>#{t}</Tag>)}
            </div>
          </>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div>
              <div style={{ fontSize: 11, color: 'rgba(60,60,67,0.5)', marginBottom: 4 }}>标题</div>
              <input value={editTitle} onChange={e => setEditTitle(e.target.value)} style={inputStyle} />
            </div>
            <div>
              <div style={{ fontSize: 11, color: 'rgba(60,60,67,0.5)', marginBottom: 4 }}>故事</div>
              <textarea value={editStory} onChange={e => setEditStory(e.target.value)} style={{ ...inputStyle, minHeight: 80, resize: 'none', lineHeight: 1.6 }} />
            </div>
            <div>
              <div style={{ fontSize: 11, color: 'rgba(60,60,67,0.5)', marginBottom: 4 }}>角色</div>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {Object.values(CHARACTERS).map(ch => (
                  <div key={ch.key} onClick={() => setEditChar(ch.key)} style={{
                    padding: '6px 10px', borderRadius: 99, cursor: 'pointer',
                    background: editChar === ch.key ? ch.tint : '#F2F2F4',
                    fontSize: 12, fontWeight: 500, color: editChar === ch.key ? ch.ink : '#1C1C1E',
                  }}>{ch.zh}</div>
                ))}
              </div>
            </div>
            <div>
              <div style={{ fontSize: 11, color: 'rgba(60,60,67,0.5)', marginBottom: 4 }}>分类</div>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {CATEGORIES.map(cat2 => (
                  <div key={cat2.key} onClick={() => setEditCat(cat2.key)} style={{
                    padding: '6px 10px', borderRadius: 99, cursor: 'pointer',
                    background: editCat === cat2.key ? '#1C1C1E' : '#F2F2F4',
                    fontSize: 12, fontWeight: 500, color: editCat === cat2.key ? '#fff' : '#1C1C1E',
                  }}>{cat2.label}</div>
                ))}
              </div>
            </div>
            <div>
              <div style={{ fontSize: 11, color: 'rgba(60,60,67,0.5)', marginBottom: 4 }}>日期</div>
              <input type="date" value={editDate} onChange={e => setEditDate(e.target.value)} style={inputStyle} />
            </div>
            <div onClick={handleSaveEdit} style={{
              padding: '12px', borderRadius: 14, textAlign: 'center',
              background: '#1C1C1E', color: '#fff', fontSize: 14, fontWeight: 500,
              cursor: saving ? 'default' : 'pointer', opacity: saving ? 0.6 : 1,
            }}>{saving ? '保存中……' : '保存修改'}</div>
          </div>
        )}
      </div>

      {/* Comments section */}
      <div style={{ padding: '26px 22px 0' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          fontFamily: 'ui-monospace, monospace', fontSize: 10,
          color: 'rgba(60,60,67,0.4)', letterSpacing: 2, textTransform: 'uppercase',
        }}>
          <span style={{ flex: 1, height: 0.5, background: 'rgba(60,60,67,0.15)' }} />
          <span>Annotations · 注脚</span>
          <span style={{ flex: 1, height: 0.5, background: 'rgba(60,60,67,0.15)' }} />
        </div>

        {comments.length === 0 && (
          <div style={{
            textAlign: 'center', padding: '24px 0',
            fontSize: 13, color: 'rgba(60,60,67,0.4)',
          }}>还没有注脚，写下第一条吧</div>
        )}

        <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 12 }}>
          {comments.map((cm, i) => {
            const isAI = cm.author !== 'Avenil' && cm.author !== '我';
            return (
              <div key={cm.id || i} style={{
                display: 'flex', gap: 10,
                flexDirection: isAI ? 'row-reverse' : 'row',
              }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 16, flexShrink: 0,
                  background: isAI ? c.dot : '#EDEDED',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 11, fontWeight: 600,
                  color: isAI ? '#FFFFFF' : '#1C1C1E',
                  fontFamily: '"Cormorant Garamond", serif',
                }}>{(cm.author || '?').slice(0, 1)}</div>
                <div style={{
                  flex: 1, padding: '10px 14px', borderRadius: 16,
                  background: isAI ? c.tint : '#F2F2F4',
                  borderTopLeftRadius: isAI ? 16 : 4,
                  borderTopRightRadius: isAI ? 4 : 16,
                }}>
                  <div style={{
                    fontSize: 13.5, lineHeight: 1.55,
                    color: '#1C1C1E', textWrap: 'pretty',
                  }}>{cm.text}</div>
                  <div style={{
                    fontFamily: 'ui-monospace, monospace', fontSize: 9,
                    color: 'rgba(60,60,67,0.4)', letterSpacing: 1,
                    marginTop: 5, textTransform: 'uppercase',
                  }}>{formatTimestamp(cm.createdAt)}</div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Comment input with author selector */}
        <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ display: 'flex', gap: 6 }}>
            {['Avenil', 'Oshra', 'Arbor'].map(name => (
              <div key={name} onClick={() => setCommentAuthor(name)} style={{
                padding: '5px 12px', borderRadius: 99, cursor: 'pointer',
                background: commentAuthor === name ? '#1C1C1E' : '#F2F2F4',
                color: commentAuthor === name ? '#fff' : '#1C1C1E',
                fontSize: 12, fontWeight: 500,
                transition: 'all 0.2s ease',
              }}>{name}</div>
            ))}
          </div>
          <div style={{
            padding: '8px 8px 8px 16px', borderRadius: 22,
            background: '#FFFFFF',
            boxShadow: '0 1px 2px rgba(60,60,67,0.05), 0 4px 12px -2px rgba(60,60,67,0.06)',
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <input
              value={commentText}
              onChange={e => setCommentText(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter') handleSubmitComment(); }}
              placeholder="写下一点什么……"
              style={{
                flex: 1, border: 'none', outline: 'none',
                fontSize: 13.5, color: '#1C1C1E',
                background: 'transparent',
                fontFamily: '-apple-system, system-ui',
              }}
            />
            <div onClick={handleSubmitComment} style={{
              width: 30, height: 30, borderRadius: 15,
              background: submitting ? 'rgba(60,60,67,0.3)' : c.dot,
              color: '#fff', fontSize: 15,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              cursor: submitting ? 'default' : 'pointer',
              boxShadow: `0 4px 10px -2px ${c.dot.replace(')', ' / 0.4)')}`,
              transition: 'background 0.2s',
            }}>↑</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Tag({ children }) {
  return (
    <div style={{
      fontSize: 11, color: 'rgba(60,60,67,0.7)',
      padding: '4px 10px', borderRadius: 99,
      background: 'rgba(60,60,67,0.06)',
      fontFamily: '-apple-system, system-ui',
    }}>{children}</div>
  );
}

// Upload screen - real file upload to /api/images
function UploadScreen() {
  const { addItem } = useGallery();
  const [char, setChar] = React.useState('ning');
  const [cat, setCat] = React.useState('portrait');
  const [title, setTitle] = React.useState('');
  const [story, setStory] = React.useState('');
  const [tags, setTags] = React.useState([]);
  const [tagInput, setTagInput] = React.useState('');
  const [file, setFile] = React.useState(null);
  const [preview, setPreview] = React.useState(null);
  const [uploadDate, setUploadDate] = React.useState(new Date().toISOString().slice(0, 10));
  const [uploading, setUploading] = React.useState(false);
  const [success, setSuccess] = React.useState(false);
  const [error, setError] = React.useState('');
  const fileInputRef = React.useRef(null);
  const c = CHARACTERS[char];

  const handleFileSelect = (e) => {
    const f = e.target.files[0];
    if (!f) return;
    setFile(f);
    const reader = new FileReader();
    reader.onload = (ev) => setPreview(ev.target.result);
    reader.readAsDataURL(f);
  };

  const handleDrop = (e) => {
    e.preventDefault();
    const f = e.dataTransfer.files[0];
    if (!f) return;
    setFile(f);
    const reader = new FileReader();
    reader.onload = (ev) => setPreview(ev.target.result);
    reader.readAsDataURL(f);
  };

  const handleAddTag = () => {
    const t = tagInput.trim();
    if (t && !tags.includes(t)) {
      setTags([...tags, t]);
    }
    setTagInput('');
  };

  const handleSubmit = async () => {
    if (!file || uploading) return;
    setUploading(true);
    try {
      const formData = new FormData();
      formData.append('image', file);
      formData.append('title', title || '未命名');
      formData.append('story', story);
      formData.append('tags', JSON.stringify(tags));
      formData.append('character', char);
      formData.append('category', cat);
      formData.append('date', new Date(uploadDate).toISOString());

      const res = await fetch('/api/images', {
        method: 'POST',
        body: formData,
      });
      if (!res.ok) throw new Error('Upload failed');
      const img = await res.json();

      // Add to local state
      addItem({
        id: img.id,
        char: img.character || char,
        cat: img.category || cat,
        title: img.title,
        sub: img.tags && img.tags.length > 0 ? img.tags[0] : '',
        date: new Date(img.createdAt).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '.'),
        story: img.story,
        tags: img.tags || [],
        filename: img.filename,
        imageUrl: `/uploads/${img.filename}`,
        comments: [],
        aspect: 1.3,
        fav: img.category === 'fav',
        seed: parseInt(img.id, 16) % 1000 || 42,
      });

      // Reset form
      setSuccess(true);
      setFile(null);
      setPreview(null);
      setTitle('');
      setStory('');
      setTags([]);
      setTimeout(() => setSuccess(false), 3000);
    } catch (e) {
      console.error('Upload failed:', e);
      setError('上传失败: ' + e.message);
      setTimeout(() => setError(''), 5000);
    } finally {
      setUploading(false);
    }
  };

  return (
    <div style={{ padding: '0 0 100px' }}>
      <div style={{ padding: '10px 22px 22px' }}>
        <div style={{
          fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro", system-ui, sans-serif', fontSize: 10,
          color: 'rgba(60,60,67,0.5)', letterSpacing: 2, textTransform: 'uppercase',
        }}>New entry · 新增卷宗</div>
        <div style={{
          fontFamily: 'Raleway, -apple-system, "PingFang SC", sans-serif',
          fontSize: 32, fontWeight: 500, color: '#1C1C1E',
          lineHeight: 1.1, marginTop: 6, letterSpacing: 0.2,
        }}>新的记忆……</div>
      </div>

      {/* Success toast */}
      {success && (
        <div style={{
          margin: '0 18px 16px', padding: '14px 18px', borderRadius: 16,
          background: 'oklch(0.92 0.04 155)', color: 'oklch(0.45 0.09 155)',
          fontSize: 14, fontWeight: 500, textAlign: 'center',
        }}>封印成功 · 已收入画廊</div>
      )}

      {/* Drop zone / file picker */}
      <div style={{ padding: '0 18px' }}>
        <div
          onClick={() => fileInputRef.current?.click()}
          onDrop={handleDrop}
          onDragOver={e => e.preventDefault()}
          style={{
            position: 'relative', borderRadius: 24, overflow: 'hidden',
            paddingTop: preview ? '0' : '88%',
            height: preview ? 280 : undefined,
            background: preview ? '#000' : `linear-gradient(140deg, ${c.tint} 0%, #FFFFFF 100%)`,
            boxShadow: '0 1px 2px rgba(60,60,67,0.04), 0 12px 32px -12px rgba(60,60,67,0.12)',
            transition: 'background 0.4s ease',
            cursor: 'pointer',
          }}
        >
          {preview ? (
            <img src={preview} style={{
              width: '100%', height: '100%', objectFit: 'cover',
            }} />
          ) : (
            <>
              {/* soft orb */}
              <div style={{
                position: 'absolute', left: '50%', top: '38%',
                transform: 'translate(-50%, -50%)',
                width: 180, height: 180, borderRadius: '50%',
                background: `radial-gradient(circle, ${c.dot.replace(')', ' / 0.2)')} 0%, transparent 70%)`,
                filter: 'blur(8px)',
              }} />
              {/* rings */}
              {[0, 1, 2].map(i => (
                <div key={i} style={{
                  position: 'absolute',
                  left: '50%', top: '38%',
                  width: 70 + i * 60, height: 70 + i * 60,
                  borderRadius: '50%',
                  border: `0.5px solid ${c.dot.replace(')', ` / ${0.25 - i * 0.07})`)}`,
                  transform: 'translate(-50%, -50%)',
                }} />
              ))}
              <div style={{
                position: 'absolute', inset: 0,
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                gap: 14, paddingTop: '10%',
              }}>
                <div style={{
                  width: 60, height: 60, borderRadius: 30,
                  background: '#FFFFFF',
                  boxShadow: `0 6px 18px -4px ${c.dot.replace(')', ' / 0.35)')}, 0 1px 2px rgba(60,60,67,0.1)`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: c.ink, fontSize: 24, fontWeight: 300,
                }}>↑</div>
                <div style={{
                  fontFamily: '"Cormorant Garamond", "Songti SC", serif',
                  fontSize: 19, fontWeight: 500, color: '#1C1C1E',
                }}>拖拽或点击上传</div>
                <div style={{
                  fontFamily: 'ui-monospace, monospace', fontSize: 10,
                  color: 'rgba(60,60,67,0.45)', letterSpacing: 1.5, textTransform: 'uppercase',
                }}>PNG · JPG · WEBP · GIF · ≤ 20MB</div>
              </div>
            </>
          )}
          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            onChange={handleFileSelect}
            style={{ display: 'none' }}
          />
        </div>
      </div>

      {/* Form fields */}
      <div style={{ padding: '24px 22px 0', display: 'flex', flexDirection: 'column', gap: 22 }}>
        <Field label="标题" sub="Title">
          <input
            value={title} onChange={e => setTitle(e.target.value)}
            placeholder="给这段记忆一个名字……"
            style={inputStyle}
          />
        </Field>

        <Field label="归属角色" sub="Character">
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {Object.values(CHARACTERS).map(ch => (
              <div key={ch.key} onClick={() => setChar(ch.key)} style={{
                padding: '8px 12px 8px 10px', borderRadius: 99,
                background: char === ch.key ? ch.tint : '#FFFFFF',
                boxShadow: char === ch.key
                  ? `0 6px 16px -6px ${ch.dot.replace(')', ' / 0.4)')}, 0 1px 2px rgba(60,60,67,0.05)`
                  : '0 1px 2px rgba(60,60,67,0.04), 0 3px 10px -3px rgba(60,60,67,0.06)',
                display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer',
                transition: 'all 0.22s ease',
              }}>
                <div style={{
                  width: 12, height: 12, borderRadius: 12,
                  background: ch.dual
                    ? `conic-gradient(from 180deg, oklch(0.82 0.12 85), oklch(0.70 0.14 300), oklch(0.82 0.12 85))`
                    : ch.dot,
                }} />
                <span style={{
                  fontSize: 13, fontWeight: 500,
                  color: char === ch.key ? ch.ink : '#1C1C1E',
                }}>{ch.zh}</span>
              </div>
            ))}
          </div>
        </Field>

        <Field label="分类" sub="Category">
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {CATEGORIES.map(cat2 => (
              <div key={cat2.key} onClick={() => setCat(cat2.key)} style={{
                padding: '8px 14px', borderRadius: 99,
                background: cat === cat2.key ? '#1C1C1E' : '#FFFFFF',
                boxShadow: cat === cat2.key
                  ? '0 6px 16px -6px rgba(28,28,30,0.4)'
                  : '0 1px 2px rgba(60,60,67,0.04), 0 3px 10px -3px rgba(60,60,67,0.06)',
                cursor: 'pointer',
                fontSize: 13, fontWeight: 500,
                color: cat === cat2.key ? '#FFFFFF' : '#1C1C1E',
                transition: 'all 0.22s ease',
              }}>{cat2.label}</div>
            ))}
          </div>
        </Field>

        <Field label="日期" sub="Date">
          <input
            type="date"
            value={uploadDate} onChange={e => setUploadDate(e.target.value)}
            style={inputStyle}
          />
        </Field>

        <Field label="故事" sub="Story">
          <textarea
            value={story} onChange={e => setStory(e.target.value)}
            placeholder={"写下这张图背后的那一刻……\n\n（可选）"}
            style={{ ...inputStyle, minHeight: 96, resize: 'none', lineHeight: 1.6 }}
          />
        </Field>

        <Field label="标签" sub="Tags">
          <div style={{
            display: 'flex', flexWrap: 'wrap', gap: 6,
            padding: 12, borderRadius: 16,
            background: '#FFFFFF',
            boxShadow: '0 1px 2px rgba(60,60,67,0.04), 0 3px 10px -3px rgba(60,60,67,0.06)',
            minHeight: 44, alignItems: 'center',
          }}>
            {tags.map(t => (
              <div key={t} style={{
                fontSize: 12, color: c.ink,
                padding: '4px 10px', borderRadius: 99,
                background: c.tint,
                display: 'flex', alignItems: 'center', gap: 6,
              }}>
                #{t}
                <span style={{
                  color: 'rgba(60,60,67,0.4)', cursor: 'pointer', fontSize: 10,
                }} onClick={() => setTags(tags.filter(x => x !== t))}>✕</span>
              </div>
            ))}
            <input
              value={tagInput}
              onChange={e => setTagInput(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); handleAddTag(); } }}
              placeholder="+ 添加标签"
              style={{
                border: 'none', outline: 'none', background: 'transparent',
                fontSize: 12, color: 'rgba(60,60,67,0.6)', minWidth: 80,
                padding: '4px 4px',
              }}
            />
          </div>
        </Field>

        {/* Submit */}
        <div onClick={handleSubmit} style={{
          marginTop: 10, padding: '16px', borderRadius: 18,
          background: file ? '#1C1C1E' : 'rgba(60,60,67,0.2)',
          color: '#FFFFFF',
          textAlign: 'center', cursor: file ? 'pointer' : 'default',
          boxShadow: file ? '0 12px 28px -8px rgba(28,28,30,0.35)' : 'none',
          fontFamily: '"Cormorant Garamond", "Songti SC", serif',
          fontSize: 18, fontWeight: 600, letterSpacing: 0.5,
          transition: 'all 0.3s ease',
          opacity: uploading ? 0.6 : 1,
        }}>{success ? '已封入 ✓' : uploading ? '封印中……' : '封入画廊 · Seal into Gallery'}</div>

        {error && <div style={{ marginTop: 10, padding: '12px', borderRadius: 12, background: 'rgba(224,107,143,0.1)', color: '#c4546e', fontSize: 13, textAlign: 'center' }}>{error}</div>}
      </div>
    </div>
  );
}

function Field({ label, sub, children }) {
  return (
    <div>
      <div style={{
        display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 8,
      }}>
        <span style={{
          fontFamily: '"Cormorant Garamond", "Songti SC", serif',
          fontSize: 16, fontWeight: 600, color: '#1C1C1E',
        }}>{label}</span>
        <span style={{
          fontFamily: 'ui-monospace, monospace', fontSize: 9,
          color: 'rgba(60,60,67,0.45)', letterSpacing: 1.5, textTransform: 'uppercase',
        }}>{sub}</span>
      </div>
      {children}
    </div>
  );
}

const inputStyle = {
  width: '100%', boxSizing: 'border-box',
  padding: '14px 16px', borderRadius: 16,
  background: '#FFFFFF',
  boxShadow: '0 1px 2px rgba(60,60,67,0.04), 0 3px 10px -3px rgba(60,60,67,0.06)',
  border: 'none',
  color: '#1C1C1E', fontSize: 14,
  fontFamily: '-apple-system, system-ui',
  outline: 'none',
};

// Me / Archive screen
function MeScreen() {
  const { items } = useGallery();
  const stats = Object.values(CHARACTERS).map(c => ({
    c, count: items.filter(it => it.char === c.key).length,
  }));
  const totalFav = items.filter(i => i.fav || i.cat === 'fav').length;

  return (
    <div style={{ padding: '0 22px 100px' }}>
      <div style={{ padding: '10px 0 22px' }}>
        <div style={{
          fontFamily: 'ui-monospace, monospace', fontSize: 10,
          color: 'rgba(60,60,67,0.5)', letterSpacing: 2, textTransform: 'uppercase',
        }}>Curator · 守瓮人</div>
        <div style={{
          fontFamily: '"Cormorant Garamond", "Songti SC", serif',
          fontSize: 32, fontWeight: 500, color: '#1C1C1E',
          lineHeight: 1.1, marginTop: 6,
        }}>我的画廊</div>
      </div>

      <div style={{
        padding: 20, borderRadius: 22,
        background: '#FFFFFF',
        boxShadow: '0 1px 2px rgba(60,60,67,0.04), 0 12px 32px -12px rgba(60,60,67,0.1)',
      }}>
        <div style={{ display: 'flex', gap: 18 }}>
          <Stat big={items.length} label="卷宗" sub="ENTRIES"/>
          <div style={{ width: 0.5, background: 'rgba(60,60,67,0.12)' }} />
          <Stat big={Object.keys(CHARACTERS).length} label="角色" sub="SOULS"/>
          <div style={{ width: 0.5, background: 'rgba(60,60,67,0.12)' }} />
          <Stat big={totalFav} label="收藏" sub="FAVS"/>
        </div>
      </div>

      <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {stats.map(({ c, count }) => (
          <div key={c.key} style={{
            padding: '14px 16px', borderRadius: 18,
            background: '#FFFFFF',
            boxShadow: '0 1px 2px rgba(60,60,67,0.04), 0 6px 16px -6px rgba(60,60,67,0.08)',
            display: 'flex', alignItems: 'center', gap: 14,
            position: 'relative', overflow: 'hidden',
          }}>
            <div style={{
              width: 44, height: 44, borderRadius: 22,
              background: c.tint,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <div style={{
                width: 14, height: 14, borderRadius: 14,
                background: c.dual
                  ? `conic-gradient(from 180deg, oklch(0.82 0.12 85), oklch(0.70 0.14 300), oklch(0.82 0.12 85))`
                  : c.dot,
              }} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{
                fontFamily: '"Cormorant Garamond", "Songti SC", serif',
                fontSize: 18, fontWeight: 500, color: '#1C1C1E',
              }}>{c.zh}</div>
              <div style={{
                fontFamily: 'ui-monospace, monospace', fontSize: 9,
                color: 'rgba(60,60,67,0.5)', letterSpacing: 1.5, marginTop: 1, textTransform: 'uppercase',
              }}>{c.en} · {count} entries</div>
            </div>
            <div style={{
              fontFamily: '"Cormorant Garamond", serif',
              fontSize: 26, fontWeight: 500, color: c.ink,
            }}>{count}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function Stat({ big, label, sub }) {
  return (
    <div style={{ flex: 1 }}>
      <div style={{
        fontFamily: '"Cormorant Garamond", serif',
        fontSize: 36, fontWeight: 500, color: '#1C1C1E',
        lineHeight: 1,
      }}>{big}</div>
      <div style={{ fontSize: 12, color: '#1C1C1E', marginTop: 4, fontWeight: 500 }}>{label}</div>
      <div style={{
        fontFamily: 'ui-monospace, monospace', fontSize: 8,
        color: 'rgba(60,60,67,0.45)', letterSpacing: 1.2, textTransform: 'uppercase',
      }}>{sub}</div>
    </div>
  );
}

Object.assign(window, { HomeScreen, DetailScreen, UploadScreen, MeScreen });
