import { motion, useInView } from 'framer-motion';
import { useRef } from 'react';

/* ─── constants ─────────────────────────────────────────────── */
const CX = 220,
    CY = 215; // svg centre
const R = 132; // orbit radius
const AR = 139; // arrow arc radius (just outside orbit)
const NR = 31; // node coin radius

const TEAL = '#FA510F';
const GOLD = '#DCE67A';

const ease = [0.16, 1, 0.3, 1] as const;
const spring = [0.34, 1.56, 0.64, 1] as const;

/* ─── helpers ────────────────────────────────────────────────── */
const rad = (d: number) => (d * Math.PI) / 180;

// deg=0 → top, positive → clockwise
const pt = (deg: number, r = R) => ({
    x: +(CX + r * Math.sin(rad(deg))).toFixed(2),
    y: +(CY - r * Math.cos(rad(deg))).toFixed(2),
});

// SVG arc path CW from fromDeg to toDeg on circle of radius r
const arc = (fromDeg: number, toDeg: number, r = AR): string => {
    const p1 = pt(fromDeg, r),
        p2 = pt(toDeg, r);
    const span = (toDeg - fromDeg + 360) % 360;
    return `M${p1.x},${p1.y} A${r},${r} 0 ${span > 180 ? 1 : 0} 1 ${p2.x},${p2.y}`;
};

/* ─── stage definitions ──────────────────────────────────────── */
type Stage = {
    deg: number;
    label: string;
    sub: string;
    color: string;
    icon: React.ReactNode;
};

const STAGES: Stage[] = [
    {
        deg: 330,
        label: 'Application',
        sub: 'Borrower applies',
        color: TEAL,
        icon: (
            <>
                <rect
                    x={-8}
                    y={-10}
                    width={16}
                    height={20}
                    rx={2}
                    fill="none"
                    strokeWidth="1.6"
                />
                <line x1={-4} y1={-3} x2={4} y2={-3} strokeWidth="1.3" />
                <line x1={-4} y1={1} x2={4} y2={1} strokeWidth="1.3" />
                <line x1={-4} y1={5} x2={1} y2={5} strokeWidth="1.3" />
                <path d="M4,-10 L8,-6 L4,-6 Z" strokeWidth="0" />
            </>
        ),
    },
    {
        deg: 30,
        label: 'Assessment',
        sub: 'KYC & risk review',
        color: GOLD,
        icon: (
            <>
                <circle cx={-2} cy={-3} r={7} fill="none" strokeWidth="1.8" />
                <line
                    x1={3.5}
                    y1={3}
                    x2={9.5}
                    y2={9}
                    strokeWidth="2.5"
                    strokeLinecap="round"
                />
            </>
        ),
    },
    {
        deg: 90,
        label: 'Approval',
        sub: 'Multi-stage sign-off',
        color: TEAL,
        icon: (
            <>
                <path
                    d="M0,-11 L9.5,-6.5 L9.5,3 Q9.5,10.5 0,13 Q-9.5,10.5 -9.5,3 L-9.5,-6.5 Z"
                    fill="none"
                    strokeWidth="1.6"
                />
                <path
                    d="M-4.5,2 L-1,5.5 L6,-3"
                    fill="none"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                />
            </>
        ),
    },
    {
        deg: 150,
        label: 'Disbursement',
        sub: 'Funds released',
        color: GOLD,
        icon: (
            <>
                <line
                    x1={0}
                    y1={-10}
                    x2={0}
                    y2={3}
                    strokeWidth="1.8"
                    strokeLinecap="round"
                />
                <path
                    d="M-5,0 L0,6 L5,0"
                    fill="none"
                    strokeWidth="1.8"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                />
                <ellipse cx={-4.5} cy={10} rx={3.5} ry={1.6} strokeWidth="0" />
                <ellipse cx={4.5} cy={10} rx={3.5} ry={1.6} strokeWidth="0" />
                <ellipse cx={0} cy={11.8} rx={3.5} ry={1.6} strokeWidth="0" />
            </>
        ),
    },
    {
        deg: 210,
        label: 'Repayment',
        sub: 'Installments paid',
        color: TEAL,
        icon: (
            <>
                <path
                    d="M-2,-9 A9,9 0 1 1 9,0"
                    fill="none"
                    strokeWidth="1.8"
                    strokeLinecap="round"
                />
                <path
                    d="M9,-5 L9,1 L4.5,-1"
                    fill="none"
                    strokeWidth="1.4"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                />
                <path
                    d="M2,9 A9,9 0 0 1 -9,0"
                    fill="none"
                    strokeWidth="1.8"
                    strokeLinecap="round"
                />
                <path
                    d="M-9,5 L-9,-1 L-4.5,1"
                    fill="none"
                    strokeWidth="1.4"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                />
            </>
        ),
    },
    {
        deg: 270,
        label: 'Monitoring',
        sub: 'Portfolio tracked',
        color: GOLD,
        icon: (
            <>
                <line
                    x1={-10}
                    y1={8}
                    x2={10}
                    y2={8}
                    strokeWidth="1.4"
                    strokeLinecap="round"
                />
                <rect
                    x={-9}
                    y={1}
                    width={4}
                    height={7}
                    rx={0.8}
                    strokeWidth="0"
                />
                <rect
                    x={-2}
                    y={-4}
                    width={4}
                    height={12}
                    rx={0.8}
                    strokeWidth="0"
                />
                <rect
                    x={5}
                    y={-8}
                    width={4}
                    height={16}
                    rx={0.8}
                    strokeWidth="0"
                />
                <path
                    d="M-8,4 L-2,-2 L4,0 L9,-6"
                    fill="none"
                    strokeWidth="1.3"
                    opacity={0.6}
                    strokeLinecap="round"
                    strokeLinejoin="round"
                />
            </>
        ),
    },
];

