import { useEffect, useMemo, useState } from 'react'
import './schoolPolicy.css'

const FA_POLICY_LINK_ID = 'school-policy-font-awesome'

function useFontAwesomeLink() {
  useEffect(() => {
    if (document.getElementById(FA_POLICY_LINK_ID)) return
    const l = document.createElement('link')
    l.id = FA_POLICY_LINK_ID
    l.rel = 'stylesheet'
    l.href = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css'
    document.head.appendChild(l)
    return () => {
      document.getElementById(FA_POLICY_LINK_ID)?.remove()
    }
  }, [])
}

type Sub = { title?: string; body: string }

type Section = {
  heading?: string
  subsections: Sub[] | { title?: string; body: string }
}

type PolicyPayload = {
  title: string
  sections: Section[]
}

function fixAssetUrls(html: string): string {
  return html.replace(/\/assets\/images\//g, '/images/')
}

function normalizeSubsections(raw: Section['subsections']): Sub[] {
  if (Array.isArray(raw)) {
    return raw.map((s) => ({
      title: typeof s.title === 'string' ? s.title : undefined,
      body: String(s.body ?? ''),
    }))
  }
  if (raw && typeof raw === 'object' && 'body' in raw) {
    return [
      {
        title: typeof raw.title === 'string' ? raw.title : undefined,
        body: String((raw as { body?: unknown }).body ?? ''),
      },
    ]
  }
  return []
}

export function SchoolPolicyPage() {
  useFontAwesomeLink()
  const [data, setData] = useState<PolicyPayload | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [mobileNavOpen, setMobileNavOpen] = useState(false)
  const [activeId, setActiveId] = useState<string | null>(null)

  useEffect(() => {
    fetch('/policy/school-policy-content.json')
      .then((r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`)
        return r.json()
      })
      .then((j: PolicyPayload) => setData(j))
      .catch(() => setError('Could not load school policy content.'))
  }, [])

  const navEntries = useMemo(() => {
    if (!data?.sections) return []
    return data.sections
      .map((sec, index) => ({ sec, index }))
      .filter(({ sec }) => Boolean(sec.heading && String(sec.heading).trim()))
      .map(({ sec, index }) => ({
        id: `section-${index}`,
        label: String(sec.heading),
      }))
  }, [data])

  useEffect(() => {
    const sections = document.querySelectorAll('.policy-content .section')
    function onScroll() {
      const scrollY = window.scrollY + 120
      let current: string | null = null
      sections.forEach((el) => {
        const top = (el as HTMLElement).offsetTop
        const h = (el as HTMLElement).offsetHeight
        if (scrollY >= top && scrollY < top + h) {
          current = el.id
        }
      })
      setActiveId(current)
    }
    window.addEventListener('scroll', onScroll, { passive: true })
    onScroll()
    return () => window.removeEventListener('scroll', onScroll)
  }, [data])

  function scrollToId(id: string) {
    const el = document.getElementById(id)
    if (el) {
      window.scrollTo({ top: el.offsetTop - 20, behavior: 'smooth' })
    }
    setMobileNavOpen(false)
  }

  return (
    <>
      <header className="header">
        <div className="header-content">
          <div className="logo-container">
            <i className="fas fa-school logo" aria-hidden />
            <div className="school-name">Al Rahma Sunday School</div>
          </div>
          <div className="header-info">
            <i className="fas fa-calendar-alt" aria-hidden /> Last updated: 09-01-2025
          </div>
        </div>
      </header>

      <nav className={`policy-nav ${mobileNavOpen ? 'active' : ''}`} id="policyNav">
        <button type="button" className="nav-close" id="navClose" onClick={() => setMobileNavOpen(false)}>
          ×
        </button>
        <div className="nav-title">
          <i className="fas fa-list" aria-hidden /> Sections
        </div>
        <ul>
          {navEntries.map((n) => (
            <li key={n.id}>
              <a
                href={`#${n.id}`}
                className={activeId === n.id ? 'active' : ''}
                onClick={(e) => {
                  e.preventDefault()
                  scrollToId(n.id)
                }}
              >
                <i className="fas fa-chevron-right" aria-hidden /> {n.label}
              </a>
            </li>
          ))}
        </ul>
      </nav>

      <div className="main-container">
        <button
          type="button"
          className="mobile-nav-toggle"
          onClick={() => setMobileNavOpen((o) => !o)}
        >
          <i className={`fas ${mobileNavOpen ? 'fa-times' : 'fa-bars'}`} aria-hidden /> Policy Sections
        </button>

        <nav className="policy-nav desktop-nav" id="desktopNav">
          <div className="nav-title">
            <i className="fas fa-list" aria-hidden /> Sections
          </div>
          <ul>
            {navEntries.map((n) => (
              <li key={`d-${n.id}`}>
                <a
                  href={`#${n.id}`}
                  className={activeId === n.id ? 'active' : ''}
                  onClick={(e) => {
                    e.preventDefault()
                    scrollToId(n.id)
                  }}
                >
                  <i className="fas fa-chevron-right" aria-hidden /> {n.label}
                </a>
              </li>
            ))}
          </ul>
        </nav>

        <div className="policy-content">
          {error ? <div className="alert alert-danger m-3">{error}</div> : null}
          {!data && !error ? <div className="p-4 text-center text-muted">Loading policy…</div> : null}

          {data ? (
            <>
              <div className="policy-header">
                <h1>{data.title}</h1>
                <p className="last-updated">Effective from: 09-01-2025</p>
              </div>

              {data.sections.map((section, sectionIndex) => {
                const subs = normalizeSubsections(section.subsections)
                const sectionId = `section-${sectionIndex}`
                return (
                  <section key={sectionId} id={sectionId} className="section">
                    {section.heading ? (
                      <h2>
                        <i className="fas fa-info-circle" aria-hidden /> {section.heading}
                      </h2>
                    ) : null}
                    {subs.map((sub, i) => (
                      <div key={i}>
                        {sub.title ? (
                          <h3>
                            <i className="fas fa-angle-right" aria-hidden /> {sub.title}
                          </h3>
                        ) : null}
                        {sub.body ? (
                          <div
                            className="policy-body"
                            dangerouslySetInnerHTML={{ __html: fixAssetUrls(sub.body) }}
                          />
                        ) : null}
                      </div>
                    ))}
                  </section>
                )
              })}

              <div className="actions-container">
                <button type="button" className="action-btn print" onClick={() => window.print()}>
                  <i className="fas fa-print" aria-hidden /> Print
                </button>
              </div>
            </>
          ) : null}
        </div>
      </div>

      <footer className="footer">
        <p>© 2026 Al Rahma Sunday School by ISGL. All Rights Reserved.</p>
        <p>ISGL, Chelmsford MA • +1 978-364-0219 • alrahma.isgl@gmail.com</p>
      </footer>
    </>
  )
}
