import type { AdminState, LegalPage } from "@/lib/mpc-types";

export type PublicLegalPage = LegalPage & { href: string };

const PRIVACY_BODY = `## 1. Who operates this website
Marloth Park Central (MPC) is an independent visitor-information and local-discovery platform operated by John Pienaar under the trading name Marloth Park Central. MPC is based in Marloth Park, Mpumalanga, South Africa. Contact MPC at contact@marlothparkcentral.com or through the public contact page.

MPC is not SANParks, a park authority, a travel agency, an accommodation provider, an emergency service, a payment processor or a financial-services provider.

## 2. Information MPC may collect
MPC may collect information that a visitor, customer, supplier or listing applicant submits directly. This can include a name, email address, phone or WhatsApp number, travel dates, accommodation preferences, enquiry details, guide or product requested, supplier information, consent confirmations, payment or delivery references, and communications needed to answer or fulfil the request.

MPC may also receive ordinary technical information such as IP address, browser type, device type, referring page, viewed pages, approximate location derived from network information, cookie choices and interaction events used for security, analytics and service improvement.

## 3. Why information is used
MPC uses information to:
- answer visitor and supplier enquiries;
- provide requested guides, route notes, downloads or access links;
- route accommodation and local-service enquiries;
- maintain listings and verify requested changes;
- process and reconcile payments when payment processing is enabled;
- provide delivery, refund and account support;
- prevent abuse, fraud and security incidents;
- maintain records required for accounting, disputes and legal compliance; and
- improve the accuracy and usability of the website.

## 4. Payments and card information
MPC does not collect or store full payment-card numbers, card security codes or online-banking credentials on this website. When an external payment provider is enabled, payment details are entered on that provider's hosted or secured payment interface and are handled under the provider's own privacy and security terms.

MPC may receive limited transaction information such as payer name, email address, payment status, amount, currency, provider transaction reference, refund status and fraud-review outcome. MPC uses that information only for reconciliation, fulfilment, support, refunds, disputes and lawful record keeping.

## 5. Voluntary value payments
Where MPC offers an optional value-payment feature, the visitor may choose to make a voluntary commercial support payment after using free information. The payment is optional, does not unlock public information, is not a charitable donation and does not create eligibility for a tax-deductible receipt.

## 6. Enquiries routed to third parties
When a visitor contacts a listed accommodation provider, activity operator, restaurant, local service or other supplier, that supplier is responsible for its own communication, prices, availability, payments, fulfilment, cancellations, refunds, safety, customer service, privacy practices and legal compliance.

MPC may send the information necessary to the selected supplier when the visitor asks MPC to route an enquiry. MPC does not sell visitor contact information.

## 7. Service providers
MPC may use trusted service providers for hosting, email delivery, website security, analytics, backups, administration and payment processing. Those providers may process only the information needed to provide their service and are subject to their own legal and security obligations.

## 8. Cookies and analytics
MPC may use essential cookies and limited analytics technologies to keep the site secure, remember preferences, understand page performance and improve visitor journeys. Non-essential analytics or advertising technologies should operate only where permitted by the visitor's consent choices and applicable law.

Browser settings can be used to block or delete cookies, but some site functions may then work differently.

## 9. Communications
MPC may send transactional messages about an enquiry, guide request, download, listing application, payment, delivery, refund or support issue. MPC may send non-essential updates only where the recipient has consented or where another lawful basis applies.

A recipient can ask MPC to stop non-essential communications at any time. Transactional messages needed to complete or document an existing request may still be sent.

## 10. Security
MPC uses reasonable technical and organisational safeguards, including encrypted website connections, access controls, restricted administrative routes, security headers, validation of submitted data, backups and operational monitoring. No internet service can guarantee absolute security.

Visitors should not send card details, passwords, identity-document numbers or other unnecessary sensitive information through ordinary contact forms, email or WhatsApp.

## 11. Retention
MPC retains information only for as long as reasonably needed for enquiry handling, delivery, support, accounting, fraud prevention, dispute handling, supplier management, reporting, legal protection and website administration. Records are deleted, anonymised or restricted when they are no longer required.

## 12. Access, correction and deletion requests
A person may contact MPC to request access to, correction of or deletion of personal information held about them, subject to identity verification and lawful retention requirements. Requests should identify the email address or phone number used for the relevant interaction.

## 13. Children
MPC visitor information may be useful to families, but payment and enquiry forms are intended for adults. Children should not submit personal information or make payments without the involvement of a parent or legal guardian.

## 14. External links
MPC may link to park resources, maps, suppliers, accommodation providers, payment providers, social platforms or other external websites. MPC is not responsible for the privacy, security, accuracy or content of third-party websites.

## 15. Changes to this policy
MPC may update this Privacy Policy when the platform, services, payment arrangements, supplier model, analytics tools or legal requirements change. The version and update date shown on this page identify the current published policy.

## 16. Contact
Privacy questions and data requests can be sent to contact@marlothparkcentral.com or submitted through the MPC contact page.`;

