All files / varjoliitokauppa/pages AdminNew.tsx

12.66% Statements 79/624
2.12% Branches 12/566
1.22% Functions 3/245
14.05% Lines 78/555

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842                                    2x 2x 2x 2x 2x 2x     2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x                                 2x 2x 2x     2x 2x 2x   2x   2x   2x   2x     2x                 2x                                                                             2x                           2x 2x                   2x                             2x                             2x                                   2x                               2x 2x               2x                             2x               2x                                                                                 2x           2x                                               2x                                         2x   2x               2x                                                   2x                         2x               2x                                     2x                         2x                                 2x                                                                                   2x                     2x                                                           2x                         2x                     2x                     2x                                                 2x                     2x                                                 2x                                                             2x                       2x                                     2x                 2x             2x             2x                                               2x                         2x             2x 2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
'use client';
 
import React, { useState, useEffect, useRef } from 'react';
import Image from 'next/image';
import { Section } from '../components/Section';
import { Product, AdminReview, AdminOrder, CategoryImage } from '../types';
import { CATEGORIES, CATEGORY_IMAGE_DEFAULTS } from '../constants';
import { signIn, signOut, useSession } from 'next-auth/react';
import { PlusCircle, Edit2, Trash2, Save, X, Star, Package, ArrowRight, ChevronDown, MessageSquare, Search } from 'lucide-react';
import { ImageUpload } from '../components/ImageUpload';
import { useToast } from '../context/ToastContext';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '../components/ui/dropdown-menu';
 
