import React from "react";
import Link from "next/link";
import { MaterialIcon } from "@/components/ui/MaterialIcon";
import { PremiumPageShell } from "@/components/layout/PremiumPageShell";
import type { Metadata } from "next";

export const metadata: Metadata = {
  title: "Terms of Service",
  description:
    "Read Nearle's Terms of Service. Understand your rights and responsibilities as a customer, merchant, or delivery partner on India's hyperlocal neighbourhood commerce platform.",
  openGraph: {
    title: "Terms of Service | Nearle",
    description:
      "Nearle's terms of service — governing accounts, orders, payments, merchant and delivery partner responsibilities.",
    url: "https://nearle.in/terms",
  },
};

const SECTIONS = [
  { id: "accounts", label: "Accounts" },
  { id: "orders", label: "Orders" },
  { id: "payments", label: "Payments" },
  { id: "merchant-responsibilities", label: "Merchant Responsibilities" },
  { id: "delivery-responsibilities", label: "Delivery Partner Responsibilities" },
  { id: "acceptable-use", label: "Acceptable Use" },
  { id: "refunds", label: "Refunds & Cancellations" },
  { id: "termination", label: "Termination" },
  { id: "liability", label: "Limitation of Liability" },
  { id: "contact", label: "Contact Us" },
];

const SUMMARY_CARDS = [
  {
    icon: "gavel",
    title: "Governed by Indian Law",
    desc: "These terms are governed by Indian law. Disputes are subject to courts in Coimbatore, Tamil Nadu.",
    tone: "bg-[#6330D6]/8 text-[#6330D6]",
  },
  {
    icon: "handshake",
    title: "Fair Use Platform",
    desc: "Nearle is a community platform. Abuse, fraud, or misuse of any kind will result in account termination.",
    tone: "bg-secondary/8 text-secondary",
  },
  {
    icon: "support_agent",
    title: "We're Here to Help",
    desc: "Disputes? Refund questions? Our support team resolves issues fairly for all parties involved.",
    tone: "bg-[#6330D6]/8 text-[#6330D6]",
  },
];

