import { renderPublicPolicyFooter } from "../config/legal-links.js";
import { escapeHtml } from "../utils/html.js";

const navLinks = [
  ["/", "Home"],
  ["/services", "Services"],
  ["/plans", "Plans"],
  ["/mobile-app", "Mobile app"],
  ["/contact", "Contact"],
  ["/app", "Login"]
];

const serviceHighlights = [
  {
    title: "Resident OTP and profile completion",
    copy: "Residents and guards start with phone number plus OTP, then complete required profile details before protected role tools are unlocked.",
    accent: "green"
  },
  {
    title: "Visitor passes and gate scanning",
    copy: "Every scan stores the visitor, resident being visited, guard, gate, time, device, entry or exit status, vehicle details, and visit context.",
    accent: "blue"
  },
  {
    title: "Estate structure and gates",
    copy: "Estate admins can configure gates, assign guards, manage shifts, and keep gate limits aligned with the active estate plan.",
    accent: "amber"
  },
  {
    title: "Announcements and estate news",
    copy: "Admins and delegated supervisors can publish security alerts, maintenance notices, estate news, events, and service reminders by plan.",
    accent: "red"
  },
  {
    title: "Requests and complaints",
    copy: "Residents can raise security, infrastructure, estate service, and support tickets that move through assignment, response, and closure.",
    accent: "sage"
  },
  {
    title: "Plans, billing, and feature controls",
    copy: "GateWise business controls define plan names, prices, limits, discounts, CTAs, enterprise availability, and feature activation across roles and estates.",
    accent: "green"
  }
];

const services = [
  ["Visitor Access", "QR visitor passes, manual lookup, visitor approvals, check-in, checkout, denial history, vehicle details, and resident-linked visit trails."],
  ["Visitor Intelligence", "Risk color coding, reliability history, frequent visitor patterns, previous reports, denied attempts, blacklists, notes, and estate-level warnings."],
  ["Gate Operations", "Multi-gate management, guard-to-gate assignment, shift controls, gate alerts, device tracking, scan history, and daily gate activity views."],
  ["Resident App", "OTP login, required profile completion, visitor management, requests, notification history, plan visibility, and upgrade-benefit education without pricing."],
  ["Guard and Supervisor Workspaces", "Guard readiness checks, scanning access controls, incident response, resident support replies, supervisor broadcasts, and delegated messaging permissions."],
  ["Estate Admin Dashboard", "Resident and guard activation, announcements, gates, visitors, tickets, analytics, subscription status, service charge reminders, and estate settings."],
  
  ["Notifications", "Push, in-app, email, optional SMS, SOS alerts, check-in and checkout messages, request responses, estate announcements, and visitor history links."],
  ["Analytics", "Visitor statistics, guard performance, traffic analytics, risk analysis, weekly resident stats, estate engagement, heatmaps, and plan-limited exports."],
  ["Payments", "Subscription billing, payment confirmation, provider switching, webhooks, grace periods, invoices for estate admins, and service charge workflows by plan."],
  ["Compliance and Security", "Audit logs, device logs, access history, incident logs, data export controls, privacy policy links, retention rules, and data processing terms."],
  ["Demo Environment", "Approved estate prospects can test the web demo at /demo with production or local test service modes after onboarding review and payment confirmation."]
];

const roleWorkflows = [
  ["Resident", "Create visitor passes, complete profile, receive check-in and checkout alerts, review allowed visitor history, submit complaints, and see estate plan benefits."],
  ["Guard", "Use scanning only after OTP verification, complete profile, estate assignment, gate assignment, admin or supervisor approval, and active shift readiness."],
  ["Security Supervisor", "Create residents when delegated, assign gates and shifts, respond to incidents, send security broadcasts, and monitor guard readiness."],
  ["Estate Admin", "Deactivate estate users, manage gates, announcements, residents, guards, subscription visibility, feature settings, visitor intelligence, and request workflows."],
  ["Sales Admin", "Review onboarding pipeline, approved demos, estate data, subscription readiness, and client follow-up without entering private resident operations."],
  ["Platform Operations", "Business-approved controls manage plans, payment confirmation, demo approvals, audit trails, and enterprise access."]
];