const GAP = 17; // degrees trimmed from each end of arrow arc to leave gap at nodes

/* ─── component ──────────────────────────────────────────────── */
interface Props {
    className?: string;
}

export function LoanCycleIllustration({ className = '' }: Props) {
    const ref = useRef<SVGSVGElement>(null);
    const inView = useInView(ref, { once: true, margin: '-60px' });

    return (
        <svg
            ref={ref}
            viewBox="0 0 440 440"
            className={className}
            fill="none"
            aria-hidden="true"
        >
            <defs>
                <radialGradient id="lcBg2" cx="50%" cy="50%" r="50%">
                    <stop offset="0%" stopColor={TEAL} stopOpacity="0.09" />
                    <stop offset="100%" stopColor="#050C1A" stopOpacity="0" />
                </radialGradient>
                <filter
                    id="lcGlow2"
                    x="-60%"
                    y="-60%"
                    width="220%"
                    height="220%"
                >
                    <feGaussianBlur stdDeviation="3.5" result="blur" />
                    <feMerge>
                        <feMergeNode in="blur" />
                        <feMergeNode in="SourceGraphic" />
                    </feMerge>
                </filter>
                <filter
                    id="lcShadow2"
                    x="-40%"
                    y="-40%"
                    width="180%"
                    height="180%"
                >
                    <feDropShadow
                        dx="0"
                        dy="4"
                        stdDeviation="7"
                        floodColor="#000"
                        floodOpacity="0.45"
                    />
                </filter>
                {/* Arrow markers */}
                <marker
                    id="arrTeal"
                    markerWidth="9"
                    markerHeight="9"
                    refX="8"
                    refY="4.5"
                    orient="auto"
                >
                    <path d="M0,0 L0,9 L9,4.5 Z" fill={TEAL} opacity="0.9" />
                </marker>
                <marker
                    id="arrGold"
                    markerWidth="9"
                    markerHeight="9"
                    refX="8"
                    refY="4.5"
                    orient="auto"
                >
                    <path d="M0,0 L0,9 L9,4.5 Z" fill={GOLD} opacity="0.9" />
                </marker>
            </defs>

            {/* Background */}
            <circle cx={CX} cy={CY} r={210} fill="url(#lcBg2)" />
            <circle
                cx={CX}
                cy={CY}
                r={190}
                stroke={TEAL}
                strokeWidth="0.4"
                strokeDasharray="3 18"
                opacity="0.12"
            />

            {/* Orbit track */}
            <circle
                cx={CX}
                cy={CY}
                r={R}
                stroke={TEAL}
                strokeWidth="0.8"
                strokeDasharray="3 9"
                opacity="0.18"
            />

            {/* ── ARROWS ─────────────────────────────────────────────── */}
            {STAGES.map((s, i) => {
                const next = STAGES[(i + 1) % STAGES.length];
                const fromDeg = s.deg + GAP;
                const toDeg = next.deg - GAP;
                const isTeal = s.color === TEAL;
                return (
                    <motion.path
                        key={`arr-${i}`}
                        d={arc(fromDeg, toDeg)}
                        stroke={isTeal ? TEAL : GOLD}
                        strokeWidth="1.6"
                        strokeLinecap="round"
                        markerEnd={isTeal ? 'url(#arrTeal)' : 'url(#arrGold)'}
                        filter="url(#lcGlow2)"
                        initial={{ pathLength: 0, opacity: 0 }}
                        animate={inView ? { pathLength: 1, opacity: 0.75 } : {}}
                        transition={{
                            duration: 0.7,
                            delay: 0.25 + i * 0.13,
                            ease,
                        }}
                    />
                );
            })}

            {/* ── CENTRAL 3D PLATFORM ───────────────────────────────── */}
            <motion.g
                initial={{ scale: 0, opacity: 0 }}
                animate={inView ? { scale: 1, opacity: 1 } : {}}
                transition={{ duration: 0.7, delay: 0.1, ease: spring }}
                style={{ transformOrigin: `${CX}px ${CY}px` }}
            >
                {/* Soft shadow below platform */}
                <ellipse
                    cx={CX}
                    cy={CY + 56}
                    rx={72}
                    ry={14}
                    fill={TEAL}
                    opacity={0.06}
                />

                {/* Layer 3 — widest disk */}
                <circle
                    cx={CX}
                    cy={CY + 13}
                    r={62}
                    style={{ fill: 'hsl(var(--il-deep))' }}
                />
                <circle
                    cx={CX}
                    cy={CY + 9}
                    r={62}
                    style={{ fill: 'hsl(var(--il-bg))' }}
                    stroke={TEAL}
                    strokeWidth="0.7"
                    strokeOpacity={0.18}
                />

                {/* Layer 2 */}
                <circle
                    cx={CX}
                    cy={CY + 7}
                    r={50}
                    style={{ fill: 'hsl(var(--il-deep))' }}
                />
                <circle
                    cx={CX}
                    cy={CY + 3}
                    r={50}
                    style={{ fill: 'hsl(var(--il-bg))' }}
                    stroke={TEAL}
                    strokeWidth="0.7"
                    strokeOpacity={0.22}
                />

                {/* Layer 1 — medallion face */}
                <circle
                    cx={CX}
                    cy={CY + 2}
                    r={40}
                    style={{ fill: 'hsl(var(--il-deep))' }}
                />
                <circle
                    cx={CX}
                    cy={CY - 2}
                    r={40}
                    style={{ fill: 'hsl(var(--il-bg))' }}
                    stroke={TEAL}
                    strokeWidth="2"
                    filter="url(#lcShadow2)"
                />

                {/* Inner decorative ring */}
                <circle
                    cx={CX}
                    cy={CY - 2}
                    r={32}
                    fill="none"
                    stroke={TEAL}
                    strokeWidth="0.6"
                    opacity={0.28}
                />

                {/* Ambient glow pulse */}
                <motion.circle
                    cx={CX}
                    cy={CY - 2}
                    r={32}
                    fill={TEAL}
                    opacity={0}
                    animate={inView ? { opacity: [0, 0.07, 0] } : {}}
                    transition={{
                        duration: 2.6,
                        repeat: Infinity,
                        ease: 'easeInOut',
                        delay: 1.1,
                    }}
                />

                {/* Coin glow edge */}
                <circle
                    cx={CX}
                    cy={CY - 2}
                    r={40}
                    fill="none"
                    stroke={TEAL}
                    strokeWidth="2"
                    opacity={0.5}
                    filter="url(#lcGlow2)"
                />

                {/* Text */}
                <motion.text
                    x={CX}
                    y={CY - 9}
                    textAnchor="middle"
                    fill={TEAL}
                    fontSize={12}
                    fontWeight="900"
                    letterSpacing="2.5"
                    initial={{ opacity: 0 }}
                    animate={inView ? { opacity: 1 } : {}}
                    transition={{ duration: 0.5, delay: 0.9 }}
                >
                    LOAN
                </motion.text>
                <motion.text
                    x={CX}
                    y={CY + 5}
                    textAnchor="middle"
                    style={{ fill: 'hsl(var(--il-text))' }}
                    fontSize={7.5}
                    opacity={0.42}
                    letterSpacing="1.5"
                    initial={{ opacity: 0 }}
                    animate={inView ? { opacity: 0.42 } : {}}
                    transition={{ duration: 0.5, delay: 1.0 }}
                >
                    LIFECYCLE
                </motion.text>
            </motion.g>

            {/* ── NODE COINS ─────────────────────────────────────────── */}
            {STAGES.map((s, i) => {
                const pos = pt(s.deg);
                const delay = 0.18 + i * 0.12;

                return (
                    <g key={s.label}>
                        {/* Outer pulse */}
                        <motion.circle
                            cx={pos.x}
                            cy={pos.y}
                            r={NR + 15}
                            fill={s.color}
                            opacity={0}
                            animate={
                                inView
                                    ? {
                                          opacity: [0, 0.065, 0],
                                          r: [NR + 10, NR + 26, NR + 10],
                                      }
                                    : {}
                            }
                            transition={{
                                duration: 3.2,
                                repeat: Infinity,
                                delay: 1.5 + i * 0.5,
                                ease: 'easeInOut',
                            }}
                        />

                        {/* 3D depth — shadow coin (offset down) */}
                        <motion.circle
                            cx={pos.x}
                            cy={pos.y + 5}
                            r={NR}
                            initial={{ scale: 0, opacity: 0 }}
                            animate={inView ? { scale: 1, opacity: 1 } : {}}
                            transition={{ duration: 0.52, delay, ease: spring }}
                            style={{
                                transformOrigin: `${pos.x}px ${pos.y + 5}px`,
                                fill: 'hsl(var(--il-deep))',
                            }}
                        />
                        {/* 3D depth — edge ring (offset down slightly) */}
                        <motion.circle
                            cx={pos.x}
                            cy={pos.y + 2}
                            r={NR}
                            stroke={s.color}
                            strokeWidth="0.6"
                            strokeOpacity={0.25}
                            initial={{ scale: 0, opacity: 0 }}
                            animate={inView ? { scale: 1, opacity: 1 } : {}}
                            transition={{ duration: 0.52, delay, ease: spring }}
                            style={{
                                transformOrigin: `${pos.x}px ${pos.y + 2}px`,
                                fill: 'hsl(var(--il-bg))',
                            }}
                        />
                        {/* Face coin */}
                        <motion.circle
                            cx={pos.x}
                            cy={pos.y}
                            r={NR}
                            stroke={s.color}
                            strokeWidth="1.8"
                            filter="url(#lcShadow2)"
                            initial={{ scale: 0, opacity: 0 }}
                            animate={inView ? { scale: 1, opacity: 1 } : {}}
                            transition={{ duration: 0.52, delay, ease: spring }}
                            style={{
                                transformOrigin: `${pos.x}px ${pos.y}px`,
                                fill: 'hsl(var(--il-bg))',
                            }}
                        />
                        {/* Inner decorative ring */}
                        <motion.circle
                            cx={pos.x}
                            cy={pos.y}
                            r={NR - 8}
                            fill="none"
                            stroke={s.color}
                            strokeWidth="0.5"
                            opacity={0.18}
                            initial={{ opacity: 0 }}
                            animate={inView ? { opacity: 0.18 } : {}}
                            transition={{ duration: 0.3, delay: delay + 0.15 }}
                        />

                        {/* Face glow edge */}
                        <motion.circle
                            cx={pos.x}
                            cy={pos.y}
                            r={NR}
                            fill="none"
                            stroke={s.color}
                            strokeWidth="1.8"
                            opacity={0.4}
                            filter="url(#lcGlow2)"
                            initial={{ opacity: 0 }}
                            animate={inView ? { opacity: 0.4 } : {}}
                            transition={{ duration: 0.4, delay: delay + 0.1 }}
                        />

                        {/* Icon */}
                        <motion.g
                            transform={`translate(${pos.x},${pos.y - 6})`}
                            stroke={s.color}
                            fill={s.color}
                            strokeLinecap="round"
                            initial={{ opacity: 0, scale: 0.5 }}
                            animate={inView ? { opacity: 1, scale: 1 } : {}}
                            transition={{
                                duration: 0.4,
                                delay: delay + 0.18,
                                ease: spring,
                            }}
                            style={{ transformOrigin: '0px 0px' }}
                        >
                            {s.icon}
                        </motion.g>

                        {/* Label */}
                        <motion.text
                            x={pos.x}
                            y={pos.y + 19}
                            textAnchor="middle"
                            fill={s.color}
                            fontSize={6}
                            fontWeight="800"
                            letterSpacing="0.6"
                            initial={{ opacity: 0 }}
                            animate={inView ? { opacity: 1 } : {}}
                            transition={{ duration: 0.35, delay: delay + 0.28 }}
                        >
                            {s.label.toUpperCase()}
                        </motion.text>
                    </g>
                );
            })}
        </svg>
    );
}
