/* global React */
const { useState, useEffect, useRef, useCallback } = React;

// ---------- Toast hook ----------
let toastIdCounter = 0;
function ToastViewport({ toasts, dismiss }) {
  return (
    <div className="fixed bottom-6 right-6 z-50 flex flex-col gap-3 w-[360px] max-w-[calc(100vw-3rem)] pointer-events-none">
      {toasts.map((t) => (
        <div
          key={t.id}
          className={`${t.exiting ? 'toast-exit' : 'toast-enter'} pointer-events-auto rounded-xl border border-white/10 bg-[#141414]/95 backdrop-blur-md p-4 shadow-2xl shadow-black/40 flex gap-3 items-start`}
        >
          <div className="w-8 h-8 shrink-0 rounded-full bg-gradient-to-br from-[#FF5656] to-[#FF9E4F] flex items-center justify-center">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="20 6 9 17 4 12"></polyline>
            </svg>
          </div>
          <div className="flex-1 min-w-0">
            <div className="text-sm font-medium text-white">{t.title}</div>
            {t.description && (
              <div className="text-xs text-white/60 mt-0.5">{t.description}</div>
            )}
          </div>
          <button
            onClick={() => dismiss(t.id)}
            className="text-white/40 hover:text-white/80 transition-colors shrink-0"
            aria-label="Dismiss"
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <line x1="18" y1="6" x2="6" y2="18"></line>
              <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
          </button>
        </div>
      ))}
    </div>
  );
}

function useToast() {
  const [toasts, setToasts] = useState([]);
  const timersRef = useRef({});

  const dismiss = useCallback((id) => {
    setToasts((curr) => curr.map((t) => t.id === id ? { ...t, exiting: true } : t));
    setTimeout(() => {
      setToasts((curr) => curr.filter((t) => t.id !== id));
    }, 200);
    if (timersRef.current[id]) {
      clearTimeout(timersRef.current[id]);
      delete timersRef.current[id];
    }
  }, []);

  const toast = useCallback(({ title, description, duration = 3500 }) => {
    const id = ++toastIdCounter;
    setToasts((curr) => [...curr, { id, title, description }]);
    timersRef.current[id] = setTimeout(() => dismiss(id), duration);
    return id;
  }, [dismiss]);

  return { toast, toasts, dismiss };
}

// ---------- Slider ----------
function Slider({ min, max, step, value, onChange }) {
  const pct = ((value - min) / (max - min)) * 100;
  return (
    <div className="relative w-full py-3">
      <div className="relative h-[6px] rounded-full bg-[#262626]">
        <div className="slider-track-fill" style={{ width: `${pct}%` }} />
        <input
          type="range"
          min={min}
          max={max}
          step={step}
          value={value}
          onChange={(e) => onChange(parseInt(e.target.value, 10))}
          className="price-slider absolute inset-0 w-full bg-transparent"
          style={{ background: 'transparent' }}
        />
      </div>
    </div>
  );
}

// ---------- Form atoms ----------
function RadioRow({ checked, onClick, label, priceLabel }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="opt-row w-full flex items-center justify-between gap-4 py-3 px-3 -mx-3 rounded-lg text-left group"
    >
      <span className="flex items-center gap-3">
        <span className={`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors ${checked ? 'border-[#FF5656]' : 'border-white/25 group-hover:border-white/45'}`}>
          {checked && <span className="w-2 h-2 rounded-full bg-[#FF5656]" />}
        </span>
        <span className={`text-[15px] ${checked ? 'text-white' : 'text-white/75'}`}>{label}</span>
      </span>
      {priceLabel && (
        <span className="text-sm font-mono text-[#FF5656] tabular-nums">{priceLabel}</span>
      )}
    </button>
  );
}

function CheckRow({ checked, onClick, label, priceLabel }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="opt-row w-full flex items-center justify-between gap-4 py-3 px-3 -mx-3 rounded-lg text-left group"
    >
      <span className="flex items-center gap-3">
        <span className={`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${checked ? 'border-[#FF5656] bg-[#FF5656]' : 'border-white/25 group-hover:border-white/45'}`}>
          {checked && (
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="20 6 9 17 4 12"></polyline>
            </svg>
          )}
        </span>
        <span className={`text-[15px] ${checked ? 'text-white' : 'text-white/75'}`}>{label}</span>
      </span>
      {priceLabel && (
        <span className="text-sm font-mono text-[#FF5656] tabular-nums">{priceLabel}</span>
      )}
    </button>
  );
}