const otpFlow = [
  ["Request OTP", "A resident, guard, admin, supervisor, or sales admin starts from the phone number approved for their role."],
  ["Enter OTP", "The code confirms the account owner and loads the correct estate, role, plan, and feature permissions."],
  ["Complete profile", "Residents and guards finish first name, last name, valid phone, address, estate assignment, confirmation, and role-specific fields."],
  ["Open dashboard", "The app reveals only the tools allowed by the role, estate settings, plan limits, and business feature controls."]
];

const onboardingFlow = [
  ["Submit estate details", "Full name, verified phone, verified email, estate name, location, resident count, gates, security personnel, current entry flow, and budget."],
  ["Business review", "Sales and business teams verify the estate request, confirm plan fit, and prepare the approved demo or onboarding path."],
  ["Payment confirmation", "First-time estates receive the configured trial and billing rules, then activation follows payment confirmation and business approval."],
  ["Approved demo or live app", "Approved prospects test the /demo workspace; live estates use /app for OTP login and production operations."]
];

const plans = [
  {
    name: "GateWise Starter",
    tag: "Small estates and streets",
    price: "NGN 200k/month",
    limits: ["1 gate", "1 estate admin", "2 supervisors", "4 guards", "100 residents", "400 monthly visitor passes"],
    features: ["QR visitor system", "OTP login", "Resident profiles", "Resident requests", "Basic announcements once a month", "Manual visitor lookup", "Visitor logs"],
    missing: ["Service charge payments", "Weekly visitor stats", "Estate news and events", "Visitor behavior intelligence", "SOS alerts"]
  },
  {
    name: "GateWise Secure",
    tag: "Mid-sized estates",
    price: "NGN 500k/month",
    limits: ["3 gates", "3 admins", "5 supervisors", "10 guards", "500 residents", "800 monthly visitor passes"],
    features: ["Everything in Starter", "Visitor intelligence", "Multi-gate operations", "Guard shift management", "Service charge payments", "Weekly visitor statistics", "Export reports", "1 SOS alert per month"],
    missing: ["AI visitor risk scoring", "Smart estate analytics", "Smart blacklisting", "Smart automation"]
  },
  {
    name: "GateWise Luxury",
    tag: "Recommended for large estates",
    price: "NGN 2m/month",
    limits: ["5 gates", "5 admins", "5 supervisors", "2,000 residents", "Unlimited visitor passes", "Advanced analytics"],
    features: ["Everything in Secure", "AI visitor scoring", "Risk color coding", "Visitor heatmaps", "Security heatmaps", "Audit logs", "Priority support", "5 SOS alerts per month"],
    missing: ["Smart blacklisting", "Smart automation"]
  },
  {
    name: "GateWise Business",
    tag: "Estate managers and owners",
    price: "NGN 5m/month",
    limits: ["5 managed estates", "10 gates per estate", "5,000 residents", "Unlimited visitor passes", "Advanced analytics", "AI visitor scoring"],
    features: ["Everything in Luxury", "Resident engagement analytics", "50 announcements per week", "10 SOS alerts per month per estate", "Audit trail exports", "Visitor intelligence dashboard", "Multi-estate management", "Smart incident escalation"],
    missing: ["White-label apps", "Dedicated support manager", "Smart gate integrations", "Dedicated infrastructure", "Enterprise APIs"]
  },
  {
    name: "GateWise Enterprise",
    tag: "Future custom plan",
    price: "Custom enterprise pricing",
    limits: ["Unlimited gates", "Unlimited users", "Multiple estates", "Dedicated infrastructure", "Custom workflows", "SLA guarantees"],
    features: ["Everything in Business", "White-label mobile app", "White-label web dashboard", "Custom branding", "Dedicated account manager", "Smart gate hardware integration", "API integrations", "VIP onboarding"],
    missing: []
  }
];

