import Navbar from '@/components/Navbar';
import Footer from '@/components/Footer';
import DocsLayout from '@/components/docs/DocsLayout';

export default function DocsFirstServicePage() {
  return (
    <div className="flex min-h-screen flex-col bg-surface-950 text-surface-50">
      <Navbar />
      <DocsLayout
        title="Deploy Your First Service"
        intro="This is where DashCaddy becomes real: take an app from a template, an existing container, or a raw target port to a DNS-backed, reverse-proxied, HTTPS-enabled service visible in one dashboard — in a few clicks."
      >
        <h2>Prerequisites</h2>
        <blockquote className="border-l-4 border-brand-500/50 bg-brand-500/5 p-4 rounded-r-lg">
          <p className="text-surface-300">
            <strong className="text-brand-400">Before you begin:</strong> Complete the <a href="/docs/installation" className="text-brand-400 hover:text-brand-300 underline">Installation Guide</a> first. You need a running DashCaddy instance with the dashboard accessible, the API responding on <code>/healthz</code>, and Caddy's Admin API reachable. Technitium DNS is recommended but optional — services will still deploy without it using direct IP access.
          </p>
        </blockquote>

        <h2>What DashCaddy handles for you</h2>
        <p>When you deploy a service, DashCaddy automates the full infrastructure chain:</p>
        <ul>
          <li>Container deployment (from template) or adoption of an existing container</li>
          <li>Service record creation in the DashCaddy state store</li>
          <li>DNS record creation through Technitium DNS (when configured)</li>
          <li>Caddy reverse-proxy route configuration via the Admin API</li>
          <li>Automatic TLS certificate issuance through Caddy's internal CA / DashCA</li>
          <li>Real-time health tracking and WebSocket status updates on the dashboard</li>
        </ul>
        <p>
          You provide the intent (which app, which hostname), and DashCaddy coordinates every layer atomically.
          If any step fails, the operation rolls back cleanly — you never end up with a half-wired service.
        </p>

        <h2>Three ways to add a service</h2>

        <h3>1. Pick from 92+ one-click templates</h3>
        <p>
          The template library covers the most popular self-hosted applications — media servers, dashboards,
          databases, note apps, automation tools, and more. Each template bundles sane defaults for ports,
          volumes, environment variables, and the recommended subdomain.
        </p>

        <h3>2. Use Service Discovery to auto-detect existing containers</h3>
        <p>
          Already running Docker containers? DashCaddy's <strong>Service Discovery</strong> scans the host and lists
          every running container, marking any that are not yet managed.
        </p>

        <h3>3. Define a service manually</h3>
        <p>
          For custom images or apps not in the template library, define the service by hand with full control
          over image, ports, volumes, and environment variables.
        </p>

        <h2>Step-by-step: Deploy Plex</h2>
        <p>
          Let's walk through deploying Plex Media Server using the template library. This is the most common
          path for new users and demonstrates the full deployment chain.
        </p>

        <h3>Step 1: Open the template library</h3>
        <p>
          From the dashboard sidebar, click <strong>New Service → From Template</strong>. The template library
          opens with a searchable grid of 92+ applications.
        </p>

        <h3>Step 2: Find Plex</h3>
        <p>
          Type "Plex" in the search bar, or browse the "Media" category. Click the Plex template card to
          open its configuration form.
        </p>

        <h3>Step 3: Configure the service</h3>
        <p>The form is pre-filled with sensible defaults. Review and adjust:</p>
        <ul>
          <li><strong>Service name:</strong> <code>plex</code> (used for internal identification)</li>
          <li><strong>Hostname:</strong> <code>plex.local</code> (the subdomain DashCaddy will publish)</li>
          <li><strong>Container image:</strong> <code>linuxserver/plex:latest</code></li>
          <li><strong>Port:</strong> <code>32400</code> (Plex's default web interface port)</li>
          <li><strong>Volumes:</strong> <code>/opt/plex/config:/config</code> and <code>/mnt/media:/media</code></li>
          <li><strong>Environment variables:</strong> <code>PUID=1000</code>, <code>PGID=1000</code>, <code>VERSION=docker</code></li>
        </ul>

        <h3>Step 4: Deploy</h3>
        <p>
          Click <strong>Deploy</strong>. DashCaddy now executes the full deployment chain:
        </p>
        <ol>
          <li>Pulls the <code>linuxserver/plex:latest</code> Docker image</li>
          <li>Creates and starts the container with your configured volumes and environment</li>
          <li>Creates a service record in the DashCaddy state store</li>
          <li>Generates a Caddy route mapping <code>plex.local</code> → <code>localhost:32400</code></li>
          <li>Applies the route through the Caddy Admin API</li>
          <li>Requests a TLS certificate for <code>plex.local</code> via DashCA</li>
          <li>Creates an A record in Technitium DNS pointing <code>plex.local</code> to your host IP</li>
          <li>Starts health checks and reports status on the dashboard</li>
        </ol>

        <h3>Step 5: Verify</h3>
        <p>
          Within 30 seconds, the service card on the dashboard should show <strong>Healthy</strong> with a green
          status indicator. Click the service to see its detail page, which shows:
        </p>
        <ul>
          <li>Container logs (live-streamed via WebSocket)</li>
          <li>Resource usage (CPU, memory, network I/O)</li>
          <li>Caddy route configuration</li>
          <li>DNS record details</li>
          <li>Certificate expiration date</li>
          <li>Health check history</li>
        </ul>

        <h2>Service Discovery: Adopt existing containers</h2>
        <p>
          If you already have Docker containers running that you want DashCaddy to manage, use Service Discovery
          instead of redeploying from scratch.
        </p>

        <h3>How it works</h3>
        <p>
          Service Discovery scans the Docker socket and lists every running container on the host. Containers
          that are already managed by DashCaddy are marked as "Managed." Unmanaged containers are listed with
          their image name, exposed ports, and current status.
        </p>

        <h3>Adopt a container</h3>
        <ol>
          <li>Open <strong>Service Discovery</strong> from the sidebar</li>
          <li>Review the list of detected containers</li>
          <li>For each one you want to manage, click <strong>Adopt</strong></li>
          <li>Provide a hostname/subdomain (e.g., <code>grafana.local</code>)</li>
          <li>Specify which port to expose (if the container exposes multiple)</li>
          <li>Click <strong>Adopt &amp; Configure</strong></li>
        </ol>
        <p>
          DashCaddy creates a service record, generates the Caddy route, DNS record, and certificate — without
          restarting or modifying the running container. The container continues running with its existing
          configuration; DashCaddy simply adds the proxy and DNS layers on top.
        </p>

        <h2>Behind the scenes: The deployment chain</h2>
        <p>
          Understanding what happens during a deployment helps you troubleshoot when things go wrong. Here's
          the full chain, layer by layer:
        </p>

        <h3>1. Docker: Container creation</h3>
        <p>
          The orchestration layer calls the Docker API to create a container from the specified image. It attaches
          the container to the <code>dashcaddy-net</code> bridge network, mounts the configured volumes, and injects
          environment variables. The container starts in the background and begins listening on its configured port.
        </p>

        <h3>2. DashCaddy: Service record</h3>
        <p>
          A service record is written to the DashCaddy state store (a SQLite database in <code>./data/services.db</code>).
          The record includes the service name, hostname, backend port, container ID, deployment timestamp, and
          configuration metadata. This record is the source of truth for the dashboard and API.
        </p>

        <h3>3. Caddy: Reverse proxy route</h3>
        <p>
          The Caddyfile-as-Code builder generates a route configuration:
        </p>
        <pre className="mt-4 overflow-x-auto rounded-lg border border-surface-700/50 bg-surface-950/80 p-4 text-sm"><code>{`plex.local {
    reverse_proxy localhost:32400
    encode gzip
    header / {
        Strict-Transport-Security "max-age=31536000;"
    }
}`}</code></pre>
        <p>
          This configuration is applied atomically through the Caddy Admin API (<code>POST /load</code>). Caddy
          reloads its configuration without downtime and begins routing traffic for <code>plex.local</code> to
          <code>localhost:32400</code>.
        </p>

        <h3>4. DNS: Record creation</h3>
        <p>
          If Technitium DNS is configured, the orchestration layer calls the Technitium API to create an A record:
        </p>
        <pre className="mt-4 overflow-x-auto rounded-lg border border-surface-700/50 bg-surface-950/80 p-4 text-sm"><code>{`POST /api/zones/records/create
{
  "zone": "local",
  "type": "A",
  "name": "plex",
  "ipAddress": "192.168.1.100"
}`}</code></pre>
        <p>
          The DNS record propagates immediately (Technitium is authoritative for the <code>local</code> zone).
          Clients on your network can now resolve <code>plex.local</code> to your host's IP address.
        </p>

        <h3>5. TLS: Certificate issuance</h3>
        <p>
          Caddy's built-in ACME client detects the new hostname and requests a certificate. For internal domains
          like <code>plex.local</code>, Caddy uses its internal CA (DashCA) rather than Let's Encrypt. The certificate
          is issued, stored in Caddy's data directory, and served automatically for all HTTPS connections to
          <code>plex.local</code>.
        </p>
        <p>
          The certificate is valid for 90 days and renewed automatically 30 days before expiration. DashCaddy
          tracks certificate expiration dates and surfaces warnings on the dashboard when renewal is approaching.
        </p>

        <h3>6. Health: Continuous monitoring</h3>
        <p>
          Once the service is deployed, DashCaddy starts a health check loop that runs every 30 seconds. The health
          check performs an HTTP GET to the backend port and expects a 2xx or 3xx response. If the check fails three
          times in a row, the service is marked <strong>Unhealthy</strong> on the dashboard and an event is logged.
        </p>
        <p>
          Health status updates are pushed to the dashboard over WebSocket, so you see status changes in real-time
          without refreshing the page.
        </p>

        <h2>Configuration reference</h2>
        <p>
          When deploying a service, these are the configuration fields available in the deployment form:
        </p>
        <div className="overflow-x-auto">
          <table className="w-full text-left text-sm">
            <thead>
              <tr className="border-b border-surface-700">
                <th className="py-3 pr-4 font-semibold text-surface-200">Field</th>
                <th className="py-3 pr-4 font-semibold text-surface-200">Required</th>
                <th className="py-3 font-semibold text-surface-200">Description</th>
              </tr>
            </thead>
            <tbody className="text-surface-300">
              <tr className="border-b border-surface-800">
                <td className="py-3 pr-4 font-mono text-xs">Service Name</td>
                <td className="py-3 pr-4">Yes</td>
                <td className="py-3">Internal identifier (lowercase, no spaces)</td>
              </tr>
              <tr className="border-b border-surface-800">
                <td className="py-3 pr-4 font-mono text-xs">Hostname</td>
                <td className="py-3 pr-4">Yes</td>
                <td className="py-3">Subdomain for the service (e.g., plex.local)</td>
              </tr>
              <tr className="border-b border-surface-800">
                <td className="py-3 pr-4 font-mono text-xs">Container Image</td>
                <td className="py-3 pr-4">Yes</td>
                <td className="py-3">Docker image (e.g., linuxserver/plex:latest)</td>
              </tr>
              <tr className="border-b border-surface-800">
                <td className="py-3 pr-4 font-mono text-xs">Backend Port</td>
                <td className="py-3 pr-4">Yes</td>
                <td className="py-3">Port the container listens on internally</td>
              </tr>
              <tr className="border-b border-surface-800">
                <td className="py-3 pr-4 font-mono text-xs">Volumes</td>
                <td className="py-3 pr-4">No</td>
                <td className="py-3">Host:container path mappings for persistent storage</td>
              </tr>
              <tr className="border-b border-surface-800">
                <td className="py-3 pr-4 font-mono text-xs">Environment Variables</td>
                <td className="py-3 pr-4">No</td>
                <td className="py-3">Key-value pairs injected into the container</td>
              </tr>
              <tr className="border-b border-surface-800">
                <td className="py-3 pr-4 font-mono text-xs">Network</td>
                <td className="py-3 pr-4">No</td>
                <td className="py-3">Docker network to attach (default: dashcaddy-net)</td>
              </tr>
              <tr className="border-b border-surface-800">
                <td className="py-3 pr-4 font-mono text-xs">Restart Policy</td>
                <td className="py-3 pr-4">No</td>
                <td className="py-3">Container restart behavior (default: unless-stopped)</td>
              </tr>
              <tr>
                <td className="py-3 pr-4 font-mono text-xs">Health Check Path</td>
                <td className="py-3 pr-4">No</td>
                <td className="py-3">HTTP path for health checks (default: /)</td>
              </tr>
            </tbody>
          </table>
        </div>

        <h2>Common scenarios</h2>

        <h3>Deploy an internal-only service</h3>
        <p>
          For services that should stay on the local network (not exposed to the internet), use a <code>.local</code>
          or <code>.internal</code> TLD. Ensure client devices trust the DashCA root certificate (download it from
          the DashCA page in the dashboard). The service will be accessible at <code>https://servicename.local</code>
          with a trusted HTTPS connection, but only from devices on your network that have the root cert installed.
        </p>

        <h3>Deploy a service with custom environment variables</h3>
        <p>
          When deploying manually or editing a template, you can add custom environment variables in the deployment
          form. Each variable is a key-value pair that gets injected into the container at startup. Common examples:
        </p>
        <ul>
          <li><code>PUID=1000</code> / <code>PGID=1000</code> — user/group ID for file permissions (LinuxServer images)</li>
          <li><code>TZ=America/New_York</code> — timezone for log timestamps</li>
          <li><code>DB_PASSWORD=secret</code> — database credentials for apps like Nextcloud</li>
        </ul>

        <h3>Deploy multiple services on the same host</h3>
        <p>
          DashCaddy handles multiple services on the same host automatically. Each service gets a unique subdomain,
          and Caddy routes traffic based on the <code>Host</code> header. You can run Plex on <code>plex.local</code>,
          Nextcloud on <code>nextcloud.local</code>, and Grafana on <code>grafana.local</code> — all on the same
          host, all on port 443, with no port conflicts.
        </p>

        <h3>Adopt a service that's already running</h3>
        <p>
          If you have a container running outside of DashCaddy (e.g., started manually with <code>docker run</code>),
          use Service Discovery to adopt it. DashCaddy will add the proxy and DNS layers without restarting the
          container. The container's existing volumes, environment, and network configuration are preserved.
        </p>

        <h2>Verification checklist</h2>
        <p>After deploying a service, verify each layer:</p>
        <ol>
          <li>
            <strong>Container status:</strong> The service card on the dashboard shows <strong>Running</strong> with
            a green status indicator
          </li>
          <li>
            <strong>Backend port:</strong> <code>curl http://localhost:32400</code> returns a response from the
            application
          </li>
          <li>
            <strong>Caddy route:</strong> <code>curl http://localhost:2019/config/</code> shows a route for your
            hostname
          </li>
          <li>
            <strong>DNS resolution:</strong> <code>ping plex.local</code> resolves to your host's IP address
          </li>
          <li>
            <strong>TLS certificate:</strong> <code>curl -v https://plex.local</code> shows a valid certificate
            (no warnings if DashCA root is installed)
          </li>
          <li>
            <strong>Health check:</strong> The dashboard shows <strong>Healthy</strong> and the health check
            history graph shows consistent success
          </li>
        </ol>

        <h2>Troubleshooting</h2>
        <p>If the service does not come up correctly, debug in order, layer by layer:</p>
        <ol>
          <li><strong>Container:</strong> Check <code>docker logs &lt;container_name&gt;</code> for startup errors</li>
          <li><strong>Backend port:</strong> Verify the container is listening on the expected port</li>
          <li><strong>Caddy route:</strong> Confirm the route exists in the Caddy Admin API</li>
          <li><strong>DNS resolution:</strong> Check that the DNS record was created in Technitium</li>
          <li><strong>TLS trust:</strong> Verify the DashCA root certificate is installed on the client device</li>
          <li><strong>Dashboard state:</strong> Check the service detail page for error messages or failed health checks</li>
        </ol>
        <p>
          See the <a href="/docs/troubleshooting" className="text-brand-400 hover:text-brand-300 underline">Troubleshooting Guide</a> for
          the full checklist and common error patterns.
        </p>

        <h2>Next steps</h2>
        <ul>
          <li>
            <a href="/docs/overview" className="text-brand-400 hover:text-brand-300 underline">
              Product Overview
            </a> — understand the full architecture and design philosophy
          </li>
          <li>
            Explore the <strong>Template Library</strong> to discover other applications you can deploy
          </li>
          <li>
            Configure <strong>Service Discovery</strong> to adopt existing containers
          </li>
          <li>
            Set up <strong>Prometheus metrics</strong> for external monitoring integration
          </li>
        </ul>
      </DocsLayout>
      <Footer />
    </div>
  );
}
