import { Fragment } from 'react'

/**
 * The body of a legal page — «سياسة الخصوصية» and «شروط الاستخدام» are the same shape, so they are the same
 * component: a lead, numbered sections, and a closing line.
 *
 * A section's text is CMS text, not HTML. It is read exactly as somebody typed it: an empty line starts a new
 * paragraph, a line beginning with «- » is an item in a list. Nothing in it is ever treated as markup, so a
 * «<» an editor types stays a «<» on the page.
 */

type Section = { id?: string | null; title: string; text: string }

type Block = { kind: 'p'; text: string } | { kind: 'ul'; items: string[] }

/** The written text as blocks: paragraphs, and runs of «- » lines gathered into one list. */
export function blocks(text: string): Block[] {
  const out: Block[] = []
  for (const para of (text || '').split(/\n\s*\n/)) {
    const lines = para.split('\n').map((l) => l.trim()).filter(Boolean)
    let items: string[] = []
    const flush = () => {
      if (items.length) {
        out.push({ kind: 'ul', items })
        items = []
      }
    }
    for (const line of lines) {
      if (line.startsWith('- ')) {
        items.push(line.slice(2).trim())
      } else {
        flush()
        out.push({ kind: 'p', text: line })
      }
    }
    flush()
  }
  return out
}

function Prose({ text }: { text: string }) {
  return (
    <>
      {blocks(text).map((b, i) =>
        b.kind === 'p' ? (
          <p key={i}>{b.text}</p>
        ) : (
          <ul key={i}>
            {b.items.map((it, j) => (
              <li key={j}>{it}</li>
            ))}
          </ul>
        ),
      )}
    </>
  )
}

export function Legal({
  lead,
  sections,
  closing,
}: {
  lead?: string | null
  sections?: Section[] | null
  closing?: string | null
}) {
  const list = sections || []
  return (
    <section className="container">
      <div className="panel tk-legal">
        {lead ? <p className="tk-legal-lead">{lead}</p> : null}
        {list.map((s, i) => (
          <Fragment key={s.id || s.title}>
            <h2>
              <span className="tk-legal-num">{i + 1}.</span> {s.title}
            </h2>
            <Prose text={s.text} />
          </Fragment>
        ))}
        {closing ? <p className="tk-legal-closing">{closing}</p> : null}
      </div>
    </section>
  )
}
