// Feedback page — Mirrors the structure of apps/webapp/app/(dashboard)/feedback/page.tsx
// Header + sort tabs + search + sidebar boards + post list with vote columns
// Modeled on FeedbackForm dialog from feedback-form.tsx

function FeedbackPage() {
  const [activeBoard, setActiveBoard] = React.useState('all');
  const [sortBy, setSortBy] = React.useState('new');
  const [searchQuery, setSearchQuery] = React.useState('');
  const [isFormOpen, setIsFormOpen] = React.useState(false);
  const [voted, setVoted] = React.useState({}); // id -> bool
  const [voteOffset, setVoteOffset] = React.useState({}); // id -> +1/-1

  const boards = [
  { id: 'all', name: 'View all posts', icon: I.MsgCircle },
  { id: 'feature', name: 'Feature Request', icon: I.Bulb },
  { id: 'feedback', name: 'Feedback', icon: I.MsgCircle },
  { id: 'bug', name: 'Bug Reports', icon: I.Bug }];


  const items = [
  {
    id: 'p1', type: 'feature', status: 'in_progress',
    title: 'Bulk re-categorize bookmarks across collections',
    content: "When I import 200+ bookmarks from Raindrop, I'd love to multi-select and move them to a different collection in one go — currently I have to drag each one.",
    author: 'Maya Chen', initials: 'MC', avatarColor: '#F97316',
    votes: 142, ago: '2 days ago'
  },
  {
    id: 'p2', type: 'bug', status: 'pending',
    title: 'Chrome extension fails on Substack archive pages',
    content: 'Saving an article from a Substack archive view loses the author field — the regular post URL works fine. Repro on every Substack I tried.',
    author: 'Daniel Park', initials: 'DP', avatarColor: '#2563EB',
    votes: 87, ago: '5 hours ago'
  },
  {
    id: 'p3', type: 'feature', status: 'pending',
    title: 'Integrate with NotebookLM',
    content: 'Trove could use a NotebookLM integration upgrade so that every link, video or article I saved can instantly be used in my preferred medium i.e. podcast-like summary, flash cards etc.',
    author: 'Aakash G.', initials: 'AG', avatarColor: '#10B981',
    votes: 211, ago: '1 week ago'
  },
  {
    id: 'p4', type: 'feedback', status: 'pending',
    title: 'Enable Email to Trove transfer',
    content: "I get a bunch of newsletters and links in my email and I don't know where to keep them - my instinct is to send to Trove but there's no clear way to do that today?",
    author: 'Priya Shah', initials: 'PS', avatarColor: '#A855F7',
    votes: 64, ago: '3 days ago'
  },
  {
    id: 'p5', type: 'feature', status: 'pending',
    title: 'Export AI Chats to Trove',
    content: 'During an AI Chat sometimes an analysis is worth saving for future reference. How can I export that specific thing to Trove directly?',
    author: 'Tom Ochiai', initials: 'TO', avatarColor: '#EF4444',
    votes: 33, ago: '2 weeks ago'
  },
  {
    id: 'p6', type: 'feature', status: 'pending',
    title: 'Shared collections with view-only access',
    content: "I run a small reading group and want to share a curated collection with 8 people without giving them edit rights. A magic link with view-only would be perfect.",
    author: 'Rina Okada', initials: 'RO', avatarColor: '#0EA5E9',
    votes: 96, ago: '4 days ago'
  },
  {
    id: 'p7', type: 'feedback', status: 'pending',
    title: 'Insights page is genuinely surprising',
    content: 'The "what topics you actually read vs. save" chart caught me — I save tons of leadership stuff and read almost none of it. Useful, slightly humbling.',
    author: 'James Whitfield', initials: 'JW', avatarColor: '#F59E0B',
    votes: 51, ago: '6 days ago'
  }];


  const typeMeta = {
    feature: { label: 'feature', bg: 'rgba(168,85,247,0.10)', color: '#A855F7' },
    bug: { label: 'bug', bg: 'rgba(239,68,68,0.10)', color: '#EF4444' },
    feedback: { label: 'feedback', bg: 'rgba(37,99,235,0.10)', color: 'var(--blue)' },
    report: { label: 'report', bg: 'rgba(245,158,11,0.10)', color: '#F59E0B' }
  };

  const statusMeta = {
    in_progress: { label: 'in progress', bg: 'rgba(37,99,235,0.10)', color: 'var(--blue)' },
    solved: { label: 'solved', bg: 'rgba(16,185,129,0.10)', color: '#10B981' }
  };

  const filtered = items.filter((it) => {
    if (activeBoard !== 'all' && it.type !== activeBoard) return false;
    if (!searchQuery) return true;
    const q = searchQuery.toLowerCase();
    return it.title.toLowerCase().includes(q) || it.content.toLowerCase().includes(q);
  });

  const sorted = [...filtered].sort((a, b) => {
    if (sortBy === 'top' || sortBy === 'trending') {
      return b.votes + (voteOffset[b.id] || 0) - (a.votes + (voteOffset[a.id] || 0));
    }
    return 0; // 'new' — keep array order
  });

  const onVote = (id) => {
    const isVoted = voted[id];
    setVoted((v) => ({ ...v, [id]: !isVoted }));
    setVoteOffset((o) => ({ ...o, [id]: (o[id] || 0) + (isVoted ? -1 : 1) }));
  };

  return (
    <div className="fb-page">
      {/* Header */}
      <div className="fb-header">
        <div className="fb-header-icon">
          <I.MsgCircle className="icon" />
        </div>
        <div>
          <h1 className="fb-title">Trove Feedback</h1>
          <p className="fb-subtitle">Have something to say? Tell us how to make Trove more useful.</p>
        </div>
      </div>

      <div className="fb-grid">
        {/* Main column */}
        <div className="fb-main">
          {/* Controls row */}
          <div className="fb-controls">
            <div className="fb-tabs">
              {[
              { id: 'new', label: 'New', icon: I.Plus },
              { id: 'top', label: 'Top', icon: I.ChevronUp },
              { id: 'trending', label: 'Trending', icon: I.TrendUp }].
              map((t) => {
                const Icon = t.icon;
                return (
                  <button
                    key={t.id}
                    className={`fb-tab ${sortBy === t.id ? 'active' : ''}`}
                    onClick={() => setSortBy(t.id)}>
                    
                    <Icon className="icon icon-sm" />
                    {t.label}
                  </button>);

              })}
            </div>

            <div className="fb-search">
              <I.Search className="icon icon-sm" />
              <input
                placeholder="Search"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)} />
              
            </div>

            <button className="btn btn-primary fb-newpost" onClick={() => setIsFormOpen(true)}>
              <I.Plus className="icon icon-sm" />
              <span>New Post</span>
            </button>
          </div>

          {/* List */}
          <div className="fb-list card">
            {sorted.length === 0 ?
            <div className="fb-empty">
                <I.MsgCircle className="icon" style={{ width: 40, height: 40, opacity: 0.2 }} />
                <p>No feedback posts found.</p>
                <button className="link-btn" onClick={() => setIsFormOpen(true)}>Be the first to post!</button>
              </div> :
            sorted.map((it) => {
              const tm = typeMeta[it.type] || typeMeta.feedback;
              const sm = statusMeta[it.status];
              const isVoted = voted[it.id];
              const count = it.votes + (voteOffset[it.id] || 0);
              return (
                <div key={it.id} className="fb-row">
                  {/* Vote */}
                  <button
                    className={`fb-vote ${isVoted ? 'voted' : ''}`}
                    onClick={() => onVote(it.id)}
                    aria-label="Upvote">
                    
                    <I.ChevronUp className="icon icon-sm" />
                    <span>{count}</span>
                  </button>

                  {/* Content */}
                  <div className="fb-row-body">
                    <h3 className="fb-row-title">{it.title}</h3>
                    <p className="fb-row-content">{it.content}</p>
                    <div className="fb-row-meta">
                      <div className="fb-author">
                        <span className="fb-avatar" style={{ background: it.avatarColor }}>{it.initials}</span>
                        <span className="fb-author-name">{it.author}</span>
                      </div>
                      <span className="fb-badge" style={{ background: tm.bg, color: tm.color, borderColor: tm.color + '33' }}>
                        {tm.label}
                      </span>
                      {sm &&
                      <span className="fb-badge" style={{ ...{ background: sm.bg, color: sm.color, borderColor: sm.color + '33' }, color: "rgb(168, 87, 247)", background: "rgb(246, 237, 254)" }}>
                          {sm.label}
                        </span>
                      }
                      <span className="fb-ago">{it.ago}</span>
                    </div>
                  </div>
                </div>);

            })}
          </div>
        </div>

        {/* Sidebar */}
        <div className="fb-side">
          <div className="card fb-side-card">
            <h3 className="fb-side-title">Boards</h3>
            <div className="fb-board-list">
              {boards.map((b) => {
                const Icon = b.icon;
                return (
                  <button
                    key={b.id}
                    className={`fb-board ${activeBoard === b.id ? 'active' : ''}`}
                    onClick={() => setActiveBoard(b.id)}>
                    
                    <Icon className="icon icon-sm" />
                    <span>{b.name}</span>
                  </button>);

              })}
            </div>
          </div>

          <div className="card fb-side-card fb-support">
            <h3 className="fb-side-title">Support Trove</h3>
            <p>Your feedback directly shapes the future of Trove. We read every post and appreciate your contribution!</p>
          </div>
        </div>
      </div>

      {isFormOpen && <FeedbackForm onClose={() => setIsFormOpen(false)} />}
    </div>);

}

