import { useEffect, useRef, useState } from 'react'
import MindElixir, { type MindElixirInstance, type MindElixirData } from 'mind-elixir'
import 'mind-elixir/style.css'
import { IRAN_SITES } from '@/content/iranSites'
import newsData from '@/content/iranSitesNews.json'

interface NewsItem { title: string; url: string; source: string; date: string; summary: string }
const NEWS = newsData as Record<string, NewsItem[]>

const NAVY = '#032340'
const GOLD = '#CD9E53'
const norm = (s: string) => s.replace(/‌/g, '').replace(/ي/g, 'ی').replace(/ك/g, 'ک').trim()
const byTime = (a: NewsItem, b: NewsItem) => (Date.parse(b.date) || 0) - (Date.parse(a.date) || 0)
const newsCount = (id: string) => (NEWS[id] ?? []).length

// turn companies + their news into a mind-map: root → company → headline leaves
function buildTree(query: string): MindElixirData {
  const q = norm(query)
  let companies = IRAN_SITES.filter((s) => newsCount(s.id) > 0)
  if (q) {
    companies = companies.filter(
      (s) => norm(s.name.fa).includes(q) || (NEWS[s.id] ?? []).some((n) => norm(n.title + ' ' + n.summary).includes(q))
    )
  }
  const top = companies.sort((a, b) => newsCount(b.id) - newsCount(a.id)).slice(0, 12)

  return {
    direction: MindElixir.SIDE,
    theme: {
      name: 'steel',
      palette: [GOLD, '#1f6f8b', '#b3541e', '#3b82f6', '#7a5c3e', '#2f8f6b'],
      cssVar: { '--main-color': NAVY, '--main-bgcolor': '#ffffff', '--color': NAVY, '--bgcolor': '#faf7f4' },
    },
    nodeData: {
      id: 'root',
      topic: query.trim() || 'اخبار صنعت فولاد ایران',
      style: { background: NAVY, color: '#fff', fontWeight: '700' },
      children: top.map((c) => ({
        id: c.id,
        topic: c.name.fa,
        children: [...(NEWS[c.id] ?? [])].sort(byTime).slice(0, 4).map((n, i) => ({
          id: `${c.id}-${i}`,
          topic: n.title.length > 64 ? n.title.slice(0, 64) + '…' : n.title,
          hyperLink: n.url,
        })),
      })),
    },
  }
}

export default function Newstree() {
  const [query, setQuery] = useState('')
  const elRef = useRef<HTMLDivElement>(null)
  const mindRef = useRef<MindElixirInstance | null>(null)

  // init once
  useEffect(() => {
    if (!elRef.current) return
    const mind = new MindElixir({
      el: elRef.current,
      direction: MindElixir.SIDE,
      draggable: true,
      editable: false,
      contextMenu: false,
      toolBar: true,
      keypress: false,
    })
    mind.init(buildTree(''))
    // click a headline leaf → open the article
    mind.bus.addListener('selectNodes', (nodes: { hyperLink?: string }[]) => {
      const link = nodes.find((n) => n?.hyperLink)?.hyperLink
      if (link) window.open(link, '_blank', 'noopener')
    })
    mindRef.current = mind
    return () => { mindRef.current = null }
  }, [])

  const search = () => mindRef.current?.refresh(buildTree(query))

  return (
    <div style={{ position: 'fixed', inset: 0, background: '#faf7f4', direction: 'rtl', display: 'flex', flexDirection: 'column' }}>
      {/* hero / search */}
      <div style={{ flexShrink: 0, background: '#fff', borderBottom: '1px solid #eee', padding: '14px 20px', display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ width: 38, height: 38, borderRadius: 10, background: NAVY, color: GOLD, fontWeight: 900, fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>NT</span>
          <div>
            <div style={{ fontWeight: 900, fontSize: 18, color: NAVY }}>نیوزتری</div>
            <div style={{ fontSize: 11.5, color: '#888' }}>نمای درختی اخبار صنعت فولاد ایران</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1, minWidth: 240, maxWidth: 560, background: '#f4f1ec', borderRadius: 999, padding: '6px 14px' }}>
          <input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') search() }}
            placeholder="جست‌وجو در شرکت‌ها و اخبار… (مثلاً مبارکه، گل‌گهر)"
            style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 14, color: NAVY, fontFamily: 'inherit' }}
          />
          <button onClick={search} style={{ background: GOLD, color: NAVY, border: 'none', borderRadius: 999, padding: '6px 16px', fontWeight: 800, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' }}>جست‌وجو</button>
          {query && <button onClick={() => { setQuery(''); mindRef.current?.refresh(buildTree('')) }} style={{ background: 'transparent', border: 'none', color: '#999', fontSize: 18, cursor: 'pointer', lineHeight: 1 }} aria-label="پاک کردن">×</button>}
        </div>
        <div style={{ fontSize: 11.5, color: '#aaa' }}>روی هر تیتر بزنید تا مقاله باز شود</div>
      </div>

      {/* mind map */}
      <div ref={elRef} style={{ flex: 1, minHeight: 0 }} />
    </div>
  )
}