const TERMS_BODY = `## 1. Acceptance
These Terms of Use apply to marlothparkcentral.com and the visitor-information, local-discovery, enquiry-routing, digital-guide and related services provided by Marloth Park Central (MPC). By using the website, submitting an enquiry, requesting a product or making a payment, you agree to these terms and the linked Privacy Policy and Delivery & Refund Policy.

## 2. Operator and independent status
MPC is operated by John Pienaar under the trading name Marloth Park Central from Marloth Park, Mpumalanga, South Africa.

MPC is an independent platform. It is not SANParks, a park authority, a travel agency, a booking agent, an emergency service, an accommodation provider, an activity operator, a restaurant, a delivery provider, a transport provider, a payment processor, a financial-services provider or an insurer.

## 3. Planning information
MPC content is general visitor-planning guidance. It does not replace current park rules, official notices, road signs, gate times, weather alerts, emergency instructions, supplier confirmations, medical advice or common-sense safety decisions.

Visitors remain responsible for checking current information and for their own travel documents, bookings, driving, route timing, vehicle readiness, health needs, child supervision, safety decisions and compliance with applicable rules.

## 4. Accuracy and changes
MPC works to keep information useful and current, but local conditions, prices, routes, supplier details, regulations and operating hours can change without notice. MPC may correct, update, reorganise or remove content at any time.

## 5. Free information and digital products
MPC may provide free public information, free downloadable resources and paid digital planning products. Product pages describe what is included, the displayed price, the transaction currency, the delivery method and any specific conditions.

A request form does not itself charge a payment card. Where online payment processing is enabled, the customer is shown the amount, currency and provider before confirming payment.

## 6. Voluntary value payments
MPC may invite a visitor who found free information useful to make an optional value payment. Such a payment:
- is voluntary and is not required to access public information;
- is a commercial support payment and not a charitable donation;
- does not create a tax-deductible donation receipt;
- does not purchase influence over editorial content or supplier placement; and
- is governed by the Delivery & Refund Policy and the payment provider's terms.

## 7. Delivery, cancellations and refunds
Delivery timing, access support, duplicate-payment handling, cancellation rights and refund rules are set out in the Delivery & Refund Policy. That policy forms part of these terms.

MPC does not collect or store full card details. External payment providers may apply their own verification, fraud-review, currency-conversion, dispute and account terms.

## 8. Accommodation enquiries
Accommodation pages and enquiry forms help visitors request information or availability. Unless MPC expressly states otherwise in writing, submitting an enquiry is not a confirmed booking, accepted quote, payment confirmation or reservation.

The accommodation provider is responsible for final rates, availability, deposits, cancellations, refunds, house rules, safety, service quality and legal compliance.

## 9. Local listings and suppliers
MPC may display local businesses, restaurants, activities, accommodation and practical services for visitor discovery. Unless a separate written agreement says otherwise, visitors deal directly with the listed supplier.

The supplier remains responsible for its prices, availability, licensing, communication, payments, delivery, fulfilment, cancellations, refunds, safety, service quality and legal compliance. A listing, featured position or verification label is not a guarantee of outcome.

## 10. User submissions
A person submitting an enquiry, review request, listing application, image, description or other content confirms that the information is accurate, lawful and authorised. The person must not submit malicious code, unlawful material, misleading claims, private information they have no right to disclose or content that infringes another person's rights.

## 11. Intellectual property
Unless otherwise stated, MPC website copy, layouts, original graphics, guides, route notes, checklists, branding and downloadable resources are owned by or licensed to MPC. They may be used for personal visitor planning but may not be resold, republished, scraped in bulk, rebranded or commercially redistributed without written permission.

## 12. Acceptable use
Users may not attempt to bypass access controls, interfere with the website, probe private systems, automate abusive requests, impersonate another person, misuse supplier or visitor data, submit fraudulent payment information, initiate knowingly false disputes or use MPC for unlawful activity.

## 13. External services and links
MPC may link to maps, official resources, suppliers, social platforms and payment providers. External services are governed by their own terms and remain responsible for their systems, information and transactions.

## 14. Availability
MPC may suspend or restrict parts of the website for maintenance, security, provider outages, legal compliance or operational reasons. MPC does not guarantee uninterrupted availability.

## 15. Liability
To the fullest extent allowed by law, MPC is not liable for indirect or consequential loss arising from general planning information, changed local conditions, third-party actions, missed gate times, supplier disputes, travel disruption, wildlife incidents, road conditions or decisions made without checking current authoritative information.

Nothing in these terms excludes liability that cannot lawfully be excluded.

## 16. Governing law
These terms are governed by the laws of South Africa. Any dispute should first be raised with MPC through the public contact route so that a practical resolution can be attempted.

## 17. Changes
MPC may update these terms as the platform, products, payment arrangements and supplier model evolve. The version and update date shown on this page identify the current published terms.

## 18. Contact
Questions about these terms can be sent to contact@marlothparkcentral.com or submitted through the MPC contact page.`;

