/* global React, ReactDOM */
const { useState, useEffect } = React;

const NICHES = [
  { slug: 'pricing-watch',       name: 'Pricing Watch',           count: 12, active: true },
  { slug: 'competitor-launches', name: 'Competitor Launches',     count: 7 },
  { slug: 'customer-language',   name: 'Customer Language',       count: 23 },
  { slug: 'ai-seo-watch',        name: 'AI SEO Watch',            count: 5 },
  { slug: 'partner-news',        name: 'Partner News',            count: 31 },
  { slug: 'category-signals',    name: 'Category Signals',        count: 14 },
];

const ITEMS = [
  {
    id: 1, score: 0.94,
    src: 'competitor.com', time: '14m',
    title: 'RivalCo quietly adds a usage-based seat cap to its Pro plan',
    why: 'pricing page changed, plan language is concrete, buyer impact is clear',
    body: [
      ['p', "RivalCo's public pricing page now gates Pro teams by seat count and monthly tracked events. The copy moved from \"unlimited team usage\" to \"built for focused teams up to 12 seats.\""],
      ['p', "That gives your next sales call a clean comparison point: they are narrowing Pro while your plan can stay framed around monitored sources and briefing cadence."],
      ['h2', <>Suggested angle</>],
      ['p', <>Publish a short comparison note around <strong>predictable monitoring costs</strong>, not a feature-by-feature fight.</>],
      ['pre', `{\n  "signal": "pricing_change",\n  "competitor": "RivalCo",\n  "confidence": 0.94,\n  "suggested_action": "update battlecard"\n}`],
      ['p', 'This is queued for the morning digest and the midday update because pricing pages are inside the Pro source set.'],
      ['quote', "This is the kind of change a founder wants before the weekly pipeline review, not after a prospect brings it up."],
    ],
  },
  {
    id: 2, score: 0.91,
    src: 'reddit.com', time: '38m',
    title: 'Thread compares switching costs across three onboarding tools',
    why: 'buyer language, named alternatives, concrete objections',
  },
  {
    id: 3, score: 0.89,
    src: 'producthunt.com', time: '1h',
    title: 'New entrant launches with "done-for-you competitor monitoring"',
    why: 'positioning overlap, launch copy, early comments mention budget',
  },
  {
    id: 4, score: 0.82,
    src: 'linkedin.com', time: '2h',
    title: 'VP Marketing post gets traction for "founder-led category pages"',
    why: 'category language, tactical examples, strong comments',
  },
  {
    id: 5, score: 0.78,
    src: 'google.com/alerts', time: '3h',
    title: 'Analyst note calls out consolidation in sales-assist software',
    why: 'market framing, source is fresh, useful for newsletter angle',
  },
  {
    id: 6, score: 0.71,
    src: 'g2.com', time: '4h',
    title: 'Three reviews repeat the same complaint: "reporting is late"',
    why: 'repeated customer language, maps to your speed claim',
  },
  {
    id: 7, score: 0.68,
    src: 'news.ycombinator.com', time: '5h',
    title: '"What do you actually use for competitive intelligence?"',
    why: 'tool-discovery thread, buyer pain, alternatives named',
  },
  {
    id: 8, score: 0.63,
    src: 'company blog', time: '6h',
    title: 'Partner marketplace adds a dedicated AI workflows category',
    why: 'distribution opportunity, partner language, clear source link',
  },
];