const mobileScreens = [
  {
    role: "Resident",
    title: "Resident home",
    items: ["Profile 100% complete", "Visitor QR access", "Check-in alert", "Plan benefits"],
    foot: "Visitors, requests, announcements, and plan visibility."
  },
  {
    role: "Guard",
    title: "Gate scanner",
    items: ["Assigned Main Gate", "Scan visitor pass", "Checkout missing", "Risk: Yellow"],
    foot: "Gate access only after profile, estate, gate, and approval checks."
  },
  {
    role: "Supervisor",
    title: "Security board",
    items: ["Guards on shift", "Gate alerts", "Resident tickets", "Incident replies"],
    foot: "Delegated broadcasts, request responses, and gate oversight."
  },
  {
    role: "Estate Admin",
    title: "Estate command",
    items: ["Send announcement", "Create gate", "Deactivate user", "Plan limits"],
    foot: "Estate-wide controls with plan-based limits and delegated messaging."
  },
  {
    role: "Business Ops",
    title: "Feature settings",
    items: ["Role toggles", "Plan features", "Plan controls", "Approved demos"],
    foot: "Central control for all roles, plans, estates, and enterprise access."
  },
  {
    role: "Visitor Intel",
    title: "Visitor profile",
    items: ["Reliability: 92%", "Visits: 14", "Risk: Green", "Notes available"],
    foot: "History, frequency, reports, restrictions, and risk scoring by plan."
  }
];

const partners = [
  ["Estate managers", "Run multiple estates, standardize gate workflows, and report resident engagement to estate owners."],
  ["Security companies", "Bring guard performance, gate accountability, incident history, and shift management into one platform."],
  ["Sales and implementation partners", "Help estates onboard, validate needs, configure plans, and guide administrators through activation."],
  ["Payment providers", "Support subscription billing, service charge payments, webhooks, provider switching, and payment confirmation."],
  ["Smart gate and hardware providers", "Future enterprise integrations can connect GateWise workflows to physical gate systems and devices."]
];

const routeAliases = {
  "/": "home",
  "/services": "services",
  "/features": "services",
  "/plans": "plans",
  "/subscriptions": "plans",
  "/subscription-plans": "plans",
  "/mobile-app": "mobile",
  "/mobile": "mobile",
  "/partners": "partners",
  "/about": "about",
  "/contact": "contact"
};

export function renderWelcomePage(app, pathname = window.location.pathname) {
  document.body.classList.add("welcome-body");
  const cleanPath = String(pathname || "/").replace(/\/+$/, "") || "/";
  const page = routeAliases[cleanPath] || "home";
  app.className = `welcome-page public-${page}-page`;
  document.title = `${pageTitle(page)} | GateWise NG`;
  app.innerHTML = `
    ${renderHeader(cleanPath)}
    <main>
      ${renderPage(page)}
    </main>
    ${renderPublicPolicyFooter()}
  `;
}

function renderHeader(pathname) {
  return `
    <header class="welcome-nav">
      <a class="welcome-brand" href="/" aria-label="GateWise NG home">
        <span class="welcome-brand-mark" aria-hidden="true">GW</span>
        <span>GateWise NG</span>
      </a>
      <nav class="welcome-links compact-links" aria-label="Public navigation">
        ${navLinks
          .map(([href, label]) => `<a href="${href}" ${href === pathname ? 'aria-current="page"' : ""}>${escapeHtml(label)}</a>`)
          .join("")}
      </nav>
    </header>
  `;
}

function renderPage(page) {
  if (page === "services") {
    return renderServicesPage();
  }
  if (page === "plans") {
    return renderPlansPage();
  }
  if (page === "mobile") {
    return renderMobilePage();
  }
  if (page === "partners") {
    return renderPartnersPage();
  }
  if (page === "about") {
    return renderAboutPage();
  }
  if (page === "contact") {
    return renderContactPage();
  }
  return renderHomePage();
}