const SUPPLIER_BODY = `## 1. Scope
These Business Listing Terms apply to suppliers, restaurants, activity providers, practical-service providers, accommodation contacts and other businesses that request, receive or maintain visibility on Marloth Park Central (MPC).

## 2. MPC's role
MPC provides listing visibility, visitor discovery, category placement, direct-contact routing, lead tracking and general platform exposure. MPC does not become the supplier, operator, employer, booking agent, payment collector, delivery provider or customer-service department for a listed business unless a separate written agreement expressly says otherwise.

## 3. Supplier responsibility
Each listed business is responsible for its own service quality, prices, availability, operating hours, licences, insurance, safety requirements, legal compliance, staff behaviour, customer communication, payments, delivery, fulfilment, cancellations, refunds and complaints.

## 4. Accurate listing information
Businesses must provide accurate, current and lawful information, including the business name, category, description, service area, contact details, operating notes, delivery or collection terms, pricing notes, images and verification information where requested.

A business must promptly notify MPC when important details change, including ownership or management, contact numbers, operating hours, service availability, pricing approach, delivery area, temporary closure or safety restrictions.

## 5. Verification and editorial control
MPC may verify submitted information before publication and may request reasonable evidence that the applicant is authorised to represent the business. MPC controls the public wording, layout, category, ordering, labels and images used on the platform.

MPC may correct formatting, shorten descriptions, remove unsupported claims and decline content that is unsafe, misleading, unlawful or inconsistent with the platform.

## 6. Visitor contact and leads
A listing does not guarantee enquiries, calls, bookings, sales or a particular search position. Visitors choose whether to contact a listed business.

The business must respond professionally and must not misuse, sell, spam or disclose visitor contact details obtained through MPC. Visitor details may be used only to answer the relevant enquiry or provide the requested service, subject to applicable privacy and communications law.

## 7. Payments, bookings and refunds
Unless MPC and the business have a separate written payment arrangement, the business handles its own quotes, invoices, deposits, customer payments, delivery fees, bookings, refunds, cancellations and disputes directly with the visitor.

A business must not imply that MPC is collecting payment, confirming a booking, delivering the service or providing a refund unless MPC has expressly agreed to that role in writing.

## 8. Images, logos and content rights
By providing images, logos, descriptions or other listing content, the business confirms that it owns the content or has permission to use it. The business grants MPC permission to display, crop, resize, compress and edit that content for listing and related promotional purposes.

The business must not provide copyrighted, misleading, unsafe, offensive or unauthorised content.

## 9. Listing packages and fees
MPC may offer free, paid, featured, reviewed, partner or promotional listing options. Package names, prices, placement rules, reporting, renewal dates and included features may change.

A paid listing fee purchases the agreed visibility and listing features only. It does not guarantee a number of leads, bookings, calls, clicks, sales or customer outcomes.

## 10. Labels and disclosures
Featured, reviewed, partner, sponsored or similar labels describe the listing status configured by MPC at that time. They may reflect package level, placement eligibility, verification checks, editorial selection or a commercial relationship. MPC will use reasonable disclosures where a placement is paid or sponsored.

## 11. Prohibited conduct
Businesses may not use MPC to mislead visitors, impersonate another business, imply park-authority status, misrepresent credentials, publish unauthorised images, misuse visitor data, spam visitors, pressure visitors unfairly, sell unlawful services or damage the security or reputation of MPC.

## 12. Complaints and disputes
If MPC receives a complaint, it may request a response from the business, pause the listing, update wording, remove contact buttons or remove the listing. MPC is not required to mediate every supplier dispute; the business remains responsible for resolving customer issues directly.

## 13. Suspension and removal
MPC may suspend, hide or remove a listing for safety, legal, verification, accuracy, non-payment, repeated complaints, poor response behaviour, misleading claims, brand risk or operational reasons.

## 14. No exclusivity
Unless a separate written agreement states otherwise, listings are non-exclusive. MPC may list multiple businesses in the same category and decide how listings are organised.

## 15. Changes
MPC may update these Business Listing Terms as the directory, supplier model, reporting and packages evolve. The current published version applies from its stated update date.

## 16. Contact
Supplier questions, corrections and removal requests can be sent to contact@marlothparkcentral.com or submitted through the business contact route.`;

