// site-legal.jsx — Privacy, Terms, Licensing, Cookies pages.
// Rectilinear style matching the home + inner pages.

function formatTextWithLinks(text) {
  if (typeof text !== 'string') return text;
  const regex = /(https?:\/\/[^\s]+|github\.com\/[^\s]+|borderux\.com\/[^\s]+|[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}|[a-zA-Z0-9.-]+\.(?:com|org)(?:\/[^\s]*)?)/gi;
  const parts = text.split(regex);
  if (parts.length === 1) return text;
  return parts.map((part, idx) => {
    if (!part) return null;
    if (part.includes('@') && !part.startsWith('http')) {
      return (
        <a key={idx} href={`mailto:${part}`} className="legal-link">
          {part}
        </a>
      );
    }
    const isUrl = part.match(/^(https?:\/\/|[a-zA-Z0-9.-]+\.(?:com|org))/i);
    if (isUrl) {
      let href = part;
      if (!part.startsWith('http://') && !part.startsWith('https://')) {
        href = 'https://' + part;
      }
      let cleanHref = href;
      let displayText = part;
      let trailing = '';
      const trailMatch = part.match(/([.,:;!?\)]+)$/);
      if (trailMatch) {
        trailing = trailMatch[1];
        displayText = part.slice(0, -trailing.length);
        cleanHref = href.slice(0, -trailing.length);
      }
      return (
        <React.Fragment key={idx}>
          <a href={cleanHref} target="_blank" rel="noopener noreferrer" className="legal-link">
            {displayText}
          </a>
          {trailing}
        </React.Fragment>
      );
    }
    return part;
  });
}

function LegalPage({ slug }) {
  const data = (typeof window !== "undefined" && window.__BX_CONTENT && window.__BX_CONTENT[slug]) || {};
  if (!data || !data.title) return null;

  window.useSEO({
    title: data.title,
    description: data.intro
  });

  const sections = data.sections || [];

  return (
    <div className="bx-page site-page">
            <Nav />
      <div className="sp-frame">
        <PageHero
          h1={data.title}
        />

        <div className="legal-wrap">
          <aside className="legal-toc">
            <div className="lbl">Updated</div>
            <div className="updated">{data.updated}</div>
            <div className="lbl">Contents</div>
            <ul>
              {sections.map((s, i) => (
                <li key={s.h}>
                  <a href={`#${slug}-${i}`}>{(i + 1 < 10 ? '0' : '') + (i + 1)} — {s.h}</a>
                </li>
              ))}
            </ul>
          </aside>

          <article className="legal-body">
            {data.intro && (
              <p className="legal-intro">{formatTextWithLinks(data.intro)}</p>
            )}
            {sections.map((s, i) => {
              const isCookieControl = slug === "cookies" && s.h === "How to Control & Manage Cookies";
              const paragraphs = s.p || [];
              return (
                <section key={s.h} id={`${slug}-${i}`}>
                  <div className="ord">{(i + 1 < 10 ? '0' : '') + (i + 1)}</div>
                  <h2>{s.h}</h2>
                  {paragraphs.map((p, j) => {
                    if (typeof p === 'string') {
                      return <p key={j}>{formatTextWithLinks(p)}</p>;
                    }
                    if (p && p.type === 'ul') {
                      const items = p.items || [];
                      return (
                        <ul key={j}>
                          {items.map((item, idx) => (
                            <li key={idx}>{formatTextWithLinks(item)}</li>
                          ))}
                        </ul>
                      );
                    }
                    if (p && p.type === 'ol') {
                      const items = p.items || [];
                      return (
                        <ol key={j}>
                          {items.map((item, idx) => (
                            <li key={idx}>{formatTextWithLinks(item)}</li>
                          ))}
                        </ol>
                      );
                    }
                    return null;
                  })}
                  {isCookieControl && (
                    <div style={{ marginTop: "24px" }}>
                      <button 
                        className="bx-cookie-btn secondary"
                        style={{ border: "1px solid rgba(244, 236, 220, 0.2)" }}
                        onClick={() => {
                          try {
                            localStorage.removeItem('bx-cookie-consent');
                            window.location.reload();
                          } catch(e) {}
                        }}
                      >
                        Reset Cookie Preferences
                      </button>
                    </div>
                  )}
                </section>
              );
            })}
          </article>
        </div>
      </div>
      <Footer />
    </div>
  );
}

function PagePrivacy()   { return <LegalPage slug="privacy" />; }
function PageTerms()     { return <LegalPage slug="terms" />; }
function PageLicensing() { return <LegalPage slug="licensing" />; }
function PageCookies()   { return <LegalPage slug="cookies" />; }

Object.assign(window, { LegalPage, PagePrivacy, PageTerms, PageLicensing, PageCookies });
