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_TERMS_OF_SERVICE_MARKDOWN } from './terms-of-service.default';
import type { Location } from '../../types/api/location';

export async function TermsOfServicePage(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_TERMS_OF_SERVICE_MARKDOWN).trim(),
    placeholders
  );
  const effectiveDate = `January 1, ${placeholders.effectiveYear}`;

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