const DELIVERY_BODY = `## 1. Scope
This Delivery & Refund Policy applies to digital visitor guides, printable planning bundles, route notes, checklists, downloadable files, secure access links and voluntary value payments provided by Marloth Park Central (MPC).

It does not govern accommodation, activities, restaurant orders, deliveries or services supplied directly by third-party businesses listed on MPC.

## 2. Seller and contact details
The seller is John Pienaar, trading as Marloth Park Central, Marloth Park, Mpumalanga, South Africa. Support is available at contact@marlothparkcentral.com and through the public contact page.

## 3. Prices and currency
Product pages state the price and currency before a customer submits or confirms an order. Unless another currency is clearly shown, prices are displayed in South African rand (ZAR). An external payment provider may apply currency conversion or other charges under its own terms.

## 4. Request forms and payment
Submitting a planning-pack or route-guide request does not itself charge a card. MPC may respond with product availability, delivery details and an approved payment method.

When online checkout is enabled, the payment provider shows the final amount and transaction currency before confirmation. MPC does not collect or store full card details, card security codes or online-banking credentials.

## 5. Digital delivery
Unless the relevant product page states otherwise, paid digital products are delivered by email, secure access link or downloadable file within 24 hours after cleared payment and successful order matching.

Delivery depends on the customer supplying a correct email address, the payment being confirmed, the product being available and the receiving email service accepting the message.

## 6. Delivery problems
A customer who has not received a digital product within the stated delivery period should check spam, junk and promotions folders, then contact MPC using the same email address used for the order. The customer should provide their name, product title, approximate order time and available payment reference.

MPC will verify the order and resend the file or issue a replacement access link where appropriate.

## 7. Wrong email address
A customer who supplied an incorrect email address should contact MPC promptly. MPC will redirect delivery after the order and identity can be reasonably verified and where doing so does not expose another person's information or access.

## 8. Cancellation before delivery
A customer may request cancellation before MPC has sent, released or made the digital product available. Where payment has already been received and the product has not been delivered, MPC will refund the transaction to the original payment method where technically possible.

## 9. Refunds after digital delivery
Digital products can be viewed, saved, printed, copied or forwarded once access is delivered. Refunds are therefore generally not available after the correct product or access link has been supplied.

MPC will still provide a replacement, correction or appropriate refund where the wrong product was delivered, the file is materially defective, access cannot be restored, the payment was duplicated or applicable law requires another remedy.

## 10. Voluntary value payments
A voluntary value payment is optional and does not purchase access to public information. A payer may request a refund within seven calendar days of the transaction by contacting MPC with the payer name, email address, amount, currency and payment reference.

MPC will ordinarily refund the full transaction amount to the original payment method where the transaction can be verified and has not already been reversed, disputed or refunded. External provider and currency-conversion timing may affect when the refund appears.

## 11. Duplicate payments
If the same customer is charged more than once for the same intended transaction, MPC will verify the records and refund the duplicate payment or, only with the customer's agreement, apply it to another product.

## 12. Failed, pending or reviewed payments
A failed, pending, reversed, disputed or provider-reviewed payment does not count as cleared payment. Delivery may be delayed until the provider confirms the transaction. MPC cannot override an external provider's fraud, compliance or account review.

## 13. Product unavailable or MPC unable to deliver
If MPC cannot deliver a paid product within the promised period, MPC will contact the customer and offer a revised delivery time, a suitable replacement accepted by the customer or a refund.

## 14. Chargebacks and disputes
Customers should contact MPC first so that delivery, access or refund issues can be resolved quickly. If a payment dispute or chargeback is opened, MPC may provide the payment provider with order records, delivery records, access records, communications and the applicable policy version.

## 15. Third-party suppliers
Each listed accommodation provider, activity operator, restaurant, delivery service or local business is responsible for its own terms, payments, cancellations, refunds, delivery, fulfilment and customer service. MPC cannot issue a refund for money paid directly to another supplier.

## 16. How refunds are returned
Approved refunds are returned through the original payment method where technically possible. Processing time is controlled partly by the payment provider and the customer's financial institution.

## 17. Contact
For delivery, cancellation, refund or access support, contact contact@marlothparkcentral.com or use the public contact page. Include the name and email used for the transaction, product title, approximate transaction time and available reference.`;