function FeedbackForm({ onClose }) {
  const [type, setType] = React.useState('feedback');
  const [title, setTitle] = React.useState('');
  const [content, setContent] = React.useState('');
  const [attachments, setAttachments] = React.useState([]);
  const [submitting, setSubmitting] = React.useState(false);

  const onSubmit = (e) => {
    e.preventDefault();
    if (!title || !content) return;
    setSubmitting(true);
    setTimeout(() => {setSubmitting(false);onClose();}, 600);
  };

  const onAddFile = () => {
    // Mock file pick
    const names = ['screenshot.png', 'crash-log.txt', 'recording.mov', 'mockup.pdf'];
    const pick = names[attachments.length % names.length];
    setAttachments((a) => [...a, { name: pick }]);
  };

  return (
    <div className="fb-modal-overlay" onClick={onClose}>
      <div className="fb-modal" onClick={(e) => e.stopPropagation()}>
        <div className="fb-modal-header">
          <div>
            <h2>Submit Feedback</h2>
            <p>Help us improve Trove by sharing your thoughts or reporting issues.</p>
          </div>
          <button className="btn-icon" onClick={onClose} aria-label="Close">
            <I.Close className="icon icon-sm" />
          </button>
        </div>

        <form onSubmit={onSubmit} className="fb-form">
          <div className="fb-field">
            <label>Feedback Type</label>
            <select value={type} onChange={(e) => setType(e.target.value)} className="fb-select">
              <option value="feedback">General Feedback</option>
              <option value="feature">Feature Request</option>
              <option value="bug">Bug Report</option>
              <option value="report">Item Report</option>
            </select>
          </div>

          <div className="fb-field">
            <label>Title</label>
            <input
              type="text"
              placeholder="Brief summary..."
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="input" />
            
          </div>

          <div className="fb-field">
            <label>Description</label>
            <textarea
              placeholder="Tell us more about it..."
              value={content}
              onChange={(e) => setContent(e.target.value)}
              className="fb-textarea"
              rows={5} />
            
          </div>

          <div className="fb-field">
            <label>Attachments</label>
            <div className="fb-attach-row">
              {attachments.map((f, i) =>
              <div key={i} className="fb-attach-chip">
                  <span>{f.name}</span>
                  <button
                  type="button"
                  onClick={() => setAttachments((a) => a.filter((_, j) => j !== i))}
                  aria-label="Remove">
                  
                    <I.Close className="icon" style={{ width: 12, height: 12 }} />
                  </button>
                </div>
              )}
              <button type="button" className="fb-attach-add" onClick={onAddFile}>
                <I.Paperclip className="icon" style={{ width: 12, height: 12 }} />
                Add Files
              </button>
            </div>
            <p className="fb-hint">Images (max 3), Video (max 50MB), PDF/Doc supported.</p>
          </div>

          <div className="fb-modal-footer">
            <button type="button" className="btn btn-ghost" onClick={onClose}>Cancel</button>
            <button type="submit" className="btn btn-primary" disabled={submitting || !title || !content}>
              {submitting ? 'Submitting…' : 'Submit'}
            </button>
          </div>
        </form>
      </div>
    </div>);

}

window.FeedbackPage = FeedbackPage;