function renderHomePage() {
  return `
    <section class="welcome-hero public-home-hero">
      <img class="welcome-hero-bg" src="assets/gatewise-public-hero.png" alt="Modern secure estate entrance with mobile visitor access">
      <div class="welcome-hero-copy">
        <p class="welcome-kicker">Smart estate visitor management</p>
        <h1>GateWise NG gives every estate a safer visitor journey.</h1>
        <p class="welcome-lead">
          GateWise connects residents, guards, supervisors, estate admins, sales teams, and businesss around one trusted flow:
          invite visitors, verify at the gate, notify the right resident, track history, respond to incidents, and keep plan limits clear.
        </p>
        <div class="welcome-actions">
          <a class="welcome-btn primary" href="/onboarding">Start estate signup</a>
          <a class="welcome-btn" href="/demo?api=prod">Open approved demo</a>
          <a class="welcome-btn" href="/app">Login to dashboard</a>
        </div>
        <dl class="welcome-proof">
          <div><dt>OTP</dt><dd>phone-first signup and role login</dd></div>
          <div><dt>Gates</dt><dd>plan-based scanning and guard assignment</dd></div>
          <div><dt>Risk</dt><dd>visitor history, flags, and color scores</dd></div>
        </dl>
      </div>
    </section>

    <section class="welcome-section public-intro-grid">
      <div>
        <p class="welcome-kicker">Complete estate workflow</p>
        <h2>From first OTP to estate-wide operations, each screen follows the real security flow.</h2>
      </div>
      <p>
        Residents and guards can sign in after their phone number is added, but protected use depends on profile completion,
        estate assignment, role approval, active plan features, and business settings. Estate admins can create gates,
        send announcements, delegate messaging, deactivate users, and control the day-to-day security operation for their estate.
      </p>
    </section>

    <section class="welcome-section">
      <div class="welcome-section-header">
        <p class="welcome-kicker">What GateWise covers</p>
        <h2>Core services across web, service, and mobile apps.</h2>
      </div>
      <div class="welcome-feature-grid expanded-grid">
        ${serviceHighlights.map(renderFeatureCard).join("")}
      </div>
      <div class="section-actions">
        <a class="welcome-btn primary" href="/services">Explore all services</a>
        <a class="welcome-btn" href="/plans">Compare subscription plans</a>
      </div>
    </section>

    <section class="welcome-band public-flow-band">
      <div>
        <p class="welcome-kicker">Role login flow</p>
        <h2>Request OTP, enter OTP, complete profile, then open the right dashboard.</h2>
        <p>
          GateWise keeps the sign-in path simple while still enforcing estate membership, profile readiness,
          gate assignment, plan limits, and feature permissions behind the scenes.
        </p>
      </div>
      <div class="flow-list">
        ${otpFlow.map(renderFlowStep).join("")}
      </div>
    </section>

    <section class="welcome-section public-split">
      <div>
        <p class="welcome-kicker">Mobile app details</p>
        <h2>Major role screens are designed for quick decisions, not clutter.</h2>
        <p>
          The mobile app covers resident visitor passes, guard scanning, supervisor response, estate announcements,
          notifications, requests, plan visibility, and demo analytics. Each role sees the features activated for the estate plan.
        </p>
        <div class="section-actions align-left">
          <a class="welcome-btn primary" href="/mobile-app">View mobile app screens</a>
          <a class="welcome-btn" href="/app">Open web dashboard</a>
        </div>
      </div>
      <div class="phone-row compact-phones">
        ${mobileScreens.slice(0, 3).map(renderPhoneMockup).join("")}
      </div>
    </section>

    <section class="welcome-section">
      <div class="welcome-section-header">
        <p class="welcome-kicker">Plan-based access</p>
        <h2>Estate plans define gates, users, announcements, notifications, visitors, analytics, and premium features.</h2>
        <p>
          Residents see the estate plan name and upgrade benefits, but never see billing, invoices, plan prices, or estate subscription costs.
        </p>
      </div>
      <div class="plan-strip">
        ${plans.slice(0, 4).map(renderPlanMiniCard).join("")}
      </div>
      <div class="section-actions">
        <a class="welcome-btn primary" href="/plans">See plan details</a>
        <a class="welcome-btn" href="/onboarding">Request onboarding</a>
      </div>
    </section>

    <section class="welcome-section public-split reverse">
      <div>
        <p class="welcome-kicker">Demo access</p>
        <h2>The current estate signup flow now lives on its own onboarding page.</h2>
        <p>
          Prospective estates submit verified details, sales and business teams approve the request, payment is confirmed,
          and then the approved team can test the production-style demo at /demo. Local testing is also available for development.
        </p>
        <div class="mode-links">
          <a href="/demo?api=prod">Approved production demo</a>
          <a href="/demo?api=local">Local approved demo</a>
          <a href="/onboarding">Estate onboarding page</a>
        </div>
      </div>
      <img src="assets/security-operations-dashboard.png" alt="GateWise web dashboard showing estate security operations">
    </section>

    <section class="welcome-section public-link-grid">
      ${renderLinkTile("Services", "Visitor access, announcements, analytics, requests, billing, notifications, and security controls.", "/services")}
      ${renderLinkTile("Legal documents", "Terms, privacy, data protection, retention, cookies, processing, and incident response policies.", "/legal")}
      ${renderLinkTile("Partners", "Estate managers, security companies, sales partners, payment providers, and smart gate partners.", "/partners")}
      ${renderLinkTile("Contact us", "Talk to sales, support, implementation, or partnership teams.", "/contact")}
    </section>
  `;
}

