import React from 'react';
import { GenericTextHero, PolicyDocumentSection } from '../../design_system/sections';
import { getCompanyInformation, getLocations } from '../../lib/server-api';
import { buildLegalPlaceholders, replaceLegalPlaceholders } from './placeholders';
import { DEFAULT_PRIVACY_POLICY_MARKDOWN } from './privacy-policy.default';
import type { Location } from '../../types/api/location';

export async function PrivacyPolicyPage(props?: { markdownOverride?: string }) {
  const markdownOverride = props?.markdownOverride;

  const [companyInformation, locationsData] = await Promise.all([getCompanyInformation(), getLocations()]);
  const locations = Array.isArray(locationsData) ? (locationsData as Location[]) : [];
  const primaryLocation = locations.find((l) => l.is_primary) ?? locations[0];

  const placeholders = buildLegalPlaceholders(
    companyInformation?.company_name,
    null,
    companyInformation?.primary_email,
    companyInformation?.primary_phone,
    primaryLocation?.email
  );

  const markdown = replaceLegalPlaceholders(
    (markdownOverride ?? DEFAULT_PRIVACY_POLICY_MARKDOWN).trim(),
    placeholders
  );
  const effectiveDate = `January 1, ${placeholders.effectiveYear}`;

  return (
    <main>
      <GenericTextHero title="Privacy Policy" subtitle={companyInformation?.company_name ?? undefined} />
      <PolicyDocumentSection title="Privacy Policy" effectiveDate={effectiveDate} content={markdown} />
    </main>
  );
}