export default function TermsOfServicePage() {
  return (
    <PremiumPageShell>
      {/* ─── Hero Bar ─── */}
      <section className="w-full bg-gradient-to-br from-white via-[#FEFCFF] to-[#F4ECFA] border-b border-[#6330D6]/10 py-12 md:py-16 px-6 md:px-12 lg:px-16 xl:px-20">
        <div className="max-w-[1600px] mx-auto">
          <div className="flex flex-col md:flex-row md:items-end justify-between gap-6">
            <div>
              <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-black tracking-widest bg-[#6330D6]/10 text-[#6330D6] uppercase mb-5 w-fit">
                Legal
              </span>
              <h1 className="font-display text-4xl sm:text-5xl lg:text-[52px] font-black text-[#16001D] leading-tight tracking-tight">
                Terms of Service
              </h1>
              <p className="text-sm md:text-base text-[#5E5866] mt-4 max-w-2xl leading-relaxed font-semibold">
                These Terms of Service govern your use of the Nearle platform — including the customer app, merchant dashboard, and delivery partner app. By using Nearle, you agree to these terms.
              </p>
            </div>
            <div className="shrink-0 text-right">
              <span className="text-xs text-[#5E5866] font-semibold">Effective Date</span>
              <div className="text-sm font-black text-[#16001D] mt-0.5">1 January 2025</div>
              <div className="text-xs text-[#5E5866] mt-2 font-semibold">Last Updated</div>
              <div className="text-sm font-black text-[#16001D] mt-0.5">1 June 2026</div>
            </div>
          </div>

          {/* Summary cards */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-10">
            {SUMMARY_CARDS.map((card) => (
              <div key={card.title} className="flex gap-3 p-4 rounded-2xl bg-white border border-[#6330D6]/8 shadow-sm">
                <div className={`w-10 h-10 rounded-full flex items-center justify-center shrink-0 ${card.tone}`}>
                  <MaterialIcon icon={card.icon} size={20} />
                </div>
                <div>
                  <h4 className="text-sm font-black text-[#16001D]">{card.title}</h4>
                  <p className="text-xs text-[#5E5866] mt-1 leading-relaxed">{card.desc}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ─── Content with Sidebar TOC ─── */}
      <section className="py-10 md:py-14 bg-white">
        <div className="px-6 md:px-12 lg:px-16 xl:px-20 max-w-[1600px] mx-auto">
          <div className="grid grid-cols-1 lg:grid-cols-[260px_1fr] gap-10 lg:gap-16 items-start">

            {/* Sidebar TOC */}
            <nav className="lg:sticky lg:top-24 hidden lg:block" aria-label="Page sections">
              <p className="text-[10px] font-black uppercase tracking-widest text-[#5E5866] mb-4">On This Page</p>
              <ul className="space-y-1">
                {SECTIONS.map((section) => (
                  <li key={section.id}>
                    <a
                      href={`#${section.id}`}
                      className="block text-sm font-semibold text-[#5E5866] hover:text-[#6330D6] py-1.5 px-3 rounded-xl hover:bg-[#6330D6]/5 transition-all duration-200"
                    >
                      {section.label}
                    </a>
                  </li>
                ))}
              </ul>

              <div className="mt-8 p-4 rounded-2xl bg-[#FAF7FD] border border-[#6330D6]/10">
                <p className="text-xs font-black text-[#16001D] mb-2">Questions about these terms?</p>
                <Link
                  href="/contact"
                  className="inline-flex items-center gap-1.5 text-xs font-black text-[#6330D6] hover:text-[#5225b8] transition-colors"
                >
                  <span>Contact us</span>
                  <MaterialIcon icon="arrow_forward" size={14} />
                </Link>
              </div>
            </nav>

            {/* Main Content */}
            <div className="space-y-12 max-w-none">

              <TermsSection id="accounts" title="1. Accounts">
                <p>To use Nearle, you must create an account using your phone number. You are responsible for keeping your account secure and for all activity that occurs under it.</p>
                <TermsList items={[
                  "You must be at least 18 years old to create an account (or have guardian consent if aged 16–18)",
                  "You may only hold one active customer account on Nearle",
                  "You must provide accurate information during registration and keep it up to date",
                  "Sharing or transferring your account to another person is not permitted",
                  "You must notify Nearle immediately if you suspect unauthorised access to your account",
                ]} />
                <p>Nearle reserves the right to suspend or terminate accounts that appear fraudulent, inactive, or in violation of these terms.</p>
              </TermsSection>

              <TermsSection id="orders" title="2. Orders">
                <p>When you place an order through Nearle, you are entering into a purchase agreement with the merchant store, not with Nearle. Nearle facilitates the transaction and delivery but is not the seller of the goods.</p>
                <TermsList items={[
                  "Orders are confirmed only after the merchant accepts them — availability is not guaranteed",
                  "Order contents, quantities, and prices are as listed at the time of placement",
                  "Substitutions may be offered by the merchant if an item is unavailable — you can accept or cancel",
                  "Estimated delivery times are approximate and may vary based on store preparation and delivery conditions",
                  "You must be reachable at the delivery address at the time of order fulfillment",
                ]} />
                <TermsNote>
                  If a merchant is unable to fulfill your order, you will be notified promptly and fully refunded. Nearle is not liable for merchant-side stock issues.
                </TermsNote>
              </TermsSection>

              <TermsSection id="payments" title="3. Payments">
                <p>Payments on Nearle are processed through secure, PCI DSS-compliant payment gateways. Nearle accepts UPI, debit/credit cards, net banking, and wallets. Cash on Delivery is available in select zones.</p>
                <TermsList items={[
                  "All prices are inclusive of applicable taxes unless stated otherwise",
                  "Delivery fees, if applicable, are shown clearly before order confirmation",
                  "Nearle does not store card numbers or payment credentials",
                  "Merchant payouts are processed weekly on a settlement cycle",
                  "Delivery partner earnings are settled weekly, every Monday",
                  "Disputed transactions should be raised within 7 days of the transaction date",
                ]} />
              </TermsSection>

              <TermsSection id="merchant-responsibilities" title="4. Merchant Responsibilities">
                <p>Merchants listed on Nearle agree to maintain the quality and accuracy of their stores, products, and order fulfilment.</p>
                <TermsList items={[
                  "Maintain accurate product listings, including correct prices and availability",
                  "Accept and fulfil orders within agreed preparation times",
                  "Deliver quality products that match the description in the digital catalogue",
                  "Not list counterfeit, expired, or prohibited goods on the platform",
                  "Handle customer orders with care and communicate delays promptly",
                  "Follow all applicable food safety, health, and trade regulations",
                  "Not attempt to take transactions outside the Nearle platform",
                  "Respond to Nearle merchant support queries within 24 hours",
                ]} />
                <p>Repeated complaints, low ratings, or violations of merchant responsibilities may result in listing suspension or removal from the platform.</p>
              </TermsSection>

              <TermsSection id="delivery-responsibilities" title="5. Delivery Partner Responsibilities">
                <p>Delivery partners accept orders on a voluntary basis and are responsible for safe, timely deliveries.</p>
                <TermsList items={[
                  "Maintain a valid driving licence and vehicle registration (where applicable)",
                  "Handle all customer orders with care — no tampering with sealed packages",
                  "Deliver to the correct address and confirm delivery through the app",
                  "Behave respectfully toward customers and merchants at all times",
                  "Follow road safety rules during all delivery shifts",
                  "Not accept cash payments from customers unless approved for Cash on Delivery orders",
                  "Keep the Nearle app updated and maintain a functioning smartphone during shifts",
                ]} />
                <TermsNote>
                  Delivery partners are independent contractors, not employees of Nearle. They are responsible for their own taxes on earnings.
                </TermsNote>
              </TermsSection>

              <TermsSection id="acceptable-use" title="6. Acceptable Use">
                <p>Nearle is a platform built on community trust. The following are strictly prohibited:</p>
                <TermsList items={[
                  "Creating fake accounts, fake reviews, or impersonating another person",
                  "Placing fraudulent orders with no intention to receive or pay",
                  "Using Nearle to sell prohibited, illegal, or unsafe products",
                  "Attempting to reverse-engineer, scrape, or misuse the Nearle platform",
                  "Harassing, threatening, or abusing merchants, delivery partners, or customers",
                  "Using multiple accounts to abuse promotions, discounts, or referral programs",
                  "Interfering with the platform's technical infrastructure or security",
                ]} />
                <p>Violations will result in immediate account suspension without refund of any outstanding balance.</p>
              </TermsSection>

              <TermsSection id="refunds" title="7. Refunds and Cancellations">
                <TermsSubheading>Customer Cancellations</TermsSubheading>
                <p>You may cancel an order within 2 minutes of placing it for a full refund. Once a merchant has confirmed and started preparing your order, cancellations are at the merchant&apos;s discretion.</p>

                <TermsSubheading>Merchant Cancellations</TermsSubheading>
                <p>If a merchant cancels your order due to unavailability or stock issues, you will receive a full refund to your original payment method within 5 to 7 business days.</p>

                <TermsSubheading>Damaged or Incorrect Orders</TermsSubheading>
                <p>If you receive a damaged, missing, or incorrect item, report it to Nearle support within 2 hours of delivery with a photo. We will review the case and issue a full or partial refund as appropriate.</p>

                <TermsSubheading>Refund Timeline</TermsSubheading>
                <TermsList items={[
                  "UPI and wallet refunds: within 24 hours",
                  "Debit/credit card refunds: 5 to 7 business days",
                  "Cash on Delivery orders: credited to Nearle wallet for future use",
                ]} />
              </TermsSection>

              <TermsSection id="termination" title="8. Termination">
                <p>Either party may terminate the relationship at any time:</p>
                <TermsList items={[
                  "Customers can delete their account through the Nearle app settings at any time",
                  "Merchants can offboard from the platform with 30 days written notice",
                  "Delivery partners can deactivate their partner profile at any time without penalty",
                ]} />
                <p>Nearle reserves the right to suspend or permanently terminate any account — customer, merchant, or delivery partner — for violations of these terms, fraud, safety concerns, or behaviour that harms the community. We will notify affected parties where legally required.</p>
              </TermsSection>

              <TermsSection id="liability" title="9. Limitation of Liability">
                <p>Nearle provides its platform on an &quot;as available&quot; basis. While we strive for a reliable, high-quality service, the following limitations apply:</p>
                <TermsList items={[
                  "Nearle is not liable for product quality, freshness, or accuracy — those are the merchant's responsibility",
                  "Nearle is not liable for delivery delays caused by weather, traffic, or force majeure",
                  "Nearle is not responsible for losses arising from account compromise due to sharing credentials",
                  "Our aggregate liability to any user for any claim shall not exceed the value of the disputed transaction",
                ]} />
                <p>These limitations do not affect statutory rights under Indian consumer protection law.</p>
              </TermsSection>

              <TermsSection id="contact" title="10. Contact and Disputes">
                <p>For questions about these Terms of Service or to raise a dispute, contact:</p>
                <div className="mt-5 p-6 rounded-2xl bg-[#FAF7FD] border border-[#6330D6]/10">
                  <h4 className="text-base font-black text-[#16001D] mb-3">Nearle Legal Team</h4>
                  <div className="space-y-2 text-sm text-[#5E5866]">
                    <div className="flex gap-2">
                      <MaterialIcon icon="mail" size={16} className="text-[#6330D6] shrink-0 mt-0.5" />
                      <a href="mailto:legal@nearle.in" className="text-[#6330D6] font-black hover:underline">legal@nearle.in</a>
                    </div>
                    <div className="flex gap-2">
                      <MaterialIcon icon="location_on" size={16} className="text-[#6330D6] shrink-0 mt-0.5" />
                      <span>424, Diwan Bahadur Rd, Opp. Sri Krishna Sweets, R.S. Puram, Coimbatore, TN 641002</span>
                    </div>
                  </div>
                  <p className="text-xs text-[#5E5866] mt-4">These terms are governed by Indian law. Disputes are subject to the exclusive jurisdiction of courts in Coimbatore, Tamil Nadu.</p>
                </div>
              </TermsSection>

            </div>
          </div>
        </div>
      </section>

      {/* ─── Bottom nav ─── */}
      <section className="py-8 bg-[#FAF7FD] border-t border-[#6330D6]/10">
        <div className="px-6 md:px-12 lg:px-16 xl:px-20 max-w-[1600px] mx-auto">
          <div className="flex flex-wrap gap-4 justify-center">
            {[
              { label: "Privacy Policy", href: "/privacy", icon: "lock" },
              { label: "Cookie Policy", href: "/cookies", icon: "cookie" },
              { label: "Contact Us", href: "/contact", icon: "mail" },
            ].map((link) => (
              <Link
                key={link.label}
                href={link.href}
                className="inline-flex items-center gap-2 px-5 py-2.5 rounded-full border border-[#6330D6]/15 bg-white text-sm font-black text-[#16001D] hover:border-[#6330D6]/30 hover:bg-[#6330D6]/5 transition-all duration-200"
              >
                <MaterialIcon icon={link.icon} size={16} className="text-[#6330D6]" />
                {link.label}
              </Link>
            ))}
          </div>
        </div>
      </section>
    </PremiumPageShell>
  );
}

function TermsSection({ id, title, children }: { id: string; title: string; children: React.ReactNode }) {
  return (
    <div id={id} className="scroll-mt-28">
      <h2 className="font-display text-2xl md:text-3xl font-black text-[#16001D] mb-5 pb-4 border-b border-[#6330D6]/10 leading-tight tracking-tight">
        {title}
      </h2>
      <div className="space-y-4 text-sm md:text-base text-[#5E5866] leading-relaxed">
        {children}
      </div>
    </div>
  );
}

function TermsSubheading({ children }: { children: React.ReactNode }) {
  return (
    <h3 className="text-base md:text-lg font-black text-[#16001D] mt-5 mb-2">
      {children}
    </h3>
  );
}

function TermsList({ items }: { items: string[] }) {
  return (
    <ul className="space-y-2 mt-3">
      {items.map((item, i) => (
        <li key={i} className="flex gap-2.5">
          <div className="w-1.5 h-1.5 rounded-full bg-[#6330D6] mt-2 shrink-0" />
          <span>{item}</span>
        </li>
      ))}
    </ul>
  );
}

function TermsNote({ children }: { children: React.ReactNode }) {
  return (
    <div className="flex gap-3 p-4 rounded-2xl bg-[#6330D6]/5 border border-[#6330D6]/10 mt-4">
      <MaterialIcon icon="info" size={18} className="text-[#6330D6] shrink-0 mt-0.5" />
      <p className="text-sm text-[#5E5866] leading-relaxed">{children}</p>
    </div>
  );
}