function renderServicesPage() {
  return `
    ${renderPageHero("GateWise Services", "Detailed security, visitor, resident, guard, estate admin, business, billing, analytics, and notification services for modern estates.", "Services link every role to one accountable estate operation.", "assets/public-estate-arrival.png")}
    <section class="welcome-section">
      <div class="service-list">
        ${services.map(([title, copy]) => renderServiceRow(title, copy)).join("")}
      </div>
    </section>
    <section class="welcome-band">
      <div>
        <p class="welcome-kicker">Service controls</p>
        <h2>Businesss can activate or deactivate features for roles, plans, selected estates, or the whole platform.</h2>
        <p>
          Feature settings are designed to support plan packaging, pilots, temporary restrictions, enterprise access, and future product expansion.
        </p>
      </div>
      <div class="settings-grid">
        ${["Role permissions", "Plan feature toggles", "Estate-specific overrides", "Announcement limits", "Visitor history visibility", "Marketing cards"].map(renderSettingPill).join("")}
      </div>
    </section>
  `;
}

function renderPlansPage() {
  return `
    ${renderPageHero("Subscription Plans and Features", "Plan packages determine gates, users, visitor volume, scans, announcements, SOS alerts, analytics, exports, imports, storage, and advanced intelligence.", "Prices are visible to estate admins and business users only; residents see features and benefits without pricing.", "assets/security-operations-dashboard.png")}
    <section class="welcome-section">
      <div class="plan-grid">
        ${plans.map(renderPlanCard).join("")}
      </div>
    </section>
    <section class="welcome-section comparison-section">
      <div class="welcome-section-header">
        <p class="welcome-kicker">Resident upgrade visibility</p>
        <h2>Residents always understand the plan their estate uses and what community benefits higher plans unlock.</h2>
      </div>
      <div class="comparison-grid">
        ${[
          ["Starter residents see", "Visitor QR access, entry notifications, estate announcements, security alerts, and missing higher-plan benefits."],
          ["Secure residents unlock", "Service charges, weekly visitor reports, estate news, maintenance requests, complaint tracking, and better notifications."],
          ["Luxury residents unlock", "AI-powered visitor safety insights, reliability tracking, smart security monitoring, heatmaps, and faster escalation."],
          ["Business residents unlock", "Advanced estate analytics, multi-estate security intelligence, smart incident escalation, and richer visitor intelligence."]
        ].map(([title, copy]) => renderFeatureCard({ title, copy, accent: "blue" })).join("")}
      </div>
    </section>
  `;
}

function renderMobilePage() {
  return `
    ${renderPageHero("GateWise Mobile App", "The mobile app brings visitor creation, QR scanning, notifications, requests, announcements, plan benefits, demo analytics, and role dashboards into residents' and security teams' hands.", "Screens below show how the major roles experience the same estate operation.", "assets/resident-pass-preview.png")}
    <section class="welcome-section">
      <div class="welcome-section-header">
        <p class="welcome-kicker">Role screenshots</p>
        <h2>Mobile screens explain the major features across roles and plans.</h2>
      </div>
      <div class="phone-gallery">
        ${mobileScreens.map(renderPhoneMockup).join("")}
      </div>
    </section>
    <section class="welcome-band">
      <div>
        <p class="welcome-kicker">Notification experience</p>
        <h2>Residents receive visitor, request, announcement, and security updates with links back to the right screen.</h2>
        <p>
          Check-in, checkout, denial, incident, SOS, request response, and estate announcement notifications are controlled by plan limits and estate settings.
        </p>
      </div>
      <div class="notification-stack">
        ${["Visitor checked in at Main Gate", "Visitor checked out successfully", "Security alert from estate admin", "Request response from supervisor"].map(renderNotification).join("")}
      </div>
    </section>
    <section class="welcome-section public-split">
      <div>
        <p class="welcome-kicker">Mobile demo</p>
        <h2>The existing demo app now includes simulated notifications, reports, and analytics for real-life walkthroughs.</h2>
        <p>
          Potential estates can review role experiences before purchase while production data, provider settings, and live estate records stay protected.
        </p>
      </div>
      <img src="assets/gate-verification.png" alt="Guard using GateWise mobile scanning at an estate gate">
    </section>
  `;
}

