"use client";

import { useState, useEffect } from "react";
import { useLanguage } from "@/contexts/LanguageContext";
import { localizedPath } from "@/lib/localized-path";
import {
  plans,
  currencyConfig,
  getPrice,
  getAnnualTotalPrice,
  getAnnualSavingsPercent,
  formatPrice,
  detectCurrencyFromIP,
  pricingFaqs,
  type Currency,
} from "@/data/pricing-content";

export type BillingPeriod = "monthly" | "annual";

export default function PricingArea() {
  const { language, t } = useLanguage();
  const isAr = language === "ar";
  const [currency, setCurrency] = useState<Currency>("SAR");
  const [billingPeriod, setBillingPeriod] = useState<BillingPeriod>("monthly");
  const [openFaq, setOpenFaq] = useState<number | null>(null);

  useEffect(() => {
    detectCurrencyFromIP().then(setCurrency);
  }, []);

  const cc = currencyConfig[currency];

  return (
    <section className="pricing-page-area">
      <style jsx>{`
        .pricing-page-area {
          padding: 120px 0 80px;
          background: #000000;
          min-height: 100vh;
          position: relative;
          overflow: hidden;
        }

        .pricing-page-area::before {
          content: "";
          position: absolute;
          top: -200px;
          left: 50%;
          transform: translateX(-50%);
          width: 800px;
          height: 800px;
          background: radial-gradient(circle, rgba(102, 16, 242, 0.15) 0%, transparent 70%);
          pointer-events: none;
        }

        .page-header {
          text-align: center;
          margin-bottom: 20px;
          position: relative;
          z-index: 1;
        }

        .page-badge {
          display: inline-block;
          padding: 6px 16px;
          background: rgba(255, 255, 255, 0.06);
          border: 1px solid rgba(255, 255, 255, 0.08);
          border-radius: 20px;
          font-size: 13px;
          font-weight: 500;
          color: #94a3b8;
          letter-spacing: 0.5px;
          text-transform: uppercase;
          margin-bottom: 24px;
        }

        .page-header h1 {
          font-size: 48px;
          font-weight: 700;
          margin-bottom: 20px;
          color: #fff;
          letter-spacing: -0.5px;
        }

        .page-header p {
          font-size: 18px;
          color: #94a3b8;
          max-width: 640px;
          margin: 0 auto;
          line-height: 1.7;
        }

        .billing-toggle-wrap {
          display: flex;
          justify-content: center;
          margin: 40px 0 48px;
          position: relative;
          z-index: 1;
        }

        .billing-toggle {
          display: inline-flex;
          align-items: center;
          gap: 4px;
          padding: 4px;
          background: rgba(255, 255, 255, 0.05);
          border: 1px solid rgba(255, 255, 255, 0.08);
          border-radius: 12px;
        }

        .billing-option {
          position: relative;
          padding: 10px 20px;
          border: none;
          border-radius: 9px;
          background: transparent;
          font-size: 14px;
          font-weight: 600;
          color: #94a3b8;
          cursor: pointer;
          transition: color 0.2s ease, background 0.2s ease;
          white-space: nowrap;
        }

        .billing-option.active {
          background: rgba(102, 16, 242, 0.25);
          color: #fff;
        }

        .billing-savings-badge {
          display: inline-block;
          margin-inline-start: 6px;
          padding: 2px 8px;
          background: rgba(34, 197, 94, 0.15);
          border: 1px solid rgba(34, 197, 94, 0.35);
          border-radius: 20px;
          font-size: 11px;
          font-weight: 700;
          color: #4ade80;
          letter-spacing: 0.2px;
        }

        .price-savings-tag {
          display: inline-block;
          margin-top: 8px;
          padding: 3px 10px;
          background: rgba(34, 197, 94, 0.12);
          border: 1px solid rgba(34, 197, 94, 0.3);
          border-radius: 6px;
          font-size: 12px;
          font-weight: 600;
          color: #4ade80;
        }

        .pricing-grid {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 20px;
          align-items: stretch;
          position: relative;
          z-index: 1;
        }

        .pricing-card {
          background: rgba(255, 255, 255, 0.03);
          border: 1px solid rgba(255, 255, 255, 0.06);
          border-radius: 20px;
          padding: 36px 32px;
          display: flex;
          flex-direction: column;
          transition: border-color 0.3s ease, transform 0.3s ease, box-shadow 0.3s ease;
          position: relative;
        }

        .pricing-card:hover {
          border-color: rgba(255, 255, 255, 0.12);
          transform: translateY(-4px);
        }

        .pricing-card.featured {
          background: rgba(102, 16, 242, 0.08);
          border: 2px solid rgba(102, 16, 242, 0.4);
          transform: scale(1.03);
          box-shadow: 0 0 60px rgba(102, 16, 242, 0.15), 0 0 120px rgba(102, 16, 242, 0.05);
        }

        .pricing-card.featured:hover {
          transform: scale(1.03) translateY(-4px);
          border-color: rgba(102, 16, 242, 0.6);
          box-shadow: 0 0 80px rgba(102, 16, 242, 0.2), 0 0 160px rgba(102, 16, 242, 0.08);
        }

        .popular-badge {
          position: absolute;
          top: -14px;
          left: 50%;
          transform: translateX(-50%);
          background: linear-gradient(135deg, #6610f2, #8b5cf6);
          color: #fff;
          font-size: 12px;
          font-weight: 600;
          padding: 6px 20px;
          border-radius: 20px;
          letter-spacing: 0.5px;
          white-space: nowrap;
        }

        .plan-name {
          font-size: 22px;
          font-weight: 600;
          color: #fff;
          margin: 0 0 8px 0;
        }

        .plan-desc {
          font-size: 14px;
          color: #94a3b8;
          line-height: 1.6;
          margin: 0 0 24px 0;
          min-height: 44px;
        }

        .price-block {
          margin-bottom: 28px;
        }

        .price-amount {
          display: flex;
          align-items: baseline;
          gap: 6px;
        }

        .price-value {
          font-size: 44px;
          font-weight: 800;
          color: #fff;
          letter-spacing: -1px;
          line-height: 1;
        }

        .price-currency {
          font-size: 18px;
          font-weight: 600;
          color: #94a3b8;
        }

        .price-period {
          font-size: 14px;
          color: #64748b;
          margin-top: 4px;
        }

        .features-list {
          list-style: none;
          padding: 0;
          margin: 0 0 32px 0;
          flex: 1;
          display: flex;
          flex-direction: column;
          gap: 12px;
        }

        .feature-row {
          display: flex;
          align-items: flex-start;
          gap: 10px;
          font-size: 14px;
          color: #cbd5e1;
          line-height: 1.5;
        }

        .feature-icon {
          width: 20px;
          height: 20px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-shrink: 0;
          margin-top: 1px;
        }

        .feature-icon.check {
          background: rgba(16, 185, 129, 0.15);
          color: #10b981;
        }

        .feature-icon.cross {
          background: rgba(239, 68, 68, 0.1);
          color: #ef4444;
        }

        .feature-icon svg {
          width: 11px;
          height: 11px;
        }

        .feature-text {
          flex: 1;
          display: flex;
          align-items: center;
          gap: 5px;
          flex-wrap: wrap;
        }

        .info-trigger {
          position: relative;
          display: inline-flex;
          align-items: center;
          cursor: help;
          flex-shrink: 0;
        }

        .info-trigger svg {
          width: 14px;
          height: 14px;
          color: #64748b;
          transition: color 0.15s;
        }

        .info-trigger:hover svg {
          color: #8b5cf6;
        }

        .info-bubble {
          display: none;
          position: absolute;
          bottom: calc(100% + 8px);
          left: 50%;
          transform: translateX(-50%);
          background: #1e1b4b;
          border: 1px solid rgba(139, 92, 246, 0.3);
          border-radius: 10px;
          padding: 10px 14px;
          font-size: 12px;
          line-height: 1.55;
          color: #cbd5e1;
          width: 220px;
          z-index: 50;
          pointer-events: none;
          box-shadow: 0 8px 24px rgba(0,0,0,0.4);
        }

        .info-bubble::after {
          content: "";
          position: absolute;
          top: 100%;
          left: 50%;
          transform: translateX(-50%);
          border: 6px solid transparent;
          border-top-color: #1e1b4b;
        }

        .info-trigger:hover .info-bubble {
          display: block;
        }

        [dir="rtl"] .info-bubble {
          direction: rtl;
          text-align: right;
        }

        .feature-value {
          font-weight: 600;
          color: #e2e8f0;
        }

        .feature-unlimited {
          color: #8b5cf6;
          font-weight: 600;
        }

        .cta-btn {
          display: block;
          width: 100%;
          padding: 14px 24px;
          border-radius: 12px;
          font-size: 15px;
          font-weight: 600;
          text-align: center;
          text-decoration: none;
          transition: all 0.2s ease;
          cursor: pointer;
          border: none;
        }

        .cta-btn.primary {
          background: linear-gradient(135deg, #6610f2, #8b5cf6);
          color: #fff;
          box-shadow: 0 4px 20px rgba(102, 16, 242, 0.3);
        }

        .cta-btn.primary:hover {
          box-shadow: 0 4px 30px rgba(102, 16, 242, 0.5);
          transform: translateY(-1px);
        }

        .cta-btn.outline {
          background: transparent;
          color: #fff;
          border: 1px solid rgba(255, 255, 255, 0.15);
        }

        .cta-btn.outline:hover {
          border-color: rgba(102, 16, 242, 0.5);
          background: rgba(102, 16, 242, 0.08);
          transform: translateY(-1px);
        }

        .vat-note {
          text-align: center;
          margin-top: 32px;
          font-size: 13px;
          color: #64748b;
          position: relative;
          z-index: 1;
        }

        .faq-section {
          margin-top: 100px;
          position: relative;
          z-index: 1;
        }

        .faq-header {
          text-align: center;
          margin-bottom: 48px;
        }

        .faq-header h2 {
          font-size: 36px;
          font-weight: 700;
          color: #fff;
          margin: 0 0 12px 0;
        }

        .faq-header p {
          font-size: 16px;
          color: #94a3b8;
        }

        .faq-list {
          max-width: 800px;
          margin: 0 auto;
          display: flex;
          flex-direction: column;
          gap: 12px;
        }

        .faq-item {
          background: rgba(255, 255, 255, 0.03);
          border: 1px solid rgba(255, 255, 255, 0.06);
          border-radius: 14px;
          overflow: hidden;
          transition: border-color 0.2s ease;
        }

        .faq-item:hover {
          border-color: rgba(255, 255, 255, 0.1);
        }

        .faq-item.open {
          border-color: rgba(102, 16, 242, 0.3);
        }

        .faq-question {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 20px 24px;
          cursor: pointer;
          gap: 16px;
          background: none;
          border: none;
          width: 100%;
          text-align: inherit;
        }

        .faq-question h4 {
          font-size: 16px;
          font-weight: 600;
          color: #e2e8f0;
          margin: 0;
          flex: 1;
        }

        .faq-chevron {
          width: 20px;
          height: 20px;
          color: #94a3b8;
          transition: transform 0.2s ease;
          flex-shrink: 0;
        }

        .faq-item.open .faq-chevron {
          transform: rotate(180deg);
        }

        .faq-answer {
          padding: 0 24px 20px;
          font-size: 14px;
          color: #94a3b8;
          line-height: 1.7;
          margin: 0;
        }

        .custom-plan-section {
          text-align: center;
          margin-top: 80px;
          padding: 56px 40px;
          background: rgba(255, 255, 255, 0.03);
          border-radius: 20px;
          border: 1px solid rgba(255, 255, 255, 0.06);
          position: relative;
          z-index: 1;
        }

        .custom-plan-section h2 {
          font-size: 32px;
          font-weight: 700;
          color: #fff;
          margin: 0 0 12px 0;
        }

        .custom-plan-section p {
          font-size: 16px;
          color: #94a3b8;
          margin: 0 0 32px 0;
          max-width: 520px;
          margin-left: auto;
          margin-right: auto;
        }

        .contact-btn {
          display: inline-flex;
          align-items: center;
          gap: 10px;
          padding: 14px 32px;
          background: #6610f2;
          border: none;
          border-radius: 10px;
          font-size: 16px;
          font-weight: 600;
          color: #fff;
          cursor: pointer;
          transition: background 0.2s ease, transform 0.15s ease;
          text-decoration: none;
        }

        .contact-btn:hover {
          background: #5a0cd6;
          transform: translateY(-1px);
        }

        @media (max-width: 1280px) {
          .pricing-grid {
            grid-template-columns: repeat(2, 1fr);
            max-width: 720px;
            margin: 0 auto;
          }
        }

        @media (max-width: 768px) {
          .pricing-grid {
            grid-template-columns: 1fr;
            max-width: 420px;
          }

          .pricing-card.featured {
            transform: none;
          }

          .pricing-card.featured:hover {
            transform: translateY(-4px);
          }

          .pricing-page-area {
            padding: 100px 0 60px;
          }

          .page-header h1 {
            font-size: 32px;
          }

          .page-header p {
            font-size: 16px;
          }

          .pricing-card {
            padding: 28px 24px;
          }

          .price-value {
            font-size: 36px;
          }

          .faq-header h2 {
            font-size: 28px;
          }

          .custom-plan-section {
            padding: 36px 20px;
          }

          .custom-plan-section h2 {
            font-size: 26px;
          }
        }
      `}</style>

      <div className="container">
        <div className="page-header" data-aos="fade-up">
          <span className="page-badge">
            {isAr ? "الأسعار" : "Pricing"}
          </span>
          <h1>{isAr ? "اختر الباقة المناسبة لعملك" : "Choose the Right Plan for Your Business"}</h1>
          <p>
            {isAr
              ? "وسّع أعمالك مع الأتمتة بالذكاء الاصطناعي. اختر الباقة التي تناسب احتياجاتك."
              : "Scale your business with AI-powered automation. Pick a plan that fits your needs."}
          </p>
        </div>

        <div className="billing-toggle-wrap" data-aos="fade-up" data-aos-delay="100">
          <div className="billing-toggle" role="group" aria-label={isAr ? "فترة الفوترة" : "Billing period"}>
            <button
              type="button"
              className={`billing-option${billingPeriod === "monthly" ? " active" : ""}`}
              onClick={() => setBillingPeriod("monthly")}
            >
              {isAr ? "شهري" : "Monthly"}
            </button>
            <button
              type="button"
              className={`billing-option${billingPeriod === "annual" ? " active" : ""}`}
              onClick={() => setBillingPeriod("annual")}
            >
              {isAr ? "سنوي" : "Annual"}
              <span className="billing-savings-badge">
                {isAr
                  ? `وفّر ${getAnnualSavingsPercent()}%`
                  : `Save ${getAnnualSavingsPercent()}%`}
              </span>
            </button>
          </div>
        </div>

        {/* Currency is auto-detected from user IP */}

        <div className="pricing-grid">
          {plans.map((plan, idx) => {
            const monthlyPrice = getPrice(plan.priceSAR, currency);
            const annualTotal =
              plan.priceSAR > 0 ? getAnnualTotalPrice(plan.priceSAR, currency) : 0;
            const sym = isAr ? cc.symbolAr : cc.symbol;

            return (
              <div
                key={plan.id}
                className={`pricing-card${plan.featured ? " featured" : ""}`}
                data-aos="fade-up"
                data-aos-delay={idx * 100 + 200}
              >
                {plan.featured && (
                  <div className="popular-badge">
                    {isAr ? "الأكثر شيوعاً" : "Most Popular"}
                  </div>
                )}

                <h3 className="plan-name">
                  {isAr ? plan.nameAr : plan.nameEn}
                </h3>
                <p className="plan-desc">
                  {isAr ? plan.descAr : plan.descEn}
                </p>

                <div className="price-block">
                  {plan.priceSAR === 0 ? (
                    <>
                      <div className="price-amount">
                        <span className="price-value">{isAr ? "مجانية" : "Free"}</span>
                      </div>
                      <div className="price-period">
                        {isAr ? "للأبد" : "forever"}
                      </div>
                    </>
                  ) : billingPeriod === "annual" ? (
                    <>
                      <div className="price-amount">
                        <span className="price-value">{formatPrice(annualTotal, currency)}</span>
                        <span className="price-currency">{sym}</span>
                      </div>
                      <div className="price-period">
                        {isAr ? "/سنوياً" : "/year"}
                      </div>
                      <div className="price-savings-tag">
                        {isAr ? "شهران مجاناً" : "2 months free"}
                      </div>
                    </>
                  ) : (
                    <>
                      <div className="price-amount">
                        <span className="price-value">{formatPrice(monthlyPrice, currency)}</span>
                        <span className="price-currency">{sym}</span>
                      </div>
                      <div className="price-period">
                        {isAr ? "/شهرياً" : "/month"}
                      </div>
                    </>
                  )}
                </div>

                <ul className="features-list">
                  {plan.features.map((f, fi) => {
                    const label = isAr ? f.keyAr : f.keyEn;
                    const info = isAr ? f.infoAr : f.infoEn;
                    const isUnlimited = f.value === "unlimited";
                    const isBool = typeof f.value === "boolean";
                    const isIncluded = isBool ? f.value : true;
                    const isZero = f.value === "0";

                    return (
                      <li key={fi} className="feature-row">
                        <span className={`feature-icon ${isIncluded && !isZero ? "check" : "cross"}`}>
                          {isIncluded && !isZero ? (
                            <svg viewBox="0 0 12 12" fill="none">
                              <path d="M10 3L4.5 8.5L2 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                            </svg>
                          ) : (
                            <svg viewBox="0 0 12 12" fill="none">
                              <path d="M9 3L3 9M3 3l6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                            </svg>
                          )}
                        </span>
                        <span className="feature-text">
                          {isBool ? (
                            label
                          ) : isUnlimited ? (
                            <>
                              <span className="feature-unlimited">
                                {isAr ? "غير محدود" : "Unlimited"}
                              </span>{" "}
                              {label}
                            </>
                          ) : (
                            <>
                              <span className="feature-value">{f.value}</span>{" "}
                              {label}
                            </>
                          )}
                          {info && (
                            <span className="info-trigger">
                              <svg viewBox="0 0 16 16" fill="none">
                                <circle cx="8" cy="8" r="7" stroke="currentColor" strokeWidth="1.5"/>
                                <path d="M8 7v4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                                <circle cx="8" cy="5" r="0.75" fill="currentColor"/>
                              </svg>
                              <span className="info-bubble">{info}</span>
                            </span>
                          )}
                        </span>
                      </li>
                    );
                  })}
                </ul>

                <a
                  href="https://dashboard.skylightchat.com/register"
                  className={`cta-btn ${plan.featured ? "primary" : "outline"}`}
                >
                  {isAr ? "ابدأ الآن" : "Get Started"}
                </a>
              </div>
            );
          })}
        </div>

        <p className="vat-note">
          {isAr
            ? "جميع الأسعار لا تشمل ضريبة القيمة المضافة"
            : "All prices exclude VAT"}
        </p>

        {/* FAQ Section */}
        <div className="faq-section" data-aos="fade-up">
          <div className="faq-header">
            <h2>{isAr ? "الأسئلة الشائعة" : "Frequently Asked Questions"}</h2>
            <p>
              {isAr
                ? "إجابات على الأسئلة الأكثر شيوعاً حول الأسعار والباقات"
                : "Answers to the most common questions about pricing and plans"}
            </p>
          </div>

          <div className="faq-list">
            {pricingFaqs.map((faq, i) => (
              <div
                key={i}
                className={`faq-item${openFaq === i ? " open" : ""}`}
              >
                <button
                  className="faq-question"
                  onClick={() => setOpenFaq(openFaq === i ? null : i)}
                >
                  <h4>{isAr ? faq.questionAr : faq.questionEn}</h4>
                  <svg className="faq-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M6 9l6 6 6-6" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </button>
                {openFaq === i && (
                  <p className="faq-answer">
                    {isAr ? faq.answerAr : faq.answerEn}
                  </p>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Custom Plan CTA */}
        <div className="custom-plan-section" data-aos="fade-up">
          <h2>{isAr ? "هل تحتاج خطة مخصصة؟" : "Need a Custom Plan?"}</h2>
          <p>
            {isAr
              ? "تواصل مع فريق المبيعات لدينا للحصول على حل مخصص يناسب احتياجات عملك."
              : "Contact our sales team for a tailored solution that fits your business needs."}
          </p>
          <a href={localizedPath("/contact-us", language)} className="contact-btn">
            {isAr ? "تواصل معنا" : "Contact Sales"}
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M5 12h14M12 5l7 7-7 7" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </a>
        </div>
      </div>
    </section>
  );
}