const AdminNew: React.FC = () => {
  const { data: session, status } = useSession();
  const { addToast } = useToast();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
 
  // Data states
  const [products, setProducts] = useState<Product[]>([]);
  const [reviews, setReviews] = useState<AdminReview[]>([]);
  const [orders, setOrders] = useState<AdminOrder[]>([]);
  const [categoryImages, setCategoryImages] = useState<CategoryImage[]>([]);
 
  // UI states
  const [activeTab, setActiveTab] = useState<'products' | 'reviews' | 'orders' | 'category-images'>('products');
  const [showProductForm, setShowProductForm] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [showCategoryImageForm, setShowCategoryImageForm] = useState(false);
  const [editingCategory, setEditingCategory] = useState<string>('');
  const [showReviewForm, setShowReviewForm] = useState(false);
  const [editingReview, setEditingReview] = useState<AdminReview | null>(null);
  const [showOrderForm, setShowOrderForm] = useState(false);
  const [editingOrder, setEditingOrder] = useState<AdminOrder | null>(null);
  const [expandedOrderId, setExpandedOrderId] = useState<string | null>(null);
  const [isNavOpen, setIsNavOpen] = useState(false);
  const navRef = useRef<HTMLDivElement | null>(null);
 
  // Form state
  const [formData, setFormData] = useState<Partial<Product>>({
    name: '',
    price: 0,
    category: '',
    subcategory: '',
    shortDescription: '',
    description: '',
    images: [],
    stock: 0,
    brand: '',
    isNew: false,
    isUsed: false,
    colors: null,
    sizes: null,
  });
 
  // Color management state
  const [useColorVariants, setUseColorVariants] = useState(false);
  const [colorForm, setColorForm] = useState({ name: '', hex: '#000000', stock: 0 });
  const [editingColorIndex, setEditingColorIndex] = useState<number | null>(null);
 
  // Size management state
  const [useSizeVariants, setUseSizeVariants] = useState(false);
  const [sizeForm, setSizeForm] = useState({ name: '', stock: 0 });
  const [editingSizeIndex, setEditingSizeIndex] = useState<number | null>(null);
  // Per-color stock for the size form (used when both sizes + colors are active)
  const [sizeFormColorStocks, setSizeFormColorStocks] = useState<Record<string, number>>({});
  // Compact color palette: toggle inline add-color form
  const [showColorPaletteForm, setShowColorPaletteForm] = useState(false);
  // Inline size name editing in matrix mode
  const [editingMatrixSizeName, setEditingMatrixSizeName] = useState<{ index: number; name: string } | null>(null);
  // Product search
  const [productSearch, setProductSearch] = useState('');
 
  // Category image form state
  const [categoryImageForm, setCategoryImageForm] = useState<{
    categoryName: string;
    imageUrl: string;
  }>({
    categoryName: '',
    imageUrl: '',
  });
 
  // Review form state
  const [reviewFormData, setReviewFormData] = useState<{
    author: string;
    rating: number;
    text: string;
    status: 'pending' | 'approved' | 'rejected';
  }>({
    author: '',
    rating: 5,
    text: '',
    status: 'pending',
  });
 
  type OrderFormItem = {
    productId: string;
    quantity: number;
    price: number;
    selectedColor?: string | null;
    selectedSize?: string | null;
    product: Product;
  };
 
  type OrderFormData = {
    customerName: string;
    customerEmail: string;
    customerPhone: string;
    customerAddress: string;
    customerCity: string;
    customerZip: string;
    shippingMethod: string;
    notes: string | null;
    total: number;
    status: AdminOrder['status'];
    items: OrderFormItem[];
  };
 
  type OrderItemEditableField = 'quantity' | 'price' | 'selectedColor' | 'selectedSize';
  type OrderItemFieldValue = OrderFormItem[OrderItemEditableField];
 
  // Order form state
  const [orderFormData, setOrderFormData] = useState<OrderFormData>({
    customerName: '',
    customerEmail: '',
    customerPhone: '',
    customerAddress: '',
    customerCity: '',
    customerZip: '',
    shippingMethod: '',
    notes: '' as string | null,
    total: 0,
    status: 'pending',
    items: [],
  });
 
  useEffect(() => {
    Eif (!isNavOpen) return;
    const handleClick = (event: MouseEvent) => {
      if (navRef.current && !navRef.current.contains(event.target as Node)) {
        setIsNavOpen(false);
      }
    };
    document.addEventListener('click', handleClick);
    return () => document.removeEventListener('click', handleClick);
  }, [isNavOpen]);
 
  const fetchProducts = React.useCallback(async () => {
    try {
      const res = await fetch('/api/products');
      if (!res.ok) {
        throw new Error(`Failed to fetch: ${res.status}`);
      }
      const data = await res.json();
      setProducts(Array.isArray(data) ? data : []);
    } catch (error) {
      console.error('Error fetching products:', error);
      addToast('Tuotteiden lataus epäonnistui', 'error');
      setProducts([]);
    }
  }, [addToast]);
 
  const fetchReviews = React.useCallback(async () => {
    try {
      const res = await fetch('/api/admin/reviews');
      if (!res.ok) {
        throw new Error(`Failed to fetch: ${res.status}`);
      }
      const data = await res.json();
      setReviews(Array.isArray(data) ? data : []);
    } catch (error) {
      console.error('Error fetching reviews:', error);
      addToast('Arvostelujen lataus epäonnistui', 'error');
      setReviews([]);
    }
  }, [addToast]);
 
  const fetchOrders = React.useCallback(async () => {
    try {
      // Fetch recent orders with optional pagination (default: all orders)
      const res = await fetch('/api/admin/orders?limit=100');
      if (!res.ok) {
        throw new Error(`Failed to fetch: ${res.status}`);
      }
      const data = await res.json();
      // Handle both old format (array) and new format (object with orders array)
      const ordersArray = Array.isArray(data) ? data : (data.orders || []);
      setOrders(ordersArray);
    } catch (error) {
      console.error('Error fetching orders:', error);
      addToast('Tilausten lataus epäonnistui', 'error');
      setOrders([]);
    }
  }, [addToast]);
 
  const fetchCategoryImages = React.useCallback(async () => {
    try {
      const res = await fetch('/api/category-images');
      if (!res.ok) {
        throw new Error(`Failed to fetch: ${res.status}`);
      }
      const data = await res.json();
      setCategoryImages(Array.isArray(data) ? data : []);
    } catch (error) {
      console.error('Error fetching category images:', error);
      addToast('Kategorioiden kuvien lataus epäonnistui', 'error');
      setCategoryImages([]);
    }
  }, [addToast]);
 
  // Load data when authenticated
  useEffect(() => {
    Iif (status === 'authenticated') {
      fetchProducts();
      fetchReviews();
      fetchOrders();
      fetchCategoryImages();
    }
  }, [status, fetchProducts, fetchReviews, fetchOrders, fetchCategoryImages]);
 
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
 
    const result = await signIn('credentials', {
      email,
      password,
      redirect: false,
    });
 
    if (result?.error) {
      setError('Virheellinen sähköposti tai salasana');
    }
  };
 
  const handleImagesChange = (newImages: string[]) => {
    setFormData(prev => ({
      ...prev,
      images: newImages,
    }));
  };
 
  // Color management functions
  const handleAddColor = () => {
    if (!colorForm.name) {
      addToast('Anna värin nimi', 'error');
      return;
    }
    // When sizes also exist, stock is managed per-size via colorStocks (ignore colorForm.stock)
    const bothActive = useSizeVariants && formData.sizes && formData.sizes.length > 0;
 
    const colors = formData.colors || [];
    if (editingColorIndex !== null) {
      const oldColorName = colors[editingColorIndex].name;
      const updatedColors = [...colors];
      updatedColors[editingColorIndex] = { ...colorForm, stock: bothActive ? 0 : colorForm.stock };
      // Sync: rename color in all sizes' colorStocks
      const updatedSizes = bothActive
        ? (formData.sizes || []).map(s => ({
            ...s,
            colorStocks: s.colorStocks?.map(cs =>
              cs.colorName === oldColorName ? { ...cs, colorName: colorForm.name } : cs
            ),
          }))
        : formData.sizes;
      setFormData(prev => ({ ...prev, colors: updatedColors, sizes: updatedSizes }));
      setEditingColorIndex(null);
    } else {
      const newColor = { ...colorForm, stock: bothActive ? 0 : colorForm.stock };
      // Sync: add new color to all sizes' colorStocks
      const updatedSizes = bothActive
        ? (formData.sizes || []).map(s => ({
            ...s,
            colorStocks: [...(s.colorStocks || []), { colorName: colorForm.name, stock: 0 }],
          }))
        : formData.sizes;
      setFormData(prev => ({ ...prev, colors: [...colors, newColor], sizes: updatedSizes }));
      // Also update sizeFormColorStocks for the add-size form
      setSizeFormColorStocks(prev => ({ ...prev, [colorForm.name]: 0 }));
    }
 
    setColorForm({ name: '', hex: '#000000', stock: 0 });
  };
 
  const handleEditColor = (index: number) => {
    const colors = formData.colors || [];
    setColorForm(colors[index]);
    setEditingColorIndex(index);
  };
 
  const handleDeleteColor = (index: number) => {
    const colors = formData.colors || [];
    const deletedColorName = colors[index].name;
    // Sync: remove deleted color from all sizes' colorStocks
    const bothActive = useSizeVariants && formData.sizes && formData.sizes.length > 0;
    const updatedSizes = bothActive
      ? (formData.sizes || []).map(s => ({
          ...s,
          colorStocks: s.colorStocks?.filter(cs => cs.colorName !== deletedColorName),
        }))
      : formData.sizes;
    setFormData(prev => ({
      ...prev,
      colors: colors.filter((_, i) => i !== index),
      sizes: updatedSizes,
    }));
    // Also remove from sizeFormColorStocks
    setSizeFormColorStocks(prev => {
      const next = { ...prev };
      delete next[deletedColorName];
      return next;
    });
  };
 
  const handleToggleColorVariants = (enabled: boolean) => {
    setUseColorVariants(enabled);
    if (!enabled) {
      // Remove colorStocks from all sizes when colors are turned off
      const updatedSizes = formData.sizes
        ? formData.sizes.map((size) => {
            const next = { ...size };
            delete next.colorStocks;
            return next;
          })
        : null;
      setFormData(prev => ({ ...prev, colors: null, sizes: updatedSizes }));
      setColorForm({ name: '', hex: '#000000', stock: 0 });
      setEditingColorIndex(null);
      setSizeFormColorStocks({});
    } else {
      setFormData(prev => ({ ...prev, colors: [] }));
    }
  };
 
  // Size management functions
  const bothVariantsActive = useColorVariants && useSizeVariants;
 
  const buildColorStocksForSize = (): { colorName: string; stock: number }[] | undefined => {
    if (!useColorVariants || !formData.colors?.length) return undefined;
    return formData.colors.map(c => ({
      colorName: c.name,
      stock: sizeFormColorStocks[c.name] || 0,
    }));
  };
 
  const handleAddSize = () => {
    if (!sizeForm.name) {
      addToast('Anna koon nimi', 'error');
      return;
    }
    const sizes = formData.sizes || [];
    const colorStocks = buildColorStocksForSize();
    const newSize = colorStocks
      ? { name: sizeForm.name, stock: 0, colorStocks }
      : { ...sizeForm };
 
    if (editingSizeIndex !== null) {
      const updatedSizes = [...sizes];
      updatedSizes[editingSizeIndex] = newSize;
      setFormData(prev => ({ ...prev, sizes: updatedSizes }));
      setEditingSizeIndex(null);
    } else {
      setFormData(prev => ({ ...prev, sizes: [...sizes, newSize] }));
    }
    setSizeForm({ name: '', stock: 0 });
    // Reset per-color stocks
    const resetStocks: Record<string, number> = {};
    formData.colors?.forEach(c => { resetStocks[c.name] = 0; });
    setSizeFormColorStocks(resetStocks);
  };
 
  const handleEditSize = (index: number) => {
    const sizes = formData.sizes || [];
    const size = sizes[index];
    setSizeForm({ name: size.name, stock: size.stock });
    // Populate per-color stocks if they exist
    if (size.colorStocks) {
      const stocks: Record<string, number> = {};
      size.colorStocks.forEach(cs => { stocks[cs.colorName] = cs.stock; });
      setSizeFormColorStocks(stocks);
    }
    setEditingSizeIndex(index);
  };
 
  const handleDeleteSize = (index: number) => {
    const sizes = formData.sizes || [];
    setFormData(prev => ({
      ...prev,
      sizes: sizes.filter((_, i) => i !== index),
    }));
  };
 
  const handleToggleSizeVariants = (enabled: boolean) => {
    setUseSizeVariants(enabled);
    if (!enabled) {
      setFormData(prev => ({ ...prev, sizes: null }));
      setSizeForm({ name: '', stock: 0 });
      setEditingSizeIndex(null);
      setSizeFormColorStocks({});
    } else {
      setFormData(prev => ({ ...prev, sizes: [] }));
      // Initialize per-color stocks from existing colors
      if (useColorVariants && formData.colors?.length) {
        const stocks: Record<string, number> = {};
        formData.colors.forEach(c => { stocks[c.name] = 0; });
        setSizeFormColorStocks(stocks);
      }
    }
  };
 
  // Inline matrix: directly update a cell in formData.sizes[sizeIndex].colorStocks
  const handleMatrixStockChange = (sizeIndex: number, colorName: string, value: number) => {
    setFormData(prev => {
      const sizes = [...(prev.sizes || [])];
      const size = { ...sizes[sizeIndex] };
      size.colorStocks = (size.colorStocks || []).map(cs =>
        cs.colorName === colorName ? { ...cs, stock: value } : cs
      );
      sizes[sizeIndex] = size;
      return { ...prev, sizes };
    });
  };
 
  // Compute total stock across all variants for a product
  const getTotalStock = (product: Product): number => {
    // Both: sum all colorStocks
    if (product.sizes?.length && product.colors?.length) {
      return product.sizes.reduce((total, s) =>
        total + (s.colorStocks?.reduce((sum, cs) => sum + cs.stock, 0) ?? s.stock), 0);
    }
    // Sizes only
    if (product.sizes?.length) {
      return product.sizes.reduce((sum, s) => sum + s.stock, 0);
    }
    // Colors only
    if (product.colors?.length) {
      return product.colors.reduce((sum, c) => sum + c.stock, 0);
    }
    return product.stock;
  };
 
  const handleSaveProduct = async () => {
    try {
      const url = editingProduct
        ? `/api/admin/products/${editingProduct.id}`
        : '/api/admin/products';
 
      const method = editingProduct ? 'PUT' : 'POST';
 
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });
 
      if (res.ok) {
        await fetchProducts();
        setShowProductForm(false);
        setEditingProduct(null);
        setUseColorVariants(false);
        setUseSizeVariants(false);
        setSizeFormColorStocks({});
        setFormData({
          name: '',
          price: 0,
          category: '',
          subcategory: '',
          shortDescription: '',
          description: '',
          images: [],
          stock: 0,
          brand: '',
          isNew: false,
          isUsed: false,
          colors: null,
          sizes: null,
        });
      }
    } catch (error) {
      console.error('Error saving product:', error);
    }
  };
 
  const handleDeleteProduct = async (id: string) => {
    if (!confirm('Haluatko varmasti poistaa tämän tuotteen?')) return;
 
    try {
      await fetch(`/api/admin/products/${id}`, { method: 'DELETE' });
      await fetchProducts();
    } catch (error) {
      console.error('Error deleting product:', error);
    }
  };
 
  const handleEditProduct = (product: Product) => {
    setEditingProduct(product);
    setFormData({
      ...product,
      brand: product.brand ?? '',
      category: product.category ?? '',
      subcategory: product.subcategory ?? '',
      shortDescription: product.shortDescription ?? '',
      description: product.description ?? '',
      images: product.images ?? [],
      stock: product.stock ?? 0,
      price: product.price ?? 0,
      isNew: product.isNew ?? false,
      isUsed: product.isUsed ?? false,
      colors: product.colors ?? null,
      sizes: product.sizes ?? null,
    });
    setUseColorVariants(!!product.colors && product.colors.length > 0);
    setUseSizeVariants(!!product.sizes && product.sizes.length > 0);
    // Initialize sizeFormColorStocks from first size's colorStocks (for the add form defaults)
    if (product.colors?.length) {
      const stocks: Record<string, number> = {};
      product.colors.forEach(c => { stocks[c.name] = 0; });
      setSizeFormColorStocks(stocks);
    } else {
      setSizeFormColorStocks({});
    }
    setShowProductForm(true);
  };
 
  const handleReviewAction = async (id: string, status: 'approved' | 'rejected') => {
    try {
      await fetch(`/api/admin/reviews/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status }),
      });
      await fetchReviews();
    } catch (error) {
      console.error('Error updating review:', error);
    }
  };
 
  const handleCreateReview = () => {
    setEditingReview(null);
    setReviewFormData({
      author: '',
      rating: 5,
      text: '',
      status: 'approved',
    });
    setShowReviewForm(true);
  };
 
  const handleEditReview = (review: AdminReview) => {
    setEditingReview(review);
    setReviewFormData({
      author: review.author,
      rating: review.rating,
      text: review.text,
      status: review.status,
    });
    setShowReviewForm(true);
  };
 
  const handleSaveReview = async () => {
    try {
      if (editingReview) {
        // Update existing review
        await fetch(`/api/admin/reviews/${editingReview.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(reviewFormData),
        });
      } else {
        // Create new review
        await fetch('/api/reviews', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(reviewFormData),
        });
      }
      await fetchReviews();
      setShowReviewForm(false);
      setEditingReview(null);
    } catch (error) {
      console.error('Error saving review:', error);
    }
  };
 
  const handleDeleteReview = async (id: string) => {
    if (!confirm('Haluatko varmasti poistaa tämän arvostelun?')) return;
 
    try {
      await fetch(`/api/admin/reviews/${id}`, { method: 'DELETE' });
      await fetchReviews();
    } catch (error) {
      console.error('Error deleting review:', error);
    }
  };
 
  const handleEditOrder = (order: AdminOrder) => {
    setEditingOrder(order);
    setOrderFormData({
      customerName: order.customerName,
      customerEmail: order.customerEmail,
      customerPhone: order.customerPhone,
      customerAddress: order.customerAddress,
      customerCity: order.customerCity,
      customerZip: order.customerZip,
      shippingMethod: order.shippingMethod,
      notes: order.notes || null,
      total: order.total,
      status: order.status,
      items: (order.items || []).map(item => ({
        productId: item.product.id,
        quantity: item.quantity,
        price: item.price,
        selectedColor: item.selectedColor || null,
        selectedSize: item.selectedSize || null,
        product: item.product,
      })),
    });
    setShowOrderForm(true);
  };
 
  const handleSaveOrder = async () => {
    if (!editingOrder) return;
    try {
      const res = await fetch(`/api/admin/orders/${editingOrder.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...orderFormData,
          items: orderFormData.items.map(item => ({
            productId: item.productId,
            quantity: item.quantity,
            price: item.price,
            selectedColor: item.selectedColor,
            selectedSize: item.selectedSize,
          })),
        }),
      });
      if (res.ok) {
        await fetchOrders();
        setShowOrderForm(false);
        setEditingOrder(null);
        addToast('Tilaus päivitetty', 'success');
      } else {
        addToast('Tilauksen päivitys epäonnistui', 'error');
      }
    } catch (error) {
      console.error('Error updating order:', error);
      addToast('Tilauksen päivitys epäonnistui', 'error');
    }
  };
 
  const handleDeleteOrder = async (id: string) => {
    if (!confirm('Haluatko varmasti poistaa tämän tilauksen?')) return;
    try {
      await fetch(`/api/admin/orders/${id}`, { method: 'DELETE' });
      await fetchOrders();
      addToast('Tilaus poistettu', 'success');
    } catch (error) {
      console.error('Error deleting order:', error);
      addToast('Tilauksen poisto epäonnistui', 'error');
    }
  };
 
  const handleQuickStatusChange = async (orderId: string, newStatus: AdminOrder['status']) => {
    try {
      const res = await fetch(`/api/admin/orders/${orderId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus }),
      });
      if (res.ok) {
        setOrders(prev => prev.map(o => o.id === orderId ? { ...o, status: newStatus } : o));
        addToast('Tila päivitetty', 'success');
      } else {
        addToast('Tilan päivitys epäonnistui', 'error');
      }
    } catch (error) {
      console.error('Error updating order status:', error);
      addToast('Tilan päivitys epäonnistui', 'error');
    }
  };
 
  const handleOrderItemChange = (index: number, field: OrderItemEditableField, value: OrderItemFieldValue) => {
    setOrderFormData(prev => ({
      ...prev,
      items: prev.items.map((item, i) =>
        i === index ? { ...item, [field]: value } : item
      ),
    }));
  };
 
  const handleRemoveOrderItem = (index: number) => {
    setOrderFormData(prev => ({
      ...prev,
      items: prev.items.filter((_, i) => i !== index),
    }));
  };
 
  const handleCategoryImageChange = (imageUrl: string) => {
    setCategoryImageForm(prev => ({
      ...prev,
      imageUrl,
    }));
  };
 
  const handleSaveCategoryImage = async () => {
    if (!categoryImageForm.categoryName || !categoryImageForm.imageUrl) {
      alert('Valitse kategoria ja lataa kuva');
      return;
    }
 
    try {
      const res = await fetch('/api/admin/category-images', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(categoryImageForm),
      });
 
      if (res.ok) {
        await fetchCategoryImages();
        setShowCategoryImageForm(false);
        setCategoryImageForm({ categoryName: '', imageUrl: '' });
        setEditingCategory('');
      }
    } catch (error) {
      console.error('Error saving category image:', error);
    }
  };
 
  const handleDeleteCategoryImage = async (categoryName: string) => {
    if (!confirm('Haluatko varmasti poistaa tämän kategorian kuvan?')) return;
 
    try {
      await fetch(`/api/admin/category-images/${encodeURIComponent(categoryName)}`, {
        method: 'DELETE',
      });
      await fetchCategoryImages();
    } catch (error) {
      console.error('Error deleting category image:', error);
    }
  };
 
  const handleEditCategoryImage = (categoryName: string, imageUrl: string) => {
    setEditingCategory(categoryName);
    setCategoryImageForm({ categoryName, imageUrl });
    setShowCategoryImageForm(true);
  };
 
  // Login screen
  Eif (status === 'unauthenticated') {
    return (
      <Section className="min-h-[50vh] flex items-center justify-center">
        <div className="w-full max-w-md bg-white p-8 rounded-2xl border border-gray-200 shadow-xl">
          <h2 className="text-2xl font-bold mb-6 text-center">Kirjaudu ylläpitoon</h2>
          {error && (
            <div className="mb-4 p-3 bg-red-100 text-red-700 rounded-xl text-sm">
              {error}
            </div>
          )}
          <form onSubmit={handleLogin} className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-2">Sähköposti</label>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="w-full p-3 border border-gray-200 rounded-xl focus:border-black transition-colors"
                placeholder="admin@varjoliitokauppa.fi"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-2">Salasana</label>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="w-full p-3 border border-gray-200 rounded-xl focus:border-black transition-colors"
                placeholder="••••••••"
                required
              />
            </div>
            <button
              type="submit"
              className="w-full bg-black text-white py-3 rounded-xl shadow-md hover:shadow-lg transition-all"
            >
              Kirjaudu
            </button>
          </form>
          <div className="mt-4 text-center text-sm text-gray-500">
            <p>Testikäyttäjä: admin@varjoliitokauppa.fi / admin123</p>
          </div>
        </div>
      </Section>
    );
  }
 
  if (status === 'loading') {
    return (
      <Section className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-black mx-auto mb-4"></div>
          <p>Ladataan...</p>
        </div>
      </Section>
    );
  }
 
  const pendingReviews = reviews.filter(r => r.status === 'pending');
  const activeOrders = orders.filter(o => o.status !== 'delivered' && o.status !== 'cancelled');
  const activeTabLabel = (() => {
    switch (activeTab) {
      case 'products':
        return `Tuotteet (${products.length})`;
      case 'reviews':
        return `Arvostelut (${pendingReviews.length})`;
      case 'orders':
        return `Tilaukset (${activeOrders.length})`;
      case 'category-images':
        return 'Kategorioiden kuvat';
      default:
        return 'Näkymä';
    }
  })();
 
  return (
    <Section variant="gray" className="min-h-screen">
      <div className="bg-white border border-gray-200 rounded-3xl shadow-sm p-4 sm:p-8">
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <h1 className="text-3xl font-bold">Hallintapaneeli</h1>
              <p className="text-sm text-gray-500 mt-1">Hallitse tuotteita, tilauksia ja sisältöä yhdessä paikassa.</p>
            </div>
            <div className="flex flex-wrap items-center gap-2 sm:gap-3">
              <div className="text-sm bg-gray-100 px-3 py-1 rounded-full border border-gray-200 break-all max-w-full">
                {session?.user?.email}
              </div>
              <button
                onClick={() => signOut()}
                className="text-sm text-red-600 hover:text-red-700"
              >
                Kirjaudu ulos
              </button>
            </div>
          </div>
 
          {/* Tabs */}
          <div className="mt-6">
            <div className="bg-gray-50 border border-gray-200 rounded-2xl p-3">
              <div className="sm:hidden relative" ref={navRef}>
                <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2">Näkymä</label>
                <button
                  type="button"
                  onClick={() => setIsNavOpen((prev) => !prev)}
                  className="w-full rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm font-semibold text-gray-900 flex items-center justify-between focus:outline-none focus:ring-2 focus:ring-black"
                  aria-expanded={isNavOpen}
                >
                  <span className="truncate">{activeTabLabel}</span>
                  <ChevronDown size={18} className={`transition-transform ${isNavOpen ? 'rotate-180' : ''}`} />
                </button>
                {isNavOpen && (
                  <div className="absolute z-20 mt-2 w-full rounded-xl border border-gray-200 bg-white shadow-lg overflow-hidden">
                    <button
                      onClick={() => { setActiveTab('products'); setIsNavOpen(false); }}
                      className="w-full text-left px-4 py-3 text-sm font-semibold hover:bg-gray-50"
                    >
                      Tuotteet ({products.length})
                    </button>
                    <button
                      onClick={() => { setActiveTab('reviews'); setIsNavOpen(false); }}
                      className="w-full text-left px-4 py-3 text-sm font-semibold hover:bg-gray-50"
                    >
                      Arvostelut ({pendingReviews.length})
                    </button>
                    <button
                      onClick={() => { setActiveTab('orders'); setIsNavOpen(false); }}
                      className="w-full text-left px-4 py-3 text-sm font-semibold hover:bg-gray-50"
                    >
                      Tilaukset ({activeOrders.length})
                    </button>
                    <button
                      onClick={() => { setActiveTab('category-images'); setIsNavOpen(false); }}
                      className="w-full text-left px-4 py-3 text-sm font-semibold hover:bg-gray-50"
                    >
                      Kategorioiden kuvat
                    </button>
                  </div>
                )}
              </div>
              <div className="hidden sm:flex gap-2 sm:gap-3 overflow-x-auto">
                <button
                  onClick={() => setActiveTab('products')}
                  className={`whitespace-nowrap rounded-full px-4 py-2 text-sm font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-black ${
                    activeTab === 'products'
                      ? 'bg-black text-white'
                      : 'text-gray-600 hover:bg-gray-100'
                  }`}
                >
                  Tuotteet ({products.length})
                </button>
                <button
                  onClick={() => setActiveTab('reviews')}
                  className={`whitespace-nowrap rounded-full px-4 py-2 text-sm font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-black ${
                    activeTab === 'reviews'
                      ? 'bg-black text-white'
                      : 'text-gray-600 hover:bg-gray-100'
                  }`}
                >
                  Arvostelut{pendingReviews.length > 0 && ` (${pendingReviews.length} odottaa)`}
                </button>
                <button
                  onClick={() => setActiveTab('orders')}
                  className={`whitespace-nowrap rounded-full px-4 py-2 text-sm font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-black ${
                    activeTab === 'orders'
                      ? 'bg-black text-white'
                      : 'text-gray-600 hover:bg-gray-100'
                  }`}
                >
                  Tilaukset{activeOrders.length > 0 && ` (${activeOrders.length})`}
                </button>
                <button
                  onClick={() => setActiveTab('category-images')}
                  className={`whitespace-nowrap rounded-full px-4 py-2 text-sm font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-black ${
                    activeTab === 'category-images'
                      ? 'bg-black text-white'
                      : 'text-gray-600 hover:bg-gray-100'
                  }`}
                >
                  Kategorioiden kuvat
                </button>
              </div>
            </div>
          </div>
 
          {/* Quick Stats */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mt-6">
            <div className="rounded-2xl border border-gray-200 bg-gray-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-wider text-gray-500">Tuotteita</div>
              <div className="text-2xl font-bold text-gray-900 mt-1">{products.length}</div>
            </div>
            <div className="rounded-2xl border border-gray-200 bg-gray-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-wider text-gray-500">Odottaa</div>
              <div className="text-2xl font-bold text-gray-900 mt-1">{pendingReviews.length}</div>
            </div>
            <div className="rounded-2xl border border-gray-200 bg-gray-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-wider text-gray-500">Aktiiviset</div>
              <div className="text-2xl font-bold text-gray-900 mt-1">{activeOrders.length}</div>
            </div>
            <div className="rounded-2xl border border-gray-200 bg-gray-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-wider text-gray-500">Kategoriat</div>
              <div className="text-2xl font-bold text-gray-900 mt-1">{CATEGORIES.length}</div>
            </div>
          </div>
 
      {/* Products Tab */}
      {activeTab === 'products' && (
        <div className="mt-6">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between mb-4">
            <div>
              <h2 className="text-2xl font-semibold">Tuotteet</h2>
              <p className="text-sm text-gray-500 mt-1">Päivitä tuotteiden tiedot, hinnat ja varastot.</p>
            </div>
          </div>
 
          {/* Product Form Modal */}
          {showProductForm && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-start sm:items-center justify-center z-50 p-0 sm:p-4">
              <div className="bg-white w-full sm:max-w-3xl h-[100dvh] sm:h-auto sm:max-h-[90vh] overflow-y-auto rounded-none sm:rounded-2xl">
                <div className="sticky top-0 z-10 bg-white border-b border-gray-100 px-4 sm:px-8 py-4 flex items-center justify-between">
                  <h3 className="text-xl sm:text-2xl font-bold">
                    {editingProduct ? 'Muokkaa tuotetta' : 'Lisää uusi tuote'}
                  </h3>
                  <button
                    onClick={() => {
                      setShowProductForm(false);
                      setUseColorVariants(false);
                      setUseSizeVariants(false);
                      setSizeFormColorStocks({});
                    }}
                    className="w-10 h-10 rounded-full border border-gray-200 flex items-center justify-center text-gray-500 hover:text-black hover:bg-gray-100 transition-colors"
                  >
                    <X size={18} />
                  </button>
                </div>
 
                <div className="p-4 sm:p-8 space-y-4">
                  <div>
                    <label className="block text-sm font-medium mb-2">Nimi</label>
                    <input
                      type="text"
                      value={formData.name ?? ''}
                      onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                      className="w-full p-3 border border-gray-200 rounded-xl"
                    />
                  </div>
 
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium mb-2">Hinta (€)</label>
                      <input
                        type="number"
                        value={formData.price ?? 0}
                        onChange={(e) => setFormData({ ...formData, price: parseFloat(e.target.value) })}
                        className="w-full p-3 border border-gray-200 rounded-xl"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-2">Alehinta (€)</label>
                      <input
                        type="number"
                        value={formData.salePrice ?? ''}
                        onChange={(e) => setFormData({ ...formData, salePrice: e.target.value ? parseFloat(e.target.value) : undefined })}
                        className="w-full p-3 border border-gray-200 rounded-xl"
                      />
                    </div>
                  </div>
 
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium mb-2">Kategoria</label>
                      <select
                        value={formData.category ?? ''}
                        onChange={(e) => setFormData({ ...formData, category: e.target.value })}
                        className="w-full p-3 border border-gray-200 rounded-xl"
                      >
                        <option value="">Valitse kategoria</option>
                        {CATEGORIES.map(cat => (
                          <option key={cat.name} value={cat.name}>{cat.name}</option>
                        ))}
                      </select>
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-2">Alakategoria</label>
                      <select
                        value={formData.subcategory ?? ''}
                        onChange={(e) => setFormData({ ...formData, subcategory: e.target.value })}
                        className="w-full p-3 border border-gray-200 rounded-xl"
                        disabled={!formData.category}
                      >
                        <option value="">Valitse alakategoria</option>
                        {CATEGORIES.find(c => c.name === formData.category)?.subcategories?.map(sub => (
                          <option key={sub} value={sub}>{sub}</option>
                        ))}
                      </select>
                    </div>
                  </div>
 
                  <div>
                    <label className="block text-sm font-medium mb-2">Lyhyt kuvaus</label>
                    <input
                      type="text"
                      value={formData.shortDescription ?? ''}
                      onChange={(e) => setFormData({ ...formData, shortDescription: e.target.value })}
                      className="w-full p-3 border border-gray-200 rounded-xl"
                    />
                  </div>
 
                  <div>
                    <label className="block text-sm font-medium mb-2">Kuvaus</label>
                    <textarea
                      value={formData.description ?? ''}
                      onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                      rows={4}
                      className="w-full p-3 border border-gray-200 rounded-xl"
                    />
                  </div>
 
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    {!useColorVariants && !useSizeVariants && (
                      <div>
                        <label className="block text-sm font-medium mb-2">Varastosaldo</label>
                        <input
                          type="number"
                          value={formData.stock ?? 0}
                          onChange={(e) => setFormData({ ...formData, stock: parseInt(e.target.value) })}
                          className="w-full p-3 border border-gray-200 rounded-xl"
                        />
                      </div>
                    )}
                    <div className={useColorVariants || useSizeVariants ? 'col-span-2' : ''}>
                      <label className="block text-sm font-medium mb-2">Merkki</label>
                      <input
                        type="text"
                        value={formData.brand ?? ''}
                        onChange={(e) => setFormData({ ...formData, brand: e.target.value })}
                        className="w-full p-3 border border-gray-200 rounded-xl"
                      />
                    </div>
                  </div>
 
                  <div className="flex flex-col sm:flex-row gap-4">
                    <label className="flex items-center gap-2">
                      <input
                        type="checkbox"
                        checked={formData.isNew}
                        onChange={(e) => setFormData({ ...formData, isNew: e.target.checked })}
                        className="rounded"
                      />
                      <span className="text-sm">Uutuus</span>
                    </label>
                    <label className="flex items-center gap-2">
                      <input
                        type="checkbox"
                        checked={formData.isUsed}
                        onChange={(e) => setFormData({ ...formData, isUsed: e.target.checked })}
                        className="rounded"
                      />
                      <span className="text-sm">Käytetty</span>
                    </label>
                  </div>
 
                  {formData.isUsed && (
                    <div>
                      <label className="block text-sm font-medium mb-2">Kunto</label>
                      <input
                        type="text"
                        value={formData.condition ?? ''}
                        onChange={(e) => setFormData({ ...formData, condition: e.target.value })}
                        className="w-full p-3 border border-gray-200 rounded-xl"
                      />
                    </div>
                  )}
 
                  {/* === Unified Variants & Stock Section === */}
                  <div className="border-t border-gray-200 pt-6 mt-6">
                    <h3 className="text-lg font-bold mb-1">Variantit & Varastonhallinta</h3>
                    <p className="text-sm text-gray-500 mb-4">
                      {!useColorVariants && !useSizeVariants
                        ? 'Aktivoi väri- tai kokovaihtoehdot hallitaksesi varastoa varianttikohtaisesti.'
                        : bothVariantsActive
                        ? 'Varastosaldot hallitaan koko × väri -matriisina alla.'
                        : useColorVariants
                        ? 'Varastosaldot hallitaan värikohtaisesti.'
                        : 'Varastosaldot hallitaan kokokohtaisesti.'}
                    </p>
 
                    {/* Side-by-side compact toggles */}
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 mb-6">
                      <label className={`flex items-center gap-3 p-3 rounded-xl border-2 cursor-pointer transition-all ${useColorVariants ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-gray-300'}`}>
                        <input
                          type="checkbox"
                          checked={useColorVariants}
                          onChange={(e) => handleToggleColorVariants(e.target.checked)}
                          className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                        />
                        <div>
                          <div className="font-semibold text-sm text-gray-900">Värivaihtoehdot</div>
                          <div className="text-xs text-gray-500">Eri värit tuotteelle</div>
                        </div>
                      </label>
                      <label className={`flex items-center gap-3 p-3 rounded-xl border-2 cursor-pointer transition-all ${useSizeVariants ? 'border-green-500 bg-green-50' : 'border-gray-200 hover:border-gray-300'}`}>
                        <input
                          type="checkbox"
                          checked={useSizeVariants}
                          onChange={(e) => handleToggleSizeVariants(e.target.checked)}
                          className="w-5 h-5 rounded border-gray-300 text-green-600 focus:ring-green-500"
                        />
                        <div>
                          <div className="font-semibold text-sm text-gray-900">Kokovaihtoehdot</div>
                          <div className="text-xs text-gray-500">Eri koot tuotteelle</div>
                        </div>
                      </label>
                    </div>
 
                    {/* Color Management */}
                    {useColorVariants && (
                      bothVariantsActive ? (
                        /* === COLOR MANAGEMENT CARD (when both variants active) === */
                        <div className="mb-6">
                          <div className="bg-gray-50 border border-gray-200 rounded-xl p-5 space-y-4">
                            {/* Header row */}
                            <div className="flex items-center justify-between">
                              <h4 className="font-semibold text-gray-900 flex items-center gap-2">
                                Värit
                                {formData.colors && formData.colors.length > 0 && (
                                  <span className="text-xs font-medium text-gray-500 bg-gray-200 rounded-full px-2 py-0.5">
                                    {formData.colors.length}
                                  </span>
                                )}
                              </h4>
                              {!showColorPaletteForm && (
                                <button
                                  type="button"
                                  onClick={() => { setShowColorPaletteForm(true); setEditingColorIndex(null); setColorForm({ name: '', hex: '#000000', stock: 0 }); }}
                                  className="flex items-center gap-1.5 text-sm font-medium text-blue-600 hover:text-blue-800 transition-colors"
                                >
                                  <PlusCircle size={16} />
                                  Lisää väri
                                </button>
                              )}
                            </div>
 
                            {/* Color chips list */}
                            {formData.colors && formData.colors.length > 0 && (
                              <div className="flex items-center flex-wrap gap-2">
                                {formData.colors.map((color, index) => (
                                  <div
                                    key={index}
                                    className={`flex items-center gap-2 bg-white border rounded-lg px-3 py-2 text-sm transition-colors group ${
                                      editingColorIndex === index ? 'border-blue-400 ring-2 ring-blue-100' : 'border-gray-200 hover:border-gray-300'
                                    }`}
                                  >
                                    <div
                                      className="w-6 h-6 rounded-full border border-gray-300 flex-shrink-0 shadow-sm"
                                      style={{ backgroundColor: color.hex }}
                                    />
                                    <span className="font-medium text-gray-800">{color.name}</span>
                                    <span className="text-xs text-gray-400 font-mono">{color.hex}</span>
                                    <div className="flex items-center gap-0.5 ml-1">
                                      <button
                                        type="button"
                                        onClick={() => { handleEditColor(index); setShowColorPaletteForm(true); }}
                                        className="p-1 text-gray-400 hover:text-blue-600 rounded transition-colors"
                                        title="Muokkaa väriä"
                                      >
                                        <Edit2 size={14} />
                                      </button>
                                      <button
                                        type="button"
                                        onClick={() => handleDeleteColor(index)}
                                        className="p-1 text-gray-400 hover:text-red-500 rounded transition-colors"
                                        title="Poista väri"
                                      >
                                        <X size={14} />
                                      </button>
                                    </div>
                                  </div>
                                ))}
                              </div>
                            )}
 
                            {/* Empty state */}
                            {(!formData.colors || formData.colors.length === 0) && !showColorPaletteForm && (
                              <p className="text-sm text-gray-400">Ei värejä. Lisää ensimmäinen väri aloittaaksesi.</p>
                            )}
 
                            {/* Add/Edit form as separate sub-card */}
                            {showColorPaletteForm && (
                              <div className="bg-white border border-gray-200 rounded-xl p-4">
                                <div className="flex items-center gap-2 mb-3">
                                  {editingColorIndex !== null
                                    ? <Edit2 size={16} className="text-blue-600" />
                                    : <PlusCircle size={16} className="text-blue-600" />
                                  }
                                  <span className="text-sm font-semibold text-gray-700">
                                    {editingColorIndex !== null ? 'Muokkaa väriä' : 'Uusi väri'}
                                  </span>
                                </div>
                                <div className="flex flex-col sm:flex-row sm:items-end gap-3">
                                  <div>
                                    <label className="block text-xs font-medium text-gray-500 mb-1">Väri</label>
                                    <input
                                      type="color"
                                      value={colorForm.hex}
                                      onChange={(e) => setColorForm({ ...colorForm, hex: e.target.value })}
                                      className="w-12 h-10 border border-gray-300 rounded-lg cursor-pointer"
                                    />
                                  </div>
                                  <div className="flex-1 min-w-0">
                                    <label className="block text-xs font-medium text-gray-500 mb-1">Nimi</label>
                                    <input
                                      type="text"
                                      placeholder="esim. Punainen"
                                      value={colorForm.name}
                                      onChange={(e) => setColorForm({ ...colorForm, name: e.target.value })}
                                      onKeyDown={(e) => {
                                        if (e.key === 'Enter') { handleAddColor(); setShowColorPaletteForm(false); setEditingColorIndex(null); }
                                      }}
                                      className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                      autoFocus
                                    />
                                  </div>
                                  <div className="w-full sm:w-24">
                                    <label className="block text-xs font-medium text-gray-500 mb-1">Koodi</label>
                                    <input
                                      type="text"
                                      value={colorForm.hex}
                                      onChange={(e) => setColorForm({ ...colorForm, hex: e.target.value })}
                                      className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                    />
                                  </div>
                                  <div className="flex flex-col sm:flex-row gap-2 flex-shrink-0">
                                    <button
                                      type="button"
                                      onClick={() => { handleAddColor(); setShowColorPaletteForm(false); setEditingColorIndex(null); }}
                                      className="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-1.5"
                                    >
                                      <Save size={14} />
                                      {editingColorIndex !== null ? 'Päivitä' : 'Lisää'}
                                    </button>
                                    <button
                                      type="button"
                                      onClick={() => { setShowColorPaletteForm(false); setEditingColorIndex(null); setColorForm({ name: '', hex: '#000000', stock: 0 }); }}
                                      className="px-3 py-2 text-gray-500 hover:text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-100 transition-colors"
                                    >
                                      Peruuta
                                    </button>
                                  </div>
                                </div>
                              </div>
                            )}
                          </div>
                        </div>
                      ) : (
                        /* === FULL COLOR FORM (when colors-only, no sizes) === */
                        <div className="space-y-4 mb-4">
                          <div className="bg-gray-50 border border-gray-200 p-5 rounded-xl space-y-4">
                            <h4 className="font-semibold text-gray-900">Lisää värivaihtoehto</h4>
                            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                              <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                  Värin nimi <span className="text-red-500">*</span>
                                </label>
                                <input
                                  type="text"
                                  placeholder="esim. Punainen"
                                  value={colorForm.name}
                                  onChange={(e) => setColorForm({ ...colorForm, name: e.target.value })}
                                  className="w-full p-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                />
                              </div>
                              <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">Värikoodi</label>
                                <div className="flex gap-2">
                                  <input
                                    type="color"
                                    value={colorForm.hex}
                                    onChange={(e) => setColorForm({ ...colorForm, hex: e.target.value })}
                                    className="w-14 h-11 border border-gray-300 rounded-lg cursor-pointer"
                                  />
                                  <input
                                    type="text"
                                    value={colorForm.hex}
                                    onChange={(e) => setColorForm({ ...colorForm, hex: e.target.value })}
                                    className="flex-1 p-3 border border-gray-300 rounded-lg text-sm font-mono focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                    placeholder="#000000"
                                  />
                                </div>
                              </div>
                              <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                  Varastosaldo <span className="text-red-500">*</span>
                                </label>
                                <input
                                  type="number"
                                  value={colorForm.stock}
                                  onChange={(e) => setColorForm({ ...colorForm, stock: parseInt(e.target.value) || 0 })}
                                  className="w-full p-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                  min="0"
                                  placeholder="0"
                                />
                              </div>
                            </div>
                            <button
                              type="button"
                              onClick={handleAddColor}
                              className="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 transition-all font-medium shadow-sm hover:shadow-md"
                            >
                              {editingColorIndex !== null ? '✓ Päivitä väri' : '+ Lisää väri'}
                            </button>
                          </div>
 
                          {/* Color List */}
                          {formData.colors && formData.colors.length > 0 ? (
                            <div className="space-y-2">
                              <h4 className="font-semibold text-gray-900 mb-3">
                                Lisätyt värit ({formData.colors.length})
                              </h4>
                              {formData.colors.map((color, index) => (
                                <div key={index} className="flex items-center gap-4 p-4 bg-white border border-gray-200 rounded-lg hover:border-gray-300 transition-colors">
                                  <div
                                    className="w-10 h-10 rounded-lg border-2 border-gray-300 shadow-sm flex-shrink-0"
                                    style={{ backgroundColor: color.hex }}
                                    title={color.hex}
                                  />
                                  <div className="flex-1 min-w-0">
                                    <div className="font-semibold text-gray-900">{color.name}</div>
                                    <div className="text-sm text-gray-500 mt-0.5">
                                      <span className="font-mono">{color.hex}</span>
                                      {' '} • <span className="font-medium text-gray-700">{color.stock} kpl</span> varastossa
                                    </div>
                                  </div>
                                  <div className="flex gap-1">
                                    <button
                                      type="button"
                                      onClick={() => handleEditColor(index)}
                                      className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-all"
                                      title="Muokkaa"
                                    >
                                      <Edit2 size={18} />
                                    </button>
                                    <button
                                      type="button"
                                      onClick={() => handleDeleteColor(index)}
                                      className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-all"
                                      title="Poista"
                                    >
                                      <Trash2 size={18} />
                                    </button>
                                  </div>
                                </div>
                              ))}
                            </div>
                          ) : (
                            <div className="text-center py-8 border-2 border-dashed border-gray-300 rounded-xl bg-gray-50">
                              <p className="text-gray-500 text-sm">
                                Ei vielä lisättyjä värejä. Lisää ensimmäinen värivaihtoehto yllä olevalla lomakkeella.
                              </p>
                            </div>
                          )}
                        </div>
                      )
                    )}
 
                  {/* Size Variants Content */}
                  {useSizeVariants && (
                    bothVariantsActive ? (
                      /* === BOTH VARIANTS: Size Card + Matrix Card === */
                      <div className="space-y-6">
                        {/* SIZE MANAGEMENT CARD */}
                        <div className="bg-gray-50 border border-gray-200 rounded-xl p-5 space-y-4">
                          {/* Header */}
                          <h4 className="font-semibold text-gray-900 flex items-center gap-2">
                            Koot
                            {formData.sizes && formData.sizes.length > 0 && (
                              <span className="text-xs font-medium text-gray-500 bg-gray-200 rounded-full px-2 py-0.5">
                                {formData.sizes.length}
                              </span>
                            )}
                          </h4>
 
                          {/* Quick add: standard sizes */}
                          <div>
                            <label className="block text-xs font-medium text-gray-500 mb-2">Vakiokoot</label>
                            <div className="flex flex-wrap gap-2">
                              {['XS', 'S', 'SM', 'M', 'ML', 'L', 'XL', 'XXL'].map(sizeName => (
                                <button
                                  key={sizeName}
                                  type="button"
                                  onClick={() => {
                                    const sizes = formData.sizes || [];
                                    if (!sizes.find(s => s.name === sizeName)) {
                                      const colorStocks = formData.colors?.length
                                        ? formData.colors.map(c => ({ colorName: c.name, stock: 0 }))
                                        : undefined;
                                      const newSize = colorStocks
                                        ? { name: sizeName, stock: 0, colorStocks }
                                        : { name: sizeName, stock: 0 };
                                      setFormData(prev => ({ ...prev, sizes: [...sizes, newSize] }));
                                    }
                                  }}
                                  disabled={formData.sizes?.some(s => s.name === sizeName)}
                                  className="px-3.5 py-2 text-sm font-semibold border border-gray-300 rounded-lg hover:bg-green-50 hover:border-green-400 hover:text-green-700 transition-all disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:border-gray-300"
                                >
                                  {sizeName}
                                </button>
                              ))}
                            </div>
                          </div>
 
                          {/* Divider with "tai" */}
                          <div className="flex items-center gap-3">
                            <div className="flex-1 border-t border-gray-200"></div>
                            <span className="text-xs font-medium text-gray-400 uppercase">tai</span>
                            <div className="flex-1 border-t border-gray-200"></div>
                          </div>
 
                          {/* Custom size input */}
                          <div>
                            <label className="block text-xs font-medium text-gray-500 mb-2">Oma koko</label>
                            <div className="flex flex-col sm:flex-row sm:items-center gap-2">
                              <input
                                type="text"
                                placeholder="esim. 28, 32, XXS..."
                                value={sizeForm.name}
                                onChange={(e) => setSizeForm({ ...sizeForm, name: e.target.value })}
                                onKeyDown={(e) => {
                                  if (e.key === 'Enter' && sizeForm.name.trim()) {
                                    const sizes = formData.sizes || [];
                                    if (!sizes.find(s => s.name === sizeForm.name.trim())) {
                                      const colorStocks = formData.colors?.length
                                        ? formData.colors.map(c => ({ colorName: c.name, stock: 0 }))
                                        : undefined;
                                      const newSize = colorStocks
                                        ? { name: sizeForm.name.trim(), stock: 0, colorStocks }
                                        : { name: sizeForm.name.trim(), stock: 0 };
                                      setFormData(prev => ({ ...prev, sizes: [...sizes, newSize] }));
                                      setSizeForm({ name: '', stock: 0 });
                                    } else {
                                      addToast('Tämä koko on jo lisätty', 'error');
                                    }
                                  }
                                }}
                                className="w-full sm:w-40 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 focus:border-green-500"
                              />
                              <button
                                type="button"
                                onClick={() => {
                                  if (!sizeForm.name.trim()) return;
                                  const sizes = formData.sizes || [];
                                  if (!sizes.find(s => s.name === sizeForm.name.trim())) {
                                    const colorStocks = formData.colors?.length
                                      ? formData.colors.map(c => ({ colorName: c.name, stock: 0 }))
                                      : undefined;
                                    const newSize = colorStocks
                                      ? { name: sizeForm.name.trim(), stock: 0, colorStocks }
                                      : { name: sizeForm.name.trim(), stock: 0 };
                                    setFormData(prev => ({ ...prev, sizes: [...sizes, newSize] }));
                                    setSizeForm({ name: '', stock: 0 });
                                  } else {
                                    addToast('Tämä koko on jo lisätty', 'error');
                                  }
                                }}
                                disabled={!sizeForm.name.trim()}
                                className="px-4 py-2 text-sm font-medium bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-40 disabled:cursor-not-allowed flex items-center gap-1.5"
                              >
                                <PlusCircle size={14} />
                                Lisää
                              </button>
                            </div>
                          </div>
                        </div>
 
                        {/* STOCK MATRIX CARD */}
                        {formData.sizes && formData.sizes.length > 0 && formData.colors && formData.colors.length > 0 ? (
                          <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
                            {/* Card header */}
                            <div className="px-5 py-4 border-b border-gray-100 bg-gray-50">
                              <h4 className="font-semibold text-gray-900 flex items-center gap-2">
                                <Package size={18} className="text-gray-500" />
                                Varastomatriisi
                                <span className="text-xs font-medium text-gray-500">
                                  {formData.sizes.length} kokoa &times; {formData.colors.length} väriä
                                </span>
                              </h4>
                              <p className="text-xs text-gray-500 mt-1">
                                Syötä varastosaldo jokaiselle koko-väri-yhdistelmälle.
                              </p>
                            </div>
 
                            {/* Table */}
                            <div className="overflow-x-auto">
                              <table className="w-full border-collapse">
                                <thead>
                                  <tr className="bg-gray-50/50">
                                    <th className="text-left text-xs font-bold text-gray-500 uppercase tracking-wider px-4 py-3 w-28 border-b border-gray-100">Koko</th>
                                    {formData.colors.map(color => (
                                      <th key={color.name} className="text-center px-3 py-3 min-w-[90px] border-b border-gray-100">
                                        <div className="flex items-center justify-center gap-1.5">
                                          <div className="w-4 h-4 rounded-full border border-gray-300 flex-shrink-0 shadow-sm" style={{ backgroundColor: color.hex }} />
                                          <span className="text-xs font-semibold text-gray-700">{color.name}</span>
                                        </div>
                                      </th>
                                    ))}
                                    <th className="text-center text-xs font-bold text-gray-400 uppercase px-3 py-3 w-16 border-b border-gray-100">Yht</th>
                                    <th className="w-12 border-b border-gray-100"></th>
                                  </tr>
                                </thead>
                                <tbody>
                                  {formData.sizes.map((size, sizeIndex) => {
                                    const rowTotal = size.colorStocks?.reduce((sum, cs) => sum + cs.stock, 0) ?? 0;
                                    return (
                                      <tr key={sizeIndex} className="border-b border-gray-50 hover:bg-blue-50/30 transition-colors">
                                        {/* Size name cell — fixed width container prevents jitter */}
                                        <td className="px-4 py-2.5">
                                          <div className="w-20 h-9 relative">
                                            {editingMatrixSizeName?.index === sizeIndex ? (
                                              <input
                                                type="text"
                                                value={editingMatrixSizeName.name}
                                                onChange={(e) => setEditingMatrixSizeName({ index: sizeIndex, name: e.target.value })}
                                                onBlur={() => {
                                                  if (editingMatrixSizeName.name.trim() && editingMatrixSizeName.name.trim() !== size.name) {
                                                    setFormData(prev => {
                                                      const sizes = [...(prev.sizes || [])];
                                                      sizes[sizeIndex] = { ...sizes[sizeIndex], name: editingMatrixSizeName.name.trim() };
                                                      return { ...prev, sizes };
                                                    });
                                                  }
                                                  setEditingMatrixSizeName(null);
                                                }}
                                                onKeyDown={(e) => {
                                                  if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
                                                  if (e.key === 'Escape') setEditingMatrixSizeName(null);
                                                }}
                                                className="absolute inset-0 w-full h-full text-center bg-white border-2 border-blue-400 rounded-lg font-bold text-sm text-gray-800 focus:ring-2 focus:ring-blue-200 outline-none"
                                                autoFocus
                                              />
                                            ) : (
                                              <button
                                                type="button"
                                                onClick={() => setEditingMatrixSizeName({ index: sizeIndex, name: size.name })}
                                                className="absolute inset-0 w-full h-full flex items-center justify-center bg-gray-100 rounded-lg font-bold text-sm text-gray-700 border border-gray-200 hover:border-blue-400 hover:bg-blue-50 cursor-pointer transition-colors"
                                                title="Muokkaa koon nimeä"
                                              >
                                                {size.name}
                                              </button>
                                            )}
                                          </div>
                                        </td>
                                        {/* Stock input cells */}
                                        {formData.colors!.map(color => {
                                          const cs = size.colorStocks?.find(c => c.colorName === color.name);
                                          const val = cs?.stock ?? 0;
                                          return (
                                            <td key={color.name} className="px-2 py-2.5 text-center">
                                              <input
                                                type="number"
                                                value={val}
                                                onChange={(e) => handleMatrixStockChange(sizeIndex, color.name, parseInt(e.target.value) || 0)}
                                                className={`w-16 mx-auto px-2 py-1.5 border rounded-lg text-sm text-center font-medium focus:ring-2 focus:ring-green-500 focus:border-green-500 ${
                                                  val === 0 ? 'border-red-200 bg-red-50/50 text-red-400' : 'border-gray-200 text-gray-900 bg-white'
                                                }`}
                                                min="0"
                                              />
                                            </td>
                                          );
                                        })}
                                        {/* Row total */}
                                        <td className="px-3 py-2.5 text-center">
                                          <span className={`text-sm font-bold ${rowTotal === 0 ? 'text-red-400' : 'text-gray-700'}`}>
                                            {rowTotal}
                                          </span>
                                        </td>
                                        {/* Delete button */}
                                        <td className="px-2 py-2.5 text-center">
                                          <button
                                            type="button"
                                            onClick={() => handleDeleteSize(sizeIndex)}
                                            className="p-1.5 text-gray-300 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                                            title="Poista koko"
                                          >
                                            <Trash2 size={14} />
                                          </button>
                                        </td>
                                      </tr>
                                    );
                                  })}
                                </tbody>
                                <tfoot>
                                  <tr className="border-t-2 border-gray-200 bg-gray-50/50">
                                    <td className="px-4 py-3 text-xs font-bold text-gray-400 uppercase">Yhteensä</td>
                                    {formData.colors.map(color => {
                                      const colTotal = formData.sizes?.reduce((sum, s) =>
                                        sum + (s.colorStocks?.find(cs => cs.colorName === color.name)?.stock ?? 0), 0) ?? 0;
                                      return (
                                        <td key={color.name} className="px-3 py-3 text-center">
                                          <span className={`text-sm font-bold ${colTotal === 0 ? 'text-red-400' : 'text-gray-600'}`}>{colTotal}</span>
                                        </td>
                                      );
                                    })}
                                    <td className="px-3 py-3 text-center">
                                      <span className="text-sm font-black text-gray-900">
                                        {formData.sizes?.reduce((total, s) =>
                                          total + (s.colorStocks?.reduce((sum, cs) => sum + cs.stock, 0) ?? 0), 0) ?? 0}
                                      </span>
                                    </td>
                                    <td></td>
                                  </tr>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        ) : (
                          <div className="text-center py-8 border-2 border-dashed border-gray-300 rounded-xl bg-gray-50">
                            <Package size={24} className="mx-auto text-gray-300 mb-2" />
                            <p className="text-gray-500 text-sm">
                              {(!formData.colors || formData.colors.length === 0)
                                ? 'Lisää ensin värit, sitten varastomatriisi näkyy täällä.'
                                : 'Lisää kokoja yllä olevasta kortista.'}
                            </p>
                          </div>
                        )}
                      </div>
                    ) : (
                      /* === SIZES-ONLY: Original form + list (no matrix) === */
                      <div className="space-y-4 mt-2">
                        {/* Size Quick Add Buttons */}
                        <div className="flex flex-wrap gap-2">
                          <span className="text-xs font-medium text-gray-500 w-full">Pikalisäys:</span>
                          {['XS', 'S', 'SM', 'M', 'ML', 'L', 'XL', 'XXL'].map(sizeName => (
                            <button
                              key={sizeName}
                              type="button"
                              onClick={() => {
                                const sizes = formData.sizes || [];
                                if (!sizes.find(s => s.name === sizeName)) {
                                  setFormData(prev => ({ ...prev, sizes: [...sizes, { name: sizeName, stock: 0 }] }));
                                }
                              }}
                              disabled={formData.sizes?.some(s => s.name === sizeName)}
                              className="px-3 py-1.5 text-xs font-bold border border-gray-300 rounded-lg hover:bg-green-50 hover:border-green-400 transition-all disabled:opacity-30 disabled:cursor-not-allowed"
                            >
                              {sizeName}
                            </button>
                          ))}
                        </div>
 
                        {/* Size Form */}
                        <div className="bg-gray-50 border border-gray-200 p-5 rounded-xl space-y-4">
                          <h4 className="font-semibold text-gray-900">Lisää kokovaihtoehto</h4>
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                              <label className="block text-sm font-medium text-gray-700 mb-2">
                                Koon nimi <span className="text-red-500">*</span>
                              </label>
                              <input
                                type="text"
                                placeholder="esim. M, L, XL"
                                value={sizeForm.name}
                                onChange={(e) => setSizeForm({ ...sizeForm, name: e.target.value })}
                                className="w-full p-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 focus:border-green-500"
                              />
                            </div>
                            <div>
                              <label className="block text-sm font-medium text-gray-700 mb-2">
                                Varastosaldo <span className="text-red-500">*</span>
                              </label>
                              <input
                                type="number"
                                value={sizeForm.stock}
                                onChange={(e) => setSizeForm({ ...sizeForm, stock: parseInt(e.target.value) || 0 })}
                                className="w-full p-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 focus:border-green-500"
                                min="0"
                                placeholder="0"
                              />
                            </div>
                          </div>
                          <button
                            type="button"
                            onClick={handleAddSize}
                            className="w-full bg-green-600 text-white py-3 rounded-lg hover:bg-green-700 transition-all font-medium shadow-sm hover:shadow-md"
                          >
                            {editingSizeIndex !== null ? '✓ Päivitä koko' : '+ Lisää koko'}
                          </button>
                        </div>
 
                        {/* Size List */}
                        {formData.sizes && formData.sizes.length > 0 ? (
                          <div className="space-y-2">
                            <h4 className="font-semibold text-gray-900 mb-3">
                              Lisätyt koot ({formData.sizes.length})
                            </h4>
                            {formData.sizes.map((size, index) => (
                              <div key={index} className="flex items-center gap-4 p-4 bg-white border border-gray-200 rounded-lg hover:border-gray-300 transition-colors">
                                <div className="w-10 h-10 rounded-lg border-2 border-gray-300 shadow-sm flex-shrink-0 bg-gray-100 flex items-center justify-center font-bold text-sm text-gray-700">
                                  {size.name}
                                </div>
                                <div className="flex-1 min-w-0">
                                  <div className="font-semibold text-gray-900">{size.name}</div>
                                  <div className="text-sm text-gray-500 mt-0.5">
                                    <span className="font-medium text-gray-700">{size.stock} kpl</span> varastossa
                                  </div>
                                </div>
                                <div className="flex gap-1">
                                  <button
                                    type="button"
                                    onClick={() => handleEditSize(index)}
                                    className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-all"
                                    title="Muokkaa"
                                  >
                                    <Edit2 size={18} />
                                  </button>
                                  <button
                                    type="button"
                                    onClick={() => handleDeleteSize(index)}
                                    className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-all"
                                    title="Poista"
                                  >
                                    <Trash2 size={18} />
                                  </button>
                                </div>
                              </div>
                            ))}
                          </div>
                        ) : (
                          <div className="text-center py-8 border-2 border-dashed border-gray-300 rounded-xl bg-gray-50">
                            <p className="text-gray-500 text-sm">
                              Ei vielä lisättyjä kokoja. Käytä pikalisäystä tai lisää kokovaihtoehto yllä olevalla lomakkeella.
                            </p>
                          </div>
                        )}
                      </div>
                    )
                  )}
                  </div>
 
                  <ImageUpload
                    images={formData.images || []}
                    onImagesChange={handleImagesChange}
                    maxImages={10}
                  />
 
                  <div className="flex flex-col sm:flex-row gap-4 pt-4">
                    <button
                      onClick={handleSaveProduct}
                      className="flex-1 bg-black text-white py-3 rounded-xl hover:shadow-lg transition-all flex items-center justify-center gap-2"
                    >
                      <Save size={20} />
                      Tallenna
                    </button>
                    <button
                      onClick={() => {
                        setShowProductForm(false);
                        setUseColorVariants(false);
                        setUseSizeVariants(false);
                        setSizeFormColorStocks({});
                      }}
                      className="flex-1 bg-gray-200 text-gray-700 py-3 rounded-xl hover:bg-gray-300 transition-all"
                    >
                      Peruuta
                    </button>
                  </div>
                </div>
              </div>
            </div>
          )}
 
          {/* Product Toolbar */}
          <div className="bg-gray-50 border border-gray-200 rounded-2xl p-3 sm:p-4 mb-4">
            <div className="flex flex-col sm:flex-row gap-3 sm:items-center sm:justify-between">
              <div className="relative flex-1">
                <Search size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                <input
                  type="text"
                  placeholder="Hae tuotetta nimellä..."
                  value={productSearch}
                  onChange={(e) => setProductSearch(e.target.value)}
                  className="w-full pl-10 pr-4 py-3 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-black focus:border-black bg-white transition-colors"
                />
              </div>
              <button
                onClick={() => {
                  setShowProductForm(true);
                  setEditingProduct(null);
                  setUseColorVariants(false);
                  setUseSizeVariants(false);
                  setSizeFormColorStocks({});
                  setFormData({
                    name: '',
                    price: 0,
                    category: '',
                    subcategory: '',
                    shortDescription: '',
                    description: '',
                    images: [],
                    stock: 0,
                    brand: '',
                    isNew: false,
                    isUsed: false,
                    colors: null,
                    sizes: null,
                  });
                }}
                className="flex w-full sm:w-auto items-center justify-center gap-2 bg-black text-white px-4 py-2.5 rounded-xl hover:shadow-lg transition-all"
              >
                <PlusCircle size={20} />
                Lisää uusi tuote
              </button>
            </div>
          </div>
 
          {/* Products List */}
          <div className="grid gap-4">
            {products
              .filter(p => !productSearch || p.name.toLowerCase().includes(productSearch.toLowerCase()))
              .map(product => {
                const totalStock = getTotalStock(product);
                const hasColors = !!(product.colors && product.colors.length > 0);
                const hasSizes = !!(product.sizes && product.sizes.length > 0);
                return (
                  <div key={product.id} className="bg-white border border-gray-200 rounded-2xl shadow-sm p-4 sm:p-6 flex flex-col sm:flex-row gap-4">
                    <div className="relative w-full sm:w-24 h-40 sm:h-24 overflow-hidden rounded-lg">
                      <Image
                        src={product.images[0] || '/placeholder.svg'}
                        alt={product.name}
                        fill
                        sizes="(max-width: 640px) 100vw, 96px"
                        className="object-cover"
                      />
                    </div>
                    <div className="flex-1">
                      <div className="flex flex-col gap-3 sm:flex-row sm:justify-between sm:items-start">
                        <div>
                          <div className="flex items-center gap-2 flex-wrap">
                            <h3 className="font-semibold text-base sm:text-lg leading-snug break-words">{product.name}</h3>
                            {hasColors && (
                              <span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-blue-100 text-blue-700 uppercase tracking-wider">
                                {product.colors!.length} väriä
                              </span>
                            )}
                            {hasSizes && (
                              <span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-green-100 text-green-700 uppercase tracking-wider">
                                {product.sizes!.length} kokoa
                              </span>
                            )}
                          </div>
                          <p className="text-gray-600 text-sm break-words">{product.category} - {product.subcategory}</p>
                          <p className="text-sm mt-1 flex flex-wrap items-center gap-x-3 gap-y-1">
                            <span className="font-medium">{product.price}€</span>
                            {product.salePrice && (
                              <span className="text-red-600">{product.salePrice}€</span>
                            )}
                            <span className={`font-medium ${
                              totalStock === 0 ? 'text-red-500' : totalStock <= 5 ? 'text-amber-600' : 'text-green-600'
                            }`}>
                              Varasto: {totalStock} kpl
                            </span>
                          </p>
                        </div>
                        <div className="hidden sm:flex gap-2">
                          <button
                            onClick={() => handleEditProduct(product)}
                            className="w-10 h-10 flex items-center justify-center text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                          >
                            <Edit2 size={18} />
                          </button>
                          <button
                            onClick={() => handleDeleteProduct(product.id)}
                            className="w-10 h-10 flex items-center justify-center text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                          >
                            <Trash2 size={18} />
                          </button>
                        </div>
                      </div>
                    </div>
                    <div className="flex gap-2 sm:hidden">
                      <button
                        onClick={() => handleEditProduct(product)}
                        className="flex-1 py-2.5 rounded-lg border border-gray-200 text-gray-900 font-medium hover:bg-gray-50 transition-colors"
                      >
                        Muokkaa
                      </button>
                      <button
                        onClick={() => handleDeleteProduct(product.id)}
                        className="flex-1 py-2.5 rounded-lg border border-red-200 text-red-600 font-medium hover:bg-red-50 transition-colors"
                      >
                        Poista
                      </button>
                    </div>
                  </div>
                );
              })}
          </div>
        </div>
      )}
 
      {/* Reviews Tab */}
      {activeTab === 'reviews' && (
        <div className="mt-6">
          <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between mb-6">
            <div>
              <h2 className="text-2xl font-semibold">
                Arvostelut{pendingReviews.length > 0 && ` (${pendingReviews.length} odottaa)`}
              </h2>
              <p className="text-sm text-gray-500 mt-1">Hyväksy, muokkaa tai poista asiakasarvosteluita.</p>
            </div>
            <button
              onClick={handleCreateReview}
              className="w-full sm:w-auto px-4 py-2 bg-black text-white rounded-lg hover:bg-gray-800 transition-colors flex items-center justify-center gap-2"
            >
              <PlusCircle size={20} /> Luo uusi arvostelu
            </button>
          </div>
 
          <div className="space-y-4">
            {reviews.map(review => (
              <div key={review.id} className="bg-white border border-gray-200 rounded-2xl shadow-sm p-5 sm:p-6">
                <div className="flex flex-col gap-3">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="font-semibold text-gray-900">{review.author}</span>
                        <div className="flex items-center gap-1">
                          {[...Array(5)].map((_, i) => (
                            <Star
                              key={i}
                              size={14}
                              className={i < review.rating ? 'fill-yellow-500 text-yellow-500' : 'fill-gray-300 text-gray-300'}
                            />
                          ))}
                        </div>
                      </div>
                      {review.productId && (
                        <p className="text-xs text-gray-500 mt-1">Tuote ID: {review.productId}</p>
                      )}
                    </div>
                    <div className="flex flex-col items-end gap-1">
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                        review.status === 'approved' ? 'bg-green-100 text-green-700' :
                        review.status === 'rejected' ? 'bg-red-100 text-red-700' :
                        'bg-yellow-100 text-yellow-700'
                      }`}>
                        {review.status === 'approved' ? 'Hyväksytty' :
                         review.status === 'rejected' ? 'Hylätty' : 'Odottaa'}
                      </span>
                      <span className="text-xs text-gray-400">
                        {new Date(review.createdAt).toLocaleDateString('fi-FI')}
                      </span>
                    </div>
                  </div>
 
                  <p className="text-gray-700 text-sm sm:text-base">{review.text}</p>
 
                  {review.status === 'pending' && (
                    <div className="grid grid-cols-2 gap-2">
                      <button
                        onClick={() => handleReviewAction(review.id, 'approved')}
                        className="w-full h-11 bg-green-100 text-green-700 rounded-lg hover:bg-green-200 transition-colors text-sm font-semibold"
                      >
                        Hyväksy
                      </button>
                      <button
                        onClick={() => handleReviewAction(review.id, 'rejected')}
                        className="w-full h-11 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition-colors text-sm font-semibold"
                      >
                        Hylkää
                      </button>
                    </div>
                  )}
 
                  <div className="grid grid-cols-2 gap-2">
                    <button
                      onClick={() => handleEditReview(review)}
                      className="w-full h-11 rounded-lg border border-gray-200 text-gray-900 font-semibold text-sm hover:bg-gray-50 transition-colors"
                    >
                      Muokkaa
                    </button>
                    <button
                      onClick={() => handleDeleteReview(review.id)}
                      className="w-full h-11 rounded-lg border border-red-200 text-red-600 font-semibold text-sm hover:bg-red-50 transition-colors"
                    >
                      Poista
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
 
          {/* Review Form Modal */}
          {showReviewForm && (
            <div className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-0 sm:p-4">
              <div className="bg-white w-full sm:max-w-2xl h-[100dvh] sm:h-auto sm:max-h-[90vh] overflow-y-auto rounded-none sm:rounded-2xl">
                <div className="sticky top-0 z-10 bg-white border-b border-gray-100 px-4 sm:px-8 py-4 flex items-center justify-between">
                  <h3 className="text-xl sm:text-2xl font-bold">
                    {editingReview ? 'Muokkaa arvostelua' : 'Luo uusi arvostelu'}
                  </h3>
                  <button
                    onClick={() => setShowReviewForm(false)}
                    className="w-10 h-10 rounded-full border border-gray-200 flex items-center justify-center text-gray-500 hover:text-black hover:bg-gray-100 transition-colors"
                  >
                    <X size={18} />
                  </button>
                </div>
 
                <div className="p-4 sm:p-8 space-y-6">
                  {/* Author */}
                  <div>
                    <label className="block text-sm font-bold text-gray-700 mb-2">Arvostelijan nimi</label>
                    <input
                      type="text"
                      value={reviewFormData.author}
                      onChange={(e) => setReviewFormData({ ...reviewFormData, author: e.target.value })}
                      className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-black focus:border-transparent"
                      placeholder="Esim. Matti Meikäläinen"
                    />
                  </div>
 
                  {/* Rating */}
                  <div>
                    <label className="block text-sm font-bold text-gray-700 mb-2">Arvosana</label>
                    <div className="space-y-3">
                      <select
                        value={reviewFormData.rating}
                        onChange={(e) => setReviewFormData({ ...reviewFormData, rating: parseInt(e.target.value) })}
                        className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-black focus:border-transparent"
                      >
                        <option value={5}>5 tähteä - Erinomainen</option>
                        <option value={4}>4 tähteä - Hyvä</option>
                        <option value={3}>3 tähteä - Tyydyttävä</option>
                        <option value={2}>2 tähteä - Huono</option>
                        <option value={1}>1 tähti - Erittäin huono</option>
                      </select>
                      {/* Visual star preview */}
                      <div className="flex gap-1">
                        {[...Array(5)].map((_, i) => (
                          <Star
                            key={i}
                            size={24}
                            className={i < reviewFormData.rating ? 'fill-yellow-500 text-yellow-500' : 'fill-gray-300 text-gray-300'}
                          />
                        ))}
                      </div>
                    </div>
                  </div>
 
                  {/* Review Text */}
                  <div>
                    <label className="block text-sm font-bold text-gray-700 mb-2">Arvosteluteksti</label>
                    <textarea
                      value={reviewFormData.text}
                      onChange={(e) => setReviewFormData({ ...reviewFormData, text: e.target.value })}
                      className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-black focus:border-transparent resize-none"
                      rows={5}
                      placeholder="Kirjoita arvostelu..."
                    />
                  </div>
 
                  {/* Status */}
                  <div>
                    <label className="block text-sm font-bold text-gray-700 mb-2">Tila</label>
                    <select
                      value={reviewFormData.status}
                      onChange={(e) => setReviewFormData({ ...reviewFormData, status: e.target.value as AdminReview['status'] })}
                      className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-black focus:border-transparent"
                    >
                      <option value="pending">Odottaa</option>
                      <option value="approved">Hyväksytty</option>
                      <option value="rejected">Hylätty</option>
                    </select>
                  </div>
 
                  {/* Actions */}
                  <div className="flex flex-col sm:flex-row gap-3 pt-4">
                    <button
                      onClick={() => setShowReviewForm(false)}
                      className="flex-1 px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors font-medium"
                    >
                      Peruuta
                    </button>
                    <button
                      onClick={handleSaveReview}
                      className="flex-1 px-6 py-3 bg-black text-white rounded-lg hover:bg-gray-800 transition-colors font-bold flex items-center justify-center gap-2"
                    >
                      <Save size={20} /> Tallenna
                    </button>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
 
      {/* Orders Tab */}
      {activeTab === 'orders' && (() => {
        const statusLabels: Record<string, string> = {
          pending: 'Odottaa',
          processing: 'Käsittelyssä',
          shipped: 'Lähetetty',
          delivered: 'Toimitettu',
          cancelled: 'Peruutettu',
        };
 
        const allStatuses = ['pending', 'processing', 'shipped', 'delivered', 'cancelled'] as const;
 
        // Get next logical status for quick action
        const getNextStatus = (current: string): AdminOrder['status'] | null => {
          const flow: Record<string, AdminOrder['status']> = {
            pending: 'processing',
            processing: 'shipped',
            shipped: 'delivered',
          };
          return flow[current] || null;
        };
 
        return (
          <div className="mt-6">
            {/* Header - Simple, just title */}
            <div className="mb-10">
              <span className="text-xs font-bold text-gray-400 uppercase tracking-widest">Hallinta</span>
              <h2 className="text-3xl sm:text-4xl font-bold mt-2 tracking-tight text-black uppercase">Tilaukset</h2>
            </div>
 
            {/* Order Edit Modal */}
            {showOrderForm && editingOrder && (
              <div className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-0 sm:p-4">
                <div className="bg-white w-full sm:max-w-3xl h-[100dvh] sm:h-auto sm:max-h-[90vh] overflow-y-auto rounded-none sm:rounded-[2rem] shadow-xl shadow-gray-100">
                  {/* Modal Header */}
                  <div className="sticky top-0 bg-white border-b border-gray-100 px-4 sm:px-10 py-4 flex items-center justify-between rounded-none sm:rounded-t-[2rem] z-10">
                    <div>
                      <span className="text-[10px] font-bold uppercase tracking-widest text-gray-400">Muokkaa tilausta</span>
                      <h3 className="text-2xl font-bold text-black tracking-tight mt-1">#{editingOrder.id.slice(0, 8)}</h3>
                    </div>
                    <button
                      onClick={() => { setShowOrderForm(false); setEditingOrder(null); }}
                      className="w-10 h-10 rounded-full border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-100 hover:text-black hover:border-gray-300 transition-all"
                    >
                      <X size={18} />
                    </button>
                  </div>
 
                  <div className="p-6 sm:p-10 space-y-8 sm:space-y-10">
                    {/* Customer Info */}
                    <div>
                      <h4 className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-4">Asiakastiedot</h4>
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        {[
                          { label: 'Nimi', key: 'customerName' as const, type: 'text' },
                          { label: 'Sähköposti', key: 'customerEmail' as const, type: 'email' },
                          { label: 'Puhelin', key: 'customerPhone' as const, type: 'text' },
                          { label: 'Osoite', key: 'customerAddress' as const, type: 'text' },
                          { label: 'Kaupunki', key: 'customerCity' as const, type: 'text' },
                          { label: 'Postinumero', key: 'customerZip' as const, type: 'text' },
                        ].map(field => (
                          <div key={field.key}>
                            <label className="block text-xs font-bold text-gray-400 uppercase tracking-wider mb-2">{field.label}</label>
                            <input
                              type={field.type}
                              value={orderFormData[field.key]}
                              onChange={(e) => setOrderFormData({ ...orderFormData, [field.key]: e.target.value })}
                              className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-2xl text-sm font-medium focus:border-black focus:bg-white transition-all outline-none"
                            />
                          </div>
                        ))}
                      </div>
                    </div>
 
                    {/* Order Details */}
                    <div>
                      <h4 className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-4">Tilauksen tiedot</h4>
                      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                        <div>
                          <label className="block text-xs font-bold text-gray-400 uppercase tracking-wider mb-2">Tila</label>
                          <select
                            value={orderFormData.status}
                            onChange={(e) => setOrderFormData({ ...orderFormData, status: e.target.value as AdminOrder['status'] })}
                            className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-2xl text-sm font-medium focus:border-black focus:bg-white transition-all outline-none"
                          >
                            <option value="pending">Odottaa</option>
                            <option value="processing">Käsittelyssä</option>
                            <option value="shipped">Lähetetty</option>
                            <option value="delivered">Toimitettu</option>
                            <option value="cancelled">Peruutettu</option>
                          </select>
                        </div>
                        <div>
                          <label className="block text-xs font-bold text-gray-400 uppercase tracking-wider mb-2">Toimitustapa</label>
                          <input
                            type="text"
                            value={orderFormData.shippingMethod}
                            onChange={(e) => setOrderFormData({ ...orderFormData, shippingMethod: e.target.value })}
                            className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-2xl text-sm font-medium focus:border-black focus:bg-white transition-all outline-none"
                          />
                        </div>
                        <div>
                          <label className="block text-xs font-bold text-gray-400 uppercase tracking-wider mb-2">Yhteensä (€)</label>
                          <input
                            type="number"
                            step="0.01"
                            value={orderFormData.total}
                            onChange={(e) => setOrderFormData({ ...orderFormData, total: parseFloat(e.target.value) || 0 })}
                            className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-2xl text-sm font-medium focus:border-black focus:bg-white transition-all outline-none"
                          />
                        </div>
                      </div>
                    </div>
 
                    {/* Customer Notes */}
                    <div>
                      <h4 className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-4">
                        Asiakkaan lisätiedot
                        {orderFormData.notes && <span className="ml-2 text-amber-600">(Sisältää viestin)</span>}
                      </h4>
                      <textarea
                        value={orderFormData.notes || ''}
                        onChange={(e) => setOrderFormData({ ...orderFormData, notes: e.target.value || null })}
                        placeholder="Ei lisätietoja"
                        rows={3}
                        className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-2xl text-sm font-medium focus:border-black focus:bg-white transition-all outline-none resize-none"
                      />
                    </div>
 
                    {/* Order Items */}
                    <div>
                      <h4 className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-4">Tuotteet ({orderFormData.items.length})</h4>
                      <div className="space-y-3">
                        {orderFormData.items.map((item, index) => (
                          <div key={index} className="bg-[#f8f8f8] border border-gray-200 rounded-2xl p-5">
                            <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-4">
                              <div className="flex items-center gap-3">
                                {item.product.images?.[0] && (
                                  <Image
                                    src={item.product.images[0]}
                                    alt={item.product.name}
                                    width={40}
                                    height={40}
                                    className="w-10 h-10 rounded-xl object-cover"
                                  />
                                )}
                                <div className="font-bold text-black text-sm">{item.product.name}</div>
                              </div>
                              <button
                                onClick={() => handleRemoveOrderItem(index)}
                                className="w-8 h-8 rounded-full border border-gray-200 flex items-center justify-center text-gray-400 hover:bg-black hover:text-white hover:border-black transition-all"
                                title="Poista tuote"
                              >
                                <Trash2 size={12} />
                              </button>
                            </div>
                            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-3">
                              <div>
                                <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1.5">Määrä</label>
                                <input
                                  type="number"
                                  min="1"
                                  value={item.quantity}
                                  onChange={(e) => handleOrderItemChange(index, 'quantity', parseInt(e.target.value) || 1)}
                                  className="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-sm font-medium focus:border-black transition-all outline-none"
                                />
                              </div>
                              <div>
                                <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1.5">Hinta (€)</label>
                                <input
                                  type="number"
                                  step="0.01"
                                  value={item.price}
                                  onChange={(e) => handleOrderItemChange(index, 'price', parseFloat(e.target.value) || 0)}
                                  className="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-sm font-medium focus:border-black transition-all outline-none"
                                />
                              </div>
                              <div>
                                <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1.5">Väri</label>
                                {item.product.colors && Array.isArray(item.product.colors) && item.product.colors.length > 0 ? (
                                  <select
                                    value={item.selectedColor || ''}
                                    onChange={(e) => handleOrderItemChange(index, 'selectedColor', e.target.value || null)}
                                    className="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-sm font-medium focus:border-black transition-all outline-none"
                                  >
                                    <option value="">Ei valittu</option>
                                    {(item.product.colors as { name: string; hex: string }[]).map((color) => (
                                      <option key={color.name} value={color.name}>{color.name}</option>
                                    ))}
                                  </select>
                                ) : (
                                  <input
                                    type="text"
                                    value={item.selectedColor || ''}
                                    onChange={(e) => handleOrderItemChange(index, 'selectedColor', e.target.value || null)}
                                    className="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-sm font-medium focus:border-black transition-all outline-none"
                                    placeholder="-"
                                  />
                                )}
                              </div>
                              <div>
                                <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1.5">Koko</label>
                                {item.product.sizes && Array.isArray(item.product.sizes) && item.product.sizes.length > 0 ? (
                                  <select
                                    value={item.selectedSize || ''}
                                    onChange={(e) => handleOrderItemChange(index, 'selectedSize', e.target.value || null)}
                                    className="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-sm font-medium focus:border-black transition-all outline-none"
                                  >
                                    <option value="">Ei valittu</option>
                                    {(item.product.sizes as { name: string }[]).map((size) => (
                                      <option key={size.name} value={size.name}>{size.name}</option>
                                    ))}
                                  </select>
                                ) : (
                                  <input
                                    type="text"
                                    value={item.selectedSize || ''}
                                    onChange={(e) => handleOrderItemChange(index, 'selectedSize', e.target.value || null)}
                                    className="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-sm font-medium focus:border-black transition-all outline-none"
                                    placeholder="-"
                                  />
                                )}
                              </div>
                            </div>
                          </div>
                        ))}
                        {orderFormData.items.length === 0 && (
                          <div className="text-center py-10 text-gray-400 text-sm font-medium">Ei tuotteita tilauksessa</div>
                        )}
                      </div>
                    </div>
                  </div>
 
                  {/* Modal Footer */}
                  <div className="sticky bottom-0 bg-white border-t border-gray-100 px-6 sm:px-10 py-4 sm:py-5 flex flex-col sm:flex-row gap-4 rounded-b-[2rem]">
                    <button
                      onClick={() => { setShowOrderForm(false); setEditingOrder(null); }}
                      className="flex-1 px-6 py-3.5 border border-gray-200 text-black rounded-full hover:border-black transition-all font-bold text-sm"
                    >
                      Peruuta
                    </button>
                    <button
                      onClick={handleSaveOrder}
                      className="flex-1 px-6 py-3.5 bg-black text-white rounded-full hover:bg-white hover:text-black border border-black transition-all font-bold text-sm flex items-center justify-center gap-2"
                    >
                      Tallenna muutokset <ArrowRight size={16} />
                    </button>
                  </div>
                </div>
              </div>
            )}
 
            {/* Orders List */}
            <div className="sm:hidden space-y-3">
              {orders.map(order => {
                const nextStatus = getNextStatus(order.status);
                const isExpanded = expandedOrderId === order.id;
                return (
                  <div key={order.id} className="bg-white border border-gray-200 rounded-2xl p-4">
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <div className="text-[10px] font-semibold uppercase tracking-wider text-gray-400">
                          #{order.id.slice(0, 8)}
                        </div>
                        <div className="font-semibold text-gray-900 truncate">{order.customerName}</div>
                        <div className="text-xs text-gray-500 mt-0.5">
                          {new Date(order.createdAt).toLocaleDateString('fi-FI')} • {order.items?.length || 0} tuotetta
                        </div>
                      </div>
                      <div className="text-right">
                        <div className="text-xl font-bold text-gray-900">{order.total.toFixed(0)}€</div>
                        <div className="text-xs font-semibold text-gray-500 mt-0.5">{statusLabels[order.status]}</div>
                      </div>
                    </div>
 
                    <div className="mt-3 space-y-2">
                      {nextStatus && (
                        <button
                          onClick={() => handleQuickStatusChange(order.id, nextStatus)}
                          className="w-full h-11 rounded-lg bg-black text-white font-semibold text-sm"
                        >
                          {order.status === 'pending' && 'Käsittele tilaus'}
                          {order.status === 'processing' && 'Merkitse lähetetyksi'}
                          {order.status === 'shipped' && 'Merkitse toimitetuksi'}
                        </button>
                      )}
                      <button
                        onClick={() => handleEditOrder(order)}
                        className="w-full h-11 rounded-lg border border-gray-200 text-gray-900 font-semibold text-sm hover:bg-gray-50 transition-colors"
                      >
                        Muokkaa
                      </button>
                      <button
                        onClick={() => handleDeleteOrder(order.id)}
                        className="w-full h-11 rounded-lg border border-red-200 text-red-600 font-semibold text-sm hover:bg-red-50 transition-colors"
                      >
                        Poista
                      </button>
                      <button
                        onClick={() => setExpandedOrderId(isExpanded ? null : order.id)}
                        className="w-full h-11 rounded-lg border border-gray-200 text-gray-600 font-semibold text-sm hover:bg-gray-50 transition-colors"
                      >
                        {isExpanded ? 'Piilota tiedot' : 'Näytä tiedot'}
                      </button>
                    </div>
 
                    {isExpanded && (
                      <div className="mt-3 border-t border-gray-100 pt-3 space-y-3 text-sm text-gray-700">
                        <div>
                          <div className="text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1">Asiakas</div>
                          <div className="font-medium text-gray-900">{order.customerName}</div>
                          <div className="text-xs text-gray-500">{order.customerPhone}</div>
                          <div className="text-xs text-gray-500 break-all">{order.customerEmail}</div>
                        </div>
                        <div>
                          <div className="text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1">Toimitus</div>
                          <div className="text-sm text-gray-900">{order.customerAddress}, {order.customerZip} {order.customerCity}</div>
                          <div className="text-xs text-gray-500">{order.shippingMethod}</div>
                        </div>
                        <div>
                          <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1">Tila</label>
                          <select
                            value={order.status}
                            onChange={(e) => handleQuickStatusChange(order.id, e.target.value as AdminOrder['status'])}
                            className="w-full p-2 border border-gray-200 rounded-lg text-sm"
                          >
                            {allStatuses.map(s => (
                              <option key={s} value={s}>{statusLabels[s]}</option>
                            ))}
                          </select>
                        </div>
                        <div>
                          <div className="text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1">Tuotteet</div>
                          <div className="space-y-1">
                            {order.items?.map((item) => (
                              <div key={item.id} className="flex items-center justify-between gap-2 text-xs text-gray-700">
                                <span className="truncate">{item.product.name}</span>
                                <span className="font-medium">{item.quantity}× {item.price.toFixed(0)}€</span>
                              </div>
                            ))}
                            {(!order.items || order.items.length === 0) && (
                              <div className="text-xs text-gray-400">Ei tuotteita</div>
                            )}
                          </div>
                        </div>
                        {order.notes && (
                          <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 text-xs text-amber-900">
                            <div className="font-semibold uppercase tracking-wider text-amber-700 mb-1">Lisätiedot</div>
                            {order.notes}
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                );
              })}
 
              {orders.length === 0 && (
                <div className="text-center py-16 border border-gray-200 rounded-xl bg-white">
                  <Package size={28} className="text-gray-300 mx-auto mb-3" />
                  <p className="font-bold text-black">Ei tilauksia</p>
                  <p className="text-sm text-gray-400 mt-1">Tilaukset näkyvät täällä</p>
                </div>
              )}
            </div>
 
            <div className="hidden sm:block space-y-3">
              {orders.map(order => {
                const nextStatus = getNextStatus(order.status);
                const needsAction = order.status === 'pending' || order.status === 'processing';
 
                return (
                  <div
                    key={order.id}
                    className={`rounded-2xl border transition-all ${
                      needsAction ? 'border-black' : 'border-gray-200'
                    } bg-white`}
                  >
                    {/* Single Row Layout */}
                    <div className="p-5">
                      <div className="flex flex-col gap-4 lg:flex-row lg:gap-5">
                        {/* 1. Status & Action - Fixed width */}
                        <div className="w-full lg:w-40 flex-shrink-0">
                          {nextStatus ? (
                            <button
                              onClick={() => handleQuickStatusChange(order.id, nextStatus)}
                              className={`w-full py-3 rounded-lg font-bold text-base transition-all ${
                                order.status === 'pending'
                                  ? 'bg-black text-white hover:bg-gray-800'
                                  : 'bg-gray-100 text-black hover:bg-gray-200'
                              }`}
                            >
                              {order.status === 'pending' && '→ Käsittele'}
                              {order.status === 'processing' && '→ Lähetä'}
                              {order.status === 'shipped' && '→ Toimitettu'}
                            </button>
                          ) : (
                            <div className={`w-full py-3 rounded-lg font-bold text-base text-center ${
                              order.status === 'delivered' ? 'bg-gray-50 text-gray-400' : 'bg-gray-50 text-gray-400'
                            }`}>
                              {statusLabels[order.status]}
                            </div>
                          )}
                          <DropdownMenu>
                            <DropdownMenuTrigger className="w-full mt-2 text-sm font-medium text-gray-600 hover:text-black transition-colors cursor-pointer text-center flex items-center justify-center gap-1">
                              {statusLabels[order.status]} <ChevronDown size={14} />
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="center">
                              {allStatuses.map(s => (
                                <DropdownMenuItem
                                  key={s}
                                  onClick={() => handleQuickStatusChange(order.id, s)}
                                  className={order.status === s ? 'bg-gray-100' : ''}
                                >
                                  {statusLabels[s]}
                                </DropdownMenuItem>
                              ))}
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </div>
 
                        {/* 2. Customer Info - Selectable for copy */}
                        <div className="w-full lg:w-56 flex-shrink-0 border-t border-gray-100 pt-3 lg:border-t-0 lg:border-l border-gray-200 lg:pt-0 lg:pl-5">
                          <div className="flex items-center gap-2">
                            <div className="font-bold text-black text-base">{order.customerName}</div>
                            {order.notes && (
                              <span className="text-amber-600" title="Lisätietoja">
                                <MessageSquare size={16} className="fill-amber-100" />
                              </span>
                            )}
                          </div>
                          <div className="text-sm font-medium text-gray-700 mt-1 select-all cursor-text break-words">{order.customerPhone}</div>
                          <div className="text-sm font-medium text-gray-600 mt-0.5 select-all cursor-text break-all">{order.customerEmail}</div>
                        </div>
 
                        {/* 3. Delivery Address - Selectable for shipping label */}
                        <div className="w-full lg:w-56 flex-shrink-0 border-t border-gray-100 pt-3 lg:border-t-0 lg:border-l border-gray-200 lg:pt-0 lg:pl-5">
                          <div className="text-xs font-bold uppercase tracking-wider text-gray-500 mb-1">Toimitus</div>
                          <div className="text-base font-medium text-gray-900 select-all cursor-text leading-snug">
                            {order.customerName}<br />
                            {order.customerAddress}<br />
                            {order.customerZip} {order.customerCity}
                          </div>
                          <div className="text-sm font-medium text-gray-600 mt-1">{order.shippingMethod}</div>
                        </div>
 
                        {/* 4. Products - Flexible */}
                        <div className="w-full lg:flex-1 border-t border-gray-100 pt-3 lg:border-t-0 lg:border-l border-gray-200 lg:pt-0 lg:pl-5 min-w-0">
                          <div className="flex flex-wrap gap-2">
                            {order.items?.map((item) => (
                              <div key={item.id} className="flex items-center gap-2 bg-gray-100 rounded-lg px-3 py-2">
                                {item.product.images?.[0] && (
                                  <Image
                                    src={item.product.images[0]}
                                    alt={item.product.name}
                                    width={40}
                                    height={40}
                                    className="w-10 h-10 rounded object-cover"
                                  />
                                )}
                                <div>
                                  <div className="text-sm font-bold text-black truncate max-w-[160px]">{item.product.name}</div>
                                  <div className="text-xs font-medium text-gray-700">
                                    {item.quantity}× {item.price.toFixed(0)}€
                                    {item.selectedColor && (
                                      <span className="inline-flex items-center gap-1 ml-1">
                                        {item.product.colors && (() => {
                                          const colors = Array.isArray(item.product.colors) ? item.product.colors : [];
                                          const colorInfo = colors.find((c) => c.name === item.selectedColor);
                                          return colorInfo ? (
                                            <span className="w-2 h-2 rounded-full inline-block" style={{ backgroundColor: colorInfo.hex }} />
                                          ) : null;
                                        })()}
                                      </span>
                                    )}
                                    {item.selectedSize && (
                                      <span className="ml-1 text-gray-500">({item.selectedSize})</span>
                                    )}
                                  </div>
                                </div>
                              </div>
                            ))}
                          </div>
                        </div>
 
                        {/* 5. Total & Actions - Fixed width */}
                        <div className="w-full lg:w-32 flex-shrink-0 border-t border-gray-100 pt-3 lg:border-t-0 lg:border-l border-gray-200 lg:pt-0 lg:pl-5 flex flex-col items-start lg:items-end justify-between gap-3 lg:gap-0">
                          <div>
                            <div className="text-2xl font-bold text-black text-left lg:text-right">{order.total.toFixed(0)}€</div>
                            <div className="text-sm font-medium text-gray-600 text-left lg:text-right">{new Date(order.createdAt).toLocaleDateString('fi-FI')}</div>
                          </div>
                          <div className="flex gap-1.5">
                            <button
                              onClick={() => handleEditOrder(order)}
                              className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center text-gray-600 hover:bg-black hover:text-white hover:border-black transition-all"
                              title="Muokkaa"
                            >
                              <Edit2 size={14} />
                            </button>
                            <button
                              onClick={() => handleDeleteOrder(order.id)}
                              className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center text-gray-600 hover:bg-black hover:text-white hover:border-black transition-all"
                              title="Poista"
                            >
                              <Trash2 size={14} />
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
 
                    {/* Notes Section - Only shown if notes exist */}
                    {order.notes && (
                      <div className="px-5 pb-4 pt-0">
                        <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 flex gap-3">
                          <MessageSquare size={18} className="text-amber-600 flex-shrink-0 mt-0.5" />
                          <div>
                            <div className="text-xs font-bold uppercase tracking-wider text-amber-700 mb-1">Lisätietoja asiakkaalta</div>
                            <div className="text-sm font-medium text-amber-900">{order.notes}</div>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
 
              {orders.length === 0 && (
                <div className="text-center py-20 border border-gray-200 rounded-xl">
                  <Package size={28} className="text-gray-300 mx-auto mb-3" />
                  <p className="font-bold text-black">Ei tilauksia</p>
                  <p className="text-sm text-gray-400 mt-1">Tilaukset näkyvät täällä</p>
                </div>
              )}
            </div>
          </div>
        );
      })()}
 
      {/* Category Images Tab */}
      {activeTab === 'category-images' && (
        <div className="mt-6">
          <div className="mb-6">
            <h2 className="text-2xl font-semibold">Kategorioiden kuvat</h2>
            <p className="text-sm text-gray-600 mt-1">Hallitse etusivun &quot;Selaa tuoteryhmiä&quot; -osion kuvia. Klikkaa &quot;Lisää kuva&quot; tai &quot;Muokkaa&quot; muokataksesi.</p>
          </div>
 
          {/* Category Image Form Modal */}
          {showCategoryImageForm && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-start sm:items-center justify-center z-50 p-0 sm:p-4">
              <div className="bg-white w-full sm:max-w-2xl h-[100dvh] sm:h-auto sm:max-h-[90vh] overflow-y-auto rounded-none sm:rounded-2xl">
                <div className="sticky top-0 z-10 bg-white border-b border-gray-100 px-4 sm:px-8 py-4 flex items-center justify-between">
                  <h3 className="text-xl sm:text-2xl font-bold">
                    {editingCategory ? 'Muokkaa kategorian kuvaa' : 'Lisää kategorian kuva'}
                  </h3>
                  <button
                    onClick={() => setShowCategoryImageForm(false)}
                    className="w-10 h-10 rounded-full border border-gray-200 flex items-center justify-center text-gray-500 hover:text-black hover:bg-gray-100 transition-colors"
                  >
                    <X size={18} />
                  </button>
                </div>
 
                <div className="p-4 sm:p-8 space-y-4">
                  <div>
                    <label className="block text-sm font-medium mb-2">Kategoria</label>
                    <select
                      value={categoryImageForm.categoryName}
                      onChange={(e) => setCategoryImageForm({ ...categoryImageForm, categoryName: e.target.value })}
                      className="w-full p-3 border border-gray-200 rounded-xl"
                      disabled={!!editingCategory}
                    >
                      <option value="">Valitse kategoria</option>
                      {CATEGORIES.map(cat => (
                        <option key={cat.name} value={cat.name}>{cat.name}</option>
                      ))}
                    </select>
                    <p className="text-xs text-gray-500 mt-1">
                      Kategoriat tulevat CATEGORIES-vakiosta. Etusivulla näytetään 6 kategoriaa (MITTARIT ei näy).
                    </p>
                  </div>
 
                  <div>
                    <label className="block text-sm font-medium mb-2">Kuva</label>
                    <ImageUpload
                      images={categoryImageForm.imageUrl ? [categoryImageForm.imageUrl] : []}
                      onImagesChange={(images) => handleCategoryImageChange(images[0] || '')}
                      maxImages={1}
                    />
                  </div>
 
                  <div className="flex flex-col sm:flex-row gap-4 pt-4">
                    <button
                      onClick={handleSaveCategoryImage}
                      className="flex-1 bg-black text-white py-3 rounded-xl hover:shadow-lg transition-all flex items-center justify-center gap-2"
                    >
                      <Save size={20} />
                      Tallenna
                    </button>
                    <button
                      onClick={() => setShowCategoryImageForm(false)}
                      className="flex-1 bg-gray-200 text-gray-700 py-3 rounded-xl hover:bg-gray-300 transition-all"
                    >
                      Peruuta
                    </button>
                  </div>
                </div>
              </div>
            </div>
          )}
 
          {/* Category Images Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {CATEGORIES.filter(cat => cat.name !== "MITTARIT").slice(0, 6).map(cat => {
              const existingImage = categoryImages.find(img => img.categoryName === cat.name);
              const defaultImage = CATEGORY_IMAGE_DEFAULTS[cat.name];
              const isPicsum = existingImage?.imageUrl?.includes('picsum.photos');
              const customImage = !isPicsum ? existingImage?.imageUrl : undefined;
              const hasImage = Boolean(customImage || defaultImage);
              const displayImage = customImage || defaultImage || '/placeholder.svg';
              return (
                <div key={cat.name} className="bg-white border border-gray-200 rounded-xl overflow-hidden">
                  <div className="relative h-48 bg-gray-100">
                    <Image
                      src={displayImage}
                      alt={cat.name}
                      fill
                      sizes="(max-width: 768px) 100vw, 33vw"
                      className="object-cover"
                    />
                    {!hasImage && (
                      <div className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center">
                        <span className="text-white text-sm font-medium">Placeholder-kuva</span>
                      </div>
                    )}
                  </div>
                  <div className="p-4">
                    <h3 className="font-semibold text-lg mb-2">{cat.name}</h3>
                    <p className="text-sm text-gray-600 mb-4">
                      {cat.subcategories?.length || 0} alakategoriaa
                    </p>
                    <div className="flex flex-col sm:flex-row gap-2">
                      {customImage ? (
                        <>
                          <button
                            onClick={() => handleEditCategoryImage(cat.name, customImage)}
                            className="flex-1 w-full sm:w-auto px-4 py-2 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 transition-colors text-sm font-medium"
                          >
                            Muokkaa
                          </button>
                          <button
                            onClick={() => handleDeleteCategoryImage(cat.name)}
                            className="flex-1 w-full sm:w-auto px-4 py-2 bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition-colors text-sm font-medium"
                          >
                            Poista
                          </button>
                        </>
                      ) : hasImage ? (
                        <button
                          onClick={() => handleEditCategoryImage(cat.name, defaultImage || '')}
                          className="flex-1 w-full sm:w-auto px-4 py-2 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 transition-colors text-sm font-medium"
                        >
                          Muokkaa
                        </button>
                      ) : (
                        <button
                          onClick={() => {
                            setCategoryImageForm({ categoryName: cat.name, imageUrl: '' });
                            setShowCategoryImageForm(true);
                          }}
                          className="flex-1 w-full sm:w-auto px-4 py-2 bg-black text-white rounded-lg hover:shadow-lg transition-all text-sm font-medium"
                        >
                          Lisää kuva
                        </button>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}
      </div>
    </Section>
  );
};
 
export default AdminNew;