function renderPartnersPage() {
  return `
    ${renderPageHero("GateWise Partners", "GateWise can work with estate managers, security companies, sales partners, payment providers, and future smart gate providers.", "No public partner logos are listed yet; the partner model is ready for approved relationships.", "assets/gatewise-public-hero.png")}
    <section class="welcome-section">
      <div class="partner-grid">
        ${partners.map(([title, copy]) => renderFeatureCard({ title, copy, accent: "sage" })).join("")}
      </div>
    </section>
    <section class="welcome-section welcome-cta">
      <p class="welcome-kicker">Partner inquiry</p>
      <h2>Help estates move from informal gate processes to accountable digital access.</h2>
      <p>Implementation, sales, payment, and security partners can contact GateWise to discuss approved collaboration.</p>
      <div class="welcome-actions">
        <a class="welcome-btn primary" href="/contact">Contact partnerships</a>
        <a class="welcome-btn" href="/onboarding">Register an estate</a>
      </div>
    </section>
  `;
}

function renderAboutPage() {
  return `
    ${renderPageHero("About GateWise NG", "GateWise NG is built for Nigerian estates that need secure visitor access without forcing residents, guards, and admins into confusing manual processes.", "The product belongs to Globulus Technology Limited.", "assets/public-estate-arrival.png")}
    <section class="welcome-section public-intro-grid">
      <div>
        <p class="welcome-kicker">Why GateWise exists</p>
        <h2>Estate access should be fast for trusted visitors and accountable for security teams.</h2>
      </div>
      <p>
        Many estates still rely on phone calls, WhatsApp groups, paper logs, and informal guard memory. GateWise turns that daily pressure into a connected product:
        phone-first identity, resident-owned visitors, gate scanning, real-time notifications, requests, announcements, analytics, and plan-based governance.
      </p>
    </section>
    <section class="welcome-section">
      <div class="values-grid">
        ${[
          ["Privacy", "Residents manage their own visitors and never receive estate billing or internal admin information."],
          ["Accountability", "Scans, incidents, gates, guards, devices, approvals, notes, and audit trails stay linked to the right estate context."],
          ["Plan clarity", "Every estate knows the limits and features enabled by its subscription, and residents see community benefits without pricing."],
          ["Practical security", "Gate workflows are built for real guards, supervisors, admins, residents, and visitors moving through busy estates."]
        ].map(([title, copy]) => renderFeatureCard({ title, copy, accent: "amber" })).join("")}
      </div>
    </section>
  `;
}

function renderContactPage() {
  return `
    ${renderPageHero("Contact GateWise", "Talk to the team about estate onboarding, demos, sales, implementation, support, and partnerships.", "Use the channels below to reach the right GateWise team.", "assets/security-operations-dashboard.png")}
    <section class="welcome-section contact-layout">
      <div class="contact-list">
        ${[
          ["Sales", "sales@gatewise.ng", "Estate signup, plan fit, subscriptions, and demo approvals."],
          ["Support", "support@gatewise.ng", "Resident, guard, supervisor, and admin support."],
          ["Partners", "partners@gatewise.ng", "Implementation, sales, security, payment, and smart gate partnerships."],
          ["Legal", "legal@gatewise.ng", "Privacy, data protection, processing, retention, and policy questions."]
        ].map(renderContactCard).join("")}
      </div>
      <form class="contact-form" action="mailto:sales@gatewise.ng" method="post" enctype="text/plain">
        <p class="welcome-kicker">Send a message</p>
        <h2>Tell us what you want to set up.</h2>
        <label>
          Full name
          <input name="fullName" required>
        </label>
        <label>
          Email address
          <input name="email" type="email" required>
        </label>
        <label>
          Estate or company
          <input name="estateOrCompany" required>
        </label>
        <label>
          Message
          <textarea name="message" required>We want to evaluate GateWise for our estate.</textarea>
        </label>
        <button class="welcome-btn primary" type="submit">Send email</button>
      </form>
    </section>
  `;
}