function AppReader() {
  const [activeNiche, setActiveNiche] = useState('pricing-watch');
  const [activeItem, setActiveItem] = useState(1);
  const [starred, setStarred] = useState(new Set([3]));
  const [skipped, setSkipped] = useState(new Set());
  const [btwValue, setBtwValue] = useState('');
  const [toast, setToast] = useState(null);
  const [recentBtw, setRecentBtw] = useState(null);

  const current = ITEMS.find(i => i.id === activeItem);

  function submitBtw() {
    if (!btwValue.trim()) return;
    const notes = parseReaderNotes(btwValue);
    setRecentBtw({ text: btwValue, notes });
    setToast({ text: btwValue, notes, t: Date.now() });
    setBtwValue('');
    setTimeout(() => setToast(t => (t && Date.now() - t.t > 3000) ? null : t), 4500);
  }

  function parseReaderNotes(text) {
    const out = [];
    const t = text.toLowerCase();
    if (t.includes('less')) out.push({ k: 'less of', v: text.match(/less ([\w ]+)/i)?.[1]?.split(' ').slice(0,2).join(' ') || 'this topic' });
    if (t.includes('more')) out.push({ k: 'more of', v: text.match(/more ([\w ]+)/i)?.[1]?.split(' ').slice(0,2).join(' ') || 'this topic' });
    if (out.length === 0) out.push({ k: 'reader note', v: 'logged for next refresh' });
    return out;
  }

  function toggleStar(id) {
    setStarred(s => {
      const n = new Set(s);
      n.has(id) ? n.delete(id) : n.add(id);
      return n;
    });
  }
  function toggleSkip(id) {
    setSkipped(s => {
      const n = new Set(s);
      n.has(id) ? n.delete(id) : n.add(id);
      return n;
    });
  }

  return (
    <div className="app-shell">
      {/* SIDEBAR */}
      <aside className="app-sidebar">
        <div className="app-sidebar-head">
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <BrandMark />
            <span style={{ fontWeight: 600, fontSize: 17, letterSpacing: '-0.02em' }}>mece</span>
          </div>
          <a href="index.html" style={{
            fontFamily: 'var(--mono)', fontSize: 11,
            color: 'var(--ink-3)', letterSpacing: '0.04em',
          }}>← home</a>
        </div>

        <div className="app-side-group">
          <div className="app-side-label">your niches</div>
          {NICHES.map(n => (
            <div key={n.slug}
              className={`app-side-item ${activeNiche === n.slug ? 'active' : ''}`}
              onClick={() => setActiveNiche(n.slug)}>
              <div className="app-side-item-l">
                <span className="nd"></span>
                <span className="app-side-item-name">{n.name}</span>
              </div>
              <span className="app-side-count">{n.count}</span>
            </div>
          ))}
        </div>

        <div className="app-side-group" style={{ marginTop: 'auto', borderTop: '1px solid var(--line)' }}>
          <div className="app-side-label">views</div>
          <div className="app-side-item">
            <div className="app-side-item-l">
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M2 4l5 6 5-6" stroke="currentColor" strokeWidth="1.5" fill="none"/>
              </svg>
              Starred
            </div>
            <span className="app-side-count">{starred.size}</span>
          </div>
          <div className="app-side-item">
            <div className="app-side-item-l">
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <circle cx="7" cy="7" r="5" stroke="currentColor" strokeWidth="1.4" fill="none"/>
                <path d="M5 7h4" stroke="currentColor" strokeWidth="1.4"/>
              </svg>
              Skipped
            </div>
            <span className="app-side-count">{skipped.size}</span>
          </div>
          <div style={{
            margin: '14px 12px 4px', padding: 12,
            background: 'var(--bg)', borderRadius: 10,
            fontFamily: 'var(--mono)', fontSize: 10.5,
            color: 'var(--ink-3)', lineHeight: 1.5,
          }}>
            <div style={{ color: 'var(--ink-2)', marginBottom: 4 }}>this month</div>
            spent 2,410 / 3,000 credits<br/>
            <div style={{
              marginTop: 6, height: 4, borderRadius: 2,
              background: 'var(--line)', overflow: 'hidden',
            }}>
              <div style={{ width: '80%', height: '100%', background: 'var(--signal-deep)' }}></div>
            </div>
          </div>
        </div>
      </aside>

      {/* LIST */}
      <section className="app-list">
        <div className="app-list-head">
          <h1 className="app-list-title">
            AI Agents <em>Daily</em>
          </h1>
          <div className="app-list-sub">
            <span>updated 14m ago</span>
            <span>·</span>
            <span>{ITEMS.length} items · 23 deduped</span>
          </div>
        </div>
        <div className="app-list-items">
          {ITEMS.map(it => (
            <div key={it.id}
              className={`app-item ${activeItem === it.id ? 'active' : ''}`}
              onClick={() => setActiveItem(it.id)}>
              <div className="app-item-meta">
                <span className={`app-item-score ${it.score >= 0.9 ? 'high' : ''}`}>{it.score.toFixed(2)}</span>
                <span>{it.src}</span>
                <span>·</span>
                <span>{it.time}</span>
              </div>
              <div className="app-item-title">{it.title}</div>
              <div className="app-item-why">why: {it.why}</div>
              <div className="app-item-actions">
                <button className={`app-act-btn star ${starred.has(it.id) ? 'starred' : ''}`}
                  onClick={(e) => { e.stopPropagation(); toggleStar(it.id); }}>
                  ★ {starred.has(it.id) ? 'starred' : 'star'}
                </button>
                <button className={`app-act-btn skip ${skipped.has(it.id) ? 'skipped' : ''}`}
                  onClick={(e) => { e.stopPropagation(); toggleSkip(it.id); }}>
                  ⊘ {skipped.has(it.id) ? 'skipped' : 'skip'}
                </button>
                <button className="app-act-btn"
                  onClick={(e) => { e.stopPropagation(); }}>
                  ↗ open
                </button>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* READER */}
      <main className="app-reader">
        <div className="reader-toolbar">
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="reader-btn">← prev</button>
            <button className="reader-btn">next →</button>
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <span style={{
              fontFamily: 'var(--mono)', fontSize: 10,
              color: 'var(--ink-3)', letterSpacing: '0.04em',
              whiteSpace: 'nowrap',
            }}>usage receipt</span>
            <button className="reader-btn">details ↗</button>
          </div>
        </div>

        <div className="reader-body">
          <div className="reader-meta">
            <span>SCORE {current.score.toFixed(2)}</span>
            <span>·</span>
            <span>{current.src}</span>
            <span>·</span>
            <span>{current.time} ago</span>
          </div>
          <h1 className="reader-title">{current.title}</h1>
          <div className="reader-source">
            <span style={{
              width: 8, height: 8, borderRadius: '50%',
              background: 'var(--signal-deep)',
            }}></span>
            why this surfaced: <em style={{ fontFamily: 'var(--serif)', color: 'var(--trust)' }}>{current.why}</em>
          </div>

          <div className="reader-prose">
            {(current.body || [
              ['p', 'Full body for this item would load here. For the demo, only the top item has expanded content — click it in the list.'],
            ]).map((b, i) => {
              if (b[0] === 'p') return <p key={i}>{b[1]}</p>;
              if (b[0] === 'h2') return <h2 key={i}>{b[1]}</h2>;
              if (b[0] === 'pre') return <pre key={i}>{b[1]}</pre>;
              if (b[0] === 'quote') return <blockquote key={i}>{b[1]}</blockquote>;
              return null;
            })}
          </div>
        </div>
      </main>

      {/* /btw bar */}
      <form className="btw-bar" onSubmit={(e) => { e.preventDefault(); submitBtw(); }}>
        <span className="prefix">/btw</span>
        <input
          value={btwValue}
          onChange={(e) => setBtwValue(e.target.value)}
          placeholder="less launch chatter, more buyer language"
        />
        <button type="submit">teach →</button>
      </form>

      {toast && (
        <div className="btw-toast" key={toast.t}>
          <div style={{ color: 'var(--signal-deep)', fontSize: 11, letterSpacing: '0.06em' }}>
            ✓ READER NOTE QUEUED
          </div>
          {toast.notes.map((p, i) => (
            <div key={i} style={{ color: 'var(--ink-2)' }}>
              <span style={{ color: 'var(--trust)' }}>{p.k}</span> ← &ldquo;{p.v}&rdquo;
            </div>
          ))}
          <div style={{ color: 'var(--ink-3)', fontSize: 10, marginTop: 4 }}>
            applies to next refresh · receipt recorded
          </div>
        </div>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('app-root')).render(<AppReader />);