export const legalFallbackPages: Record<string, Omit<LegalPage, "slug">> = {
  privacy: {
    title: "Privacy Policy",
    body: PRIVACY_BODY,
    version: "2.0",
    lastUpdated: "2026-07-10",
    published: true,
  },
  terms: {
    title: "Terms of Use",
    body: TERMS_BODY,
    version: "2.0",
    lastUpdated: "2026-07-10",
    published: true,
  },
  "supplier-terms": {
    title: "Business Listing Terms",
    body: SUPPLIER_BODY,
    version: "2.0",
    lastUpdated: "2026-07-10",
    published: true,
  },
  "delivery-refunds": {
    title: "Delivery & Refund Policy",
    body: DELIVERY_BODY,
    version: "2.0",
    lastUpdated: "2026-07-10",
    published: true,
  },
};

export function legalHref(slug: string) {
  if (slug === "privacy") return "/privacy";
  if (slug === "terms") return "/terms";
  if (slug === "supplier-terms") return "/supplier-terms";
  if (slug === "delivery-refunds") return "/delivery-refunds";
  return `/legal/${encodeURIComponent(slug)}`;
}

export function legalSummary(body: string) {
  const compact = body.replace(/^##\s+/gm, "").replace(/\s+/g, " ").trim();
  return compact.length > 190 ? `${compact.slice(0, 190).trim()}…` : compact;
}

function dateValue(value?: string) {
  if (!value) return 0;
  const parsed = Date.parse(value);
  return Number.isFinite(parsed) ? parsed : 0;
}

function newestCoreLegalPage(adminPage: LegalPage | undefined, fallback: LegalPage | undefined) {
  if (adminPage && !adminPage.published) return null;
  if (!fallback) return adminPage && adminPage.published ? adminPage : null;
  if (!adminPage) return fallback;

  const adminDate = dateValue(adminPage.lastUpdated);
  const fallbackDate = dateValue(fallback.lastUpdated);

  if (adminDate > fallbackDate) return adminPage;
  if (adminDate === fallbackDate && adminPage.body.length > fallback.body.length) return adminPage;
  return fallback;
}

export function getLegalPageForRoute(state: AdminState, slug: string): LegalPage | null {
  const fallback = legalFallbackPages[slug] ? { slug, ...legalFallbackPages[slug] } : undefined;
  const adminPage = state.legalPages.find((item) => item.slug === slug);
  return newestCoreLegalPage(adminPage, fallback);
}

export function getPublishedLegalPages(state: AdminState): PublicLegalPage[] {
  const bySlug = new Map<string, LegalPage>();

  Object.entries(legalFallbackPages).forEach(([slug, page]) => {
    bySlug.set(slug, { slug, ...page });
  });

  state.legalPages.forEach((page) => {
    const current = bySlug.get(page.slug);
    const resolved = newestCoreLegalPage(page, current);
    if (resolved && resolved.published) bySlug.set(page.slug, resolved);
    if (!resolved && bySlug.has(page.slug)) bySlug.delete(page.slug);
  });

  return [...bySlug.values()]
    .filter((page) => page.published)
    .sort((a, b) => {
      const order = ["privacy", "terms", "delivery-refunds", "supplier-terms"];
      const ai = order.indexOf(a.slug);
      const bi = order.indexOf(b.slug);
      if (ai !== -1 || bi !== -1) return (ai === -1 ? 99 : ai) - (bi === -1 ? 99 : bi);
      return a.title.localeCompare(b.title);
    })
    .map((page) => ({ ...page, href: legalHref(page.slug) }));
}