function renderPageHero(title, lead, kicker, image) {
  return `
    <section class="public-page-hero">
      <div>
        <p class="welcome-kicker">${escapeHtml(kicker)}</p>
        <h1>${escapeHtml(title)}</h1>
        <p>${escapeHtml(lead)}</p>
        <div class="welcome-actions">
          <a class="welcome-btn primary" href="/onboarding">Start estate signup</a>
          <a class="welcome-btn" href="/app">Login</a>
        </div>
      </div>
      <img src="${escapeHtml(image)}" alt="${escapeHtml(title)} visual">
    </section>
  `;
}

function renderFeatureCard(feature) {
  return `
    <article class="welcome-feature-card accent-${escapeHtml(feature.accent || "green")}">
      <h3>${escapeHtml(feature.title)}</h3>
      <p>${escapeHtml(feature.copy)}</p>
    </article>
  `;
}

function renderServiceRow(title, copy) {
  return `
    <article class="service-row">
      <strong>${escapeHtml(title)}</strong>
      <p>${escapeHtml(copy)}</p>
    </article>
  `;
}

function renderFlowStep([title, copy], index) {
  return `
    <article class="flow-step">
      <span>${index + 1}</span>
      <div>
        <strong>${escapeHtml(title)}</strong>
        <p>${escapeHtml(copy)}</p>
      </div>
    </article>
  `;
}

function renderPlanMiniCard(plan) {
  return `
    <article class="plan-mini-card">
      <strong>${escapeHtml(plan.name)}</strong>
      <span>${escapeHtml(plan.tag)}</span>
      <small>${escapeHtml(plan.limits.slice(0, 3).join(" | "))}</small>
    </article>
  `;
}

function renderPlanCard(plan) {
  return `
    <article class="plan-card ${plan.name.includes("Luxury") ? "recommended-plan" : ""}">
      <div class="plan-card-head">
        <span>${escapeHtml(plan.tag)}</span>
        <h2>${escapeHtml(plan.name)}</h2>
        <strong>${escapeHtml(plan.price)}</strong>
      </div>
      <section>
        <h3>Limits</h3>
        ${renderList(plan.limits)}
      </section>
      <section>
        <h3>Features</h3>
        ${renderList(plan.features)}
      </section>
      ${plan.missing.length ? `<section><h3>Resident upgrade prompts</h3>${renderList(plan.missing)}</section>` : ""}
    </article>
  `;
}

function renderList(items) {
  return `<ul>${items.map((item) => `<li>${escapeHtml(item)}</li>`).join("")}</ul>`;
}

function renderPhoneMockup(screen) {
  return `
    <article class="phone-mockup" aria-label="${escapeHtml(screen.role)} mobile screen preview">
      <div class="phone-top"><span></span><strong>${escapeHtml(screen.role)}</strong><span></span></div>
      <div class="phone-screen">
        <small>${escapeHtml(screen.title)}</small>
        ${screen.items.map((item) => `<div class="phone-row-item">${escapeHtml(item)}</div>`).join("")}
      </div>
      <p>${escapeHtml(screen.foot)}</p>
    </article>
  `;
}

function renderLinkTile(title, copy, href) {
  return `
    <a class="link-tile" href="${escapeHtml(href)}">
      <strong>${escapeHtml(title)}</strong>
      <span>${escapeHtml(copy)}</span>
    </a>
  `;
}

function renderSettingPill(label) {
  return `<span>${escapeHtml(label)}</span>`;
}

function renderNotification(message) {
  return `
    <article>
      <strong>${escapeHtml(message)}</strong>
      <span>Tap to open the related GateWise screen.</span>
    </article>
  `;
}

function renderContactCard([team, email, copy]) {
  return `
    <article class="contact-card">
      <strong>${escapeHtml(team)}</strong>
      <a href="mailto:${escapeHtml(email)}">${escapeHtml(email)}</a>
      <p>${escapeHtml(copy)}</p>
    </article>
  `;
}

function pageTitle(page) {
  const titles = {
    home: "Smart Estate Visitor Management",
    services: "Services",
    plans: "Plans and Features",
    mobile: "Mobile App",
    partners: "Partners",
    about: "About",
    contact: "Contact"
  };
  return titles[page] || titles.home;
}