// ---------- Animated price ----------
function AnimatedPrice({ value, className }) {
  const [display, setDisplay] = useState(value);
  const rafRef = useRef(null);
  const fromRef = useRef(value);
  const startRef = useRef(0);
  const DURATION = 350;

  useEffect(() => {
    cancelAnimationFrame(rafRef.current);
    fromRef.current = display;
    startRef.current = performance.now();
    const tick = (now) => {
      const t = Math.min(1, (now - startRef.current) / DURATION);
      const e = 1 - Math.pow(1 - t, 3);
      const next = Math.round(fromRef.current + (value - fromRef.current) * e);
      setDisplay(next);
      if (t < 1) rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [value]);

  return <span className={className}>${display.toLocaleString()}</span>;
}

function SectionHeader({ index, title, inline }) {
  return (
    <div className="flex items-center gap-3">
      <span className="font-mono text-[10px] text-white/30 tracking-widest">{index}</span>
      <h3 className="text-[17px] md:text-[18px] text-white font-normal tracking-tight">{title}</h3>
    </div>
  );
}

function ComparisonCard({ label, price, note, icon }) {
  const iconSvg = icon === 'agency' ? (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="7" width="18" height="14" rx="1.5"></rect>
      <path d="M8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
      <path d="M3 13h18"></path>
    </svg>
  ) : (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="8" r="4"></circle>
      <path d="M4 21a8 8 0 0 1 16 0"></path>
    </svg>
  );
  return (
    <div className="rounded-2xl p-6 bg-white/[0.035] border border-white/[0.06] space-y-3 hover:bg-white/[0.045] transition-colors">
      <div className="flex items-center justify-between gap-3">
        <div className="flex items-center gap-2.5 text-white/70 text-[13px]">
          <span className="w-7 h-7 rounded-full bg-white/5 border border-white/10 flex items-center justify-center text-white/60">
            {iconSvg}
          </span>
          <span>{label}</span>
        </div>
        <div className="text-[10px] font-mono uppercase tracking-widest text-white/30 line-through">market</div>
      </div>
      <AnimatedPrice value={price} className="block text-4xl font-bold tabular-nums text-white tracking-tight" />
      <div className="text-xs text-white/45">{note}</div>
    </div>
  );
}

// ---------- Calculator ----------
function Calculator() {
  const [serviceType, setServiceType] = useState('both');
  const [pages, setPages] = useState(5);
  const [needContent, setNeedContent] = useState(false);
  const [needSEO, setNeedSEO] = useState(false);
  const [timeline, setTimeline] = useState('regular');
  const { toast, toasts, dismiss } = useToast();
  const lastToastedRef = useRef(null);

  const calculatePrice = () => {
    const bases = {
      design: { base: 399, perPage: 100 },
      development: { base: 199, perPage: 100 },
      both: { base: 499, perPage: 200 },
    };
    const cfg = bases[serviceType];
    let total = Math.max(cfg.base, cfg.base + (pages - 1) * cfg.perPage);
    if (needContent) total += pages * 50;
    if (needSEO) total += pages * 50;
    if (timeline === 'rush') total += pages * 100;
    if (timeline === 'fast') total += pages * 25;
    return total;
  };
  const calculateAgencyCost = () => {
    const perPage = serviceType === 'both' ? 1000 : 400;
    return 8000 + (pages - 1) * perPage;
  };
  const calculateFreelancerCost = () => {
    const perPage = serviceType === 'both' ? 500 : 200;
    return 3000 + (pages - 1) * perPage;
  };

  const yourPrice = calculatePrice();
  const agencyPrice = calculateAgencyCost();
  const freelancerPrice = calculateFreelancerCost();
  const savings = Math.max(0, agencyPrice - yourPrice);

  const handleServiceChange = (val) => {
    setServiceType(val);
    const label = val === 'design' ? 'Design only' : val === 'development' ? 'Development only' : 'Design + Development';
    const key = `svc-${val}`;
    if (lastToastedRef.current !== key) {
      toast({ title: 'Service updated', description: label });
      lastToastedRef.current = key;
    }
  };

  const handleTimelineChange = (val) => {
    setTimeline(val);
    const key = `tl-${val}`;
    if (lastToastedRef.current !== key) {
      const label = val === 'rush' ? 'Rushed — within 7 days' : val === 'fast' ? 'Fast — within 14 days' : 'Regular timeline';
      toast({ title: 'Timeline updated', description: label });
      lastToastedRef.current = key;
    }
  };

  const handleRequestQuote = () => {
    toast({
      title: 'Quote request sent',
      description: `Estimate: $${yourPrice.toLocaleString()} — we'll be in touch shortly.`,
      duration: 4500,
    });
  };

  return (
    <>
      <section id="calculator-section" className="w-full bg-background scroll-mt-20">
        <div className="max-w-7xl mx-auto py-16 md:py-28 px-4 md:px-16">

          <div className="text-center mb-12 md:mb-16 reveal">
            <div className="font-mono uppercase tracking-[0.22em] text-xs text-muted-foreground mb-5 flex items-center justify-center gap-2">
              <span className="inline-block w-1.5 h-1.5 rounded-full bg-[#FF5656]" />
              Try project estimation calculator
              <span className="inline-block w-1.5 h-1.5 rounded-full bg-[#FF5656]" />
            </div>
            <h2 className="text-3xl md:text-4xl lg:text-5xl font-normal tracking-tight text-white max-w-3xl mx-auto leading-[1.1]">
              Get <span className="font-serif italic text-white/95">premium website</span> within your budget
            </h2>
            <p className="text-muted-foreground text-sm md:text-base mt-5 max-w-xl mx-auto">
              Configure your project below — your estimate updates in real time.
            </p>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 rounded-2xl overflow-hidden border border-white/[0.07] reveal">

            <div className="bg-[#0D0D0D] p-8 lg:p-12 divide-y divide-[#1E1E1E]">

              <div className="pb-7">
                <SectionHeader index="01" title="What kind of service do you need?" />
                <div className="mt-4 space-y-1">
                  <RadioRow checked={serviceType==='design'} onClick={()=>handleServiceChange('design')} label="Only Design" />
                  <RadioRow checked={serviceType==='development'} onClick={()=>handleServiceChange('development')} label="Only Development" />
                  <RadioRow checked={serviceType==='both'} onClick={()=>handleServiceChange('both')} label="Design + Development" />
                </div>
              </div>

              <div className="py-7">
                <div className="flex items-center justify-between gap-4">
                  <SectionHeader index="02" title="Number of pages" inline />
                  <div className="flex items-baseline gap-1.5">
                    <span className="text-3xl font-medium text-[#FF5656] tabular-nums leading-none">{pages}</span>
                    <span className="text-sm text-white/40 leading-none">{pages === 1 ? 'page' : 'pages'}</span>
                  </div>
                </div>
                <div className="mt-5">
                  <Slider min={1} max={30} step={1} value={pages} onChange={setPages} />
                  <div className="flex justify-between text-xs font-mono text-white/40 mt-1">
                    <span>1</span>
                    <span>30</span>
                  </div>
                </div>
              </div>

              <div className="py-7">
                <SectionHeader index="03" title="Any add-ons?" />
                <div className="mt-4 space-y-1">
                  <CheckRow
                    checked={needContent}
                    onClick={() => setNeedContent(v => !v)}
                    label="I will need help with content"
                    priceLabel="+$50/page"
                  />
                  <CheckRow
                    checked={needSEO}
                    onClick={() => setNeedSEO(v => !v)}
                    label="I want to optimize my website for SEO"
                    priceLabel="+$50/page"
                  />
                </div>
              </div>

              <div className="pt-7">
                <SectionHeader index="04" title="How fast do you need this?" />
                <div className="mt-4 space-y-1">
                  <RadioRow
                    checked={timeline==='rush'}
                    onClick={()=>handleTimelineChange('rush')}
                    label="Within 7 days"
                    priceLabel="+$100/page"
                  />
                  <RadioRow
                    checked={timeline==='fast'}
                    onClick={()=>handleTimelineChange('fast')}
                    label="Within 14 days"
                    priceLabel="+$25/page"
                  />
                  <RadioRow
                    checked={timeline==='regular'}
                    onClick={()=>handleTimelineChange('regular')}
                    label="Regular speed (based on discussion)"
                    priceLabel="No extra"
                  />
                </div>
              </div>
            </div>

            <div
              className="p-8 lg:p-12 border-t lg:border-t-0 lg:border-l border-white/10 bg-[#0A0A0A] flex flex-col"
              style={{ minHeight: '717.98px' }}
            >
              <div className="mb-6">
                <div className="font-mono uppercase tracking-[0.22em] text-[10px] text-muted-foreground mb-3">
                  / Estimation
                </div>
                <h3 className="text-2xl md:text-3xl font-normal text-white tracking-tight">Estimated cost</h3>
                <p className="text-sm text-muted-foreground mt-2 leading-relaxed max-w-md">
                  Here's how your project compares against the typical market. Final pricing is confirmed after a quick discovery call.
                </p>
              </div>

              <div className="space-y-4 mt-2">

                <ComparisonCard
                  label="Typical agency charges minimum"
                  price={agencyPrice}
                  note="+ Too much extra time & additional cost"
                  icon="agency"
                />

                <ComparisonCard
                  label="Regular freelancer charges minimum"
                  price={freelancerPrice}
                  note="+ Too much headache & back-and-forth"
                  icon="freelancer"
                />

                <div className="relative rounded-2xl p-6 price-card-glow overflow-hidden"
                     style={{ background: 'linear-gradient(115deg, #FF5656 0%, #FF7A4F 55%, #FF9E4F 100%)' }}>
                  <div className="absolute inset-0 opacity-20 mix-blend-overlay pointer-events-none"
                       style={{
                         backgroundImage: 'radial-gradient(circle at 20% 10%, rgba(255,255,255,0.5), transparent 40%), radial-gradient(circle at 80% 90%, rgba(0,0,0,0.25), transparent 50%)'
                       }} />
                  <div className="relative flex items-start justify-between gap-3">
                    <div className="text-xs uppercase tracking-[0.18em] font-mono text-white/85">
                      With Webfluin Studio
                    </div>
                    <div className="text-[11px] font-mono px-2 py-1 rounded-full bg-black/25 text-white border border-white/20">
                      Best value
                    </div>
                  </div>
                  <div className="relative mt-4 flex items-baseline gap-3 flex-wrap">
                    <AnimatedPrice value={yourPrice} className="text-5xl font-bold tabular-nums text-white tracking-tight" />
                    {savings > 0 && (
                      <span className="text-xs font-mono text-white/85 bg-black/20 border border-white/15 px-2 py-1 rounded-md">
                        save ${savings.toLocaleString()}
                      </span>
                    )}
                  </div>
                  <div className="relative text-sm text-white/90 mt-2.5">
                    Save your money, time & headache.
                  </div>
                </div>
              </div>

              <div className="mt-auto pt-7">
                <button
                  onClick={handleRequestQuote}
                  className="group w-full flex items-center justify-between gap-3 bg-white text-black rounded-xl px-5 py-4 text-[15px] font-medium hover:bg-white/90 transition-colors"
                >
                  <span>Request a tailored quote</span>
                  <span className="w-8 h-8 rounded-full bg-black flex items-center justify-center group-hover:translate-x-0.5 transition-transform">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <line x1="5" y1="12" x2="19" y2="12"></line>
                      <polyline points="12 5 19 12 12 19"></polyline>
                    </svg>
                  </span>
                </button>
                <p className="text-xs text-white/35 text-center mt-3 font-mono">
                  No commitment · We reply within 24h
                </p>
              </div>
            </div>
          </div>
        </div>
      </section>
      <ToastViewport toasts={toasts} dismiss={dismiss} />
    </>
  );
}

Object.assign(window, { Calculator });
