Spaces:
Running
Running
File size: 131,720 Bytes
da7c69a 15bf25b da7c69a 15bf25b fe6a4ea 15bf25b da7c69a 15bf25b da7c69a 994da7d da7c69a 994da7d da7c69a fe6a4ea 6b2c51b fe6a4ea 6b2c51b fe6a4ea 6b2c51b fe6a4ea 6b2c51b fe6a4ea 6b2c51b fe6a4ea da7c69a fe6a4ea da7c69a 747b5b2 a12597f 818ce84 14f1f7e 818ce84 14f1f7e 818ce84 14f1f7e b201116 fe6a4ea 513f8bb 8f394cc da7c69a 15bf25b da7c69a 15bf25b da7c69a 15bf25b da7c69a 15bf25b da7c69a 15bf25b da7c69a 15bf25b da7c69a 15bf25b da7c69a 15bf25b da7c69a 8f394cc da7c69a 6b2c51b da7c69a 8f394cc da7c69a 8f394cc da7c69a 15bf25b 50a712c 747b5b2 a12597f b201116 6508d8a 631d5ed a12597f 747b5b2 a12597f 747b5b2 a12597f 747b5b2 a12597f 747b5b2 a12597f 747b5b2 a12597f b201116 a12597f b201116 a12597f 747b5b2 b201116 a12597f 747b5b2 a12597f 747b5b2 a12597f 747b5b2 a12597f 747b5b2 a12597f 747b5b2 b201116 747b5b2 6508d8a 818ce84 631d5ed 6508d8a 818ce84 6508d8a b201116 6508d8a 513f8bb b201116 6508d8a 513f8bb b201116 513f8bb b201116 6508d8a b201116 6508d8a 513f8bb 6508d8a 513f8bb 6508d8a 513f8bb 14f1f7e 513f8bb 14f1f7e 6508d8a 14f1f7e 6508d8a 513f8bb 6508d8a 513f8bb 14f1f7e 6508d8a 14f1f7e 6508d8a 818ce84 6508d8a 818ce84 6508d8a 631d5ed 6508d8a 631d5ed 6508d8a 631d5ed 6508d8a 631d5ed 6508d8a 631d5ed 6508d8a 631d5ed 6508d8a b201116 6508d8a 513f8bb 6508d8a 513f8bb 6508d8a 513f8bb b201116 513f8bb 6508d8a b201116 513f8bb 6508d8a a12597f 747b5b2 a12597f b201116 a12597f b201116 a12597f ee0ac9c a12597f ee0ac9c a12597f b201116 a12597f b201116 a12597f 747b5b2 50a712c 747b5b2 50a712c 747b5b2 631d5ed ee0ac9c fe6a4ea ee0ac9c 14f1f7e fe6a4ea 14f1f7e 513f8bb 8f394cc de20df8 6b2c51b ee0ac9c 14f1f7e 513f8bb 14f1f7e 513f8bb 8f394cc 513f8bb 14f1f7e de20df8 da7c69a 50a712c da7c69a 15bf25b 50a712c da7c69a 15bf25b da7c69a 15bf25b 747b5b2 a12597f 818ce84 631d5ed da7c69a | 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 | // BeatFridge - Core Application Logic
const BF = (() => {
// ===== DEFAULT DATA =====
const defaultTracks = [
{ id: 1, title: "Neon Horizons", artist: "Aurora Void", artistId: "aurora-void", duration: "4:32", image: "http://static.photos/technology/400x400/1", plays: "12.5K", genre: "techno", date: "2 days ago" },
{ id: 2, title: "Digital Rain", artist: "Aurora Void", artistId: "aurora-void", duration: "3:45", image: "http://static.photos/technology/400x400/2", plays: "8.2K", genre: "ambient", date: "5 days ago" },
{ id: 3, title: "Cybernetic Dreams", artist: "Aurora Void", artistId: "aurora-void", duration: "5:18", image: "http://static.photos/technology/400x400/3", plays: "24.1K", genre: "techno", date: "1 week ago" },
{ id: 4, title: "Analog Heart", artist: "Aurora Void", artistId: "aurora-void", duration: "3:22", image: "http://static.photos/technology/400x400/4", plays: "15.3K", genre: "synthwave", date: "2 weeks ago" },
{ id: 5, title: "Midnight Synthesis", artist: "Aurora Void", artistId: "aurora-void", duration: "4:08", image: "http://static.photos/technology/400x400/5", plays: "32.7K", genre: "techno", date: "3 weeks ago" },
{ id: 6, title: "Void Walker", artist: "Aurora Void", artistId: "aurora-void", duration: "6:14", image: "http://static.photos/technology/400x400/6", plays: "9.8K", genre: "ambient", date: "1 month ago" },
{ id: 7, title: "Electric Soul", artist: "Neon Prophet", artistId: "neon-prophet", duration: "3:55", image: "http://static.photos/technology/400x400/7", plays: "18.4K", genre: "house", date: "3 days ago" },
{ id: 8, title: "Digital Horizon", artist: "Cyber Dreamer", artistId: "cyber-dreamer", duration: "4:15", image: "http://static.photos/technology/400x400/8", plays: "11.2K", genre: "synthwave", date: "1 week ago" },
{ id: 9, title: "Deep Pulse", artist: "Deep Frequencies", artistId: "deep-freq", duration: "6:18", image: "http://static.photos/technology/400x400/9", plays: "7.6K", genre: "techno", date: "4 days ago" },
{ id: 10, title: "Neon City", artist: "Neon Prophet", artistId: "neon-prophet", duration: "4:22", image: "http://static.photos/technology/400x400/10", plays: "14.1K", genre: "synthwave", date: "6 days ago" },
{ id: 11, title: "Binary Sunset", artist: "Synth Wanderer", artistId: "synth-wanderer", duration: "5:02", image: "http://static.photos/technology/400x400/11", plays: "6.3K", genre: "ambient", date: "2 weeks ago" },
{ id: 12, title: "Crystal Waves", artist: "Cyber Dreamer", artistId: "cyber-dreamer", duration: "3:38", image: "http://static.photos/technology/400x400/12", plays: "19.7K", genre: "house", date: "1 day ago" }
];
const defaultArtists = [
{ id: "aurora-void", name: "Aurora Void", followers: "128.5K", image: "http://static.photos/people/200x200/77", genre: "Electronic", verified: true },
{ id: "neon-prophet", name: "Neon Prophet", followers: "45.2K", image: "http://static.photos/people/200x200/10", genre: "Techno", verified: false },
{ id: "cyber-dreamer", name: "Cyber Dreamer", followers: "32.8K", image: "http://static.photos/people/200x200/11", genre: "Synthwave", verified: false },
{ id: "synth-wanderer", name: "Synth Wanderer", followers: "28.1K", image: "http://static.photos/people/200x200/12", genre: "Ambient", verified: false },
{ id: "deep-freq", name: "Deep Frequencies", followers: "15.7K", image: "http://static.photos/people/200x200/13", genre: "Techno", verified: false },
{ id: "bass-architect", name: "Bass Architect", followers: "22.4K", image: "http://static.photos/people/200x200/14", genre: "Drum & Bass", verified: true }
];
const genres = [
{ name: "Techno", icon: "waves", color: "cyan" },
{ name: "Ambient", icon: "cloud", color: "purple" },
{ name: "House", icon: "flame", color: "orange" },
{ name: "Synthwave", icon: "zap", color: "pink" },
{ name: "Lo-Fi", icon: "leaf", color: "green" },
{ name: "Drum & Bass", icon: "activity", color: "red" }
];
// ===== AUTH =====
const isLoggedIn = () => localStorage.getItem('isLoggedIn') === 'true';
const isProducer = () => {
try {
const user = JSON.parse(localStorage.getItem('beatfridge_current_user'));
return user && (user.role === 'producer' || (!user.role && user.isArtist));
} catch { return false; }
};
const isFan = () => {
try {
const user = JSON.parse(localStorage.getItem('beatfridge_current_user'));
return user && user.role === 'fan';
} catch { return false; }
};
const getCurrentUser = () => {
try {
return JSON.parse(localStorage.getItem('beatfridge_current_user')) || null;
} catch { return null; }
};
const signIn = (identifier, password) => {
try {
const users = JSON.parse(localStorage.getItem('beatfridge_users') || '[]');
const user = users.find(u => (u.username === identifier || u.email === identifier) && u.password === password);
if (user) {
localStorage.setItem('beatfridge_current_user', JSON.stringify(user));
localStorage.setItem('isLoggedIn', 'true');
localStorage.setItem('currentUserId', user.id);
return { success: true, user };
}
return { success: false, error: 'Invalid username or password' };
} catch {
return { success: false, error: 'Sign in failed' };
}
};
const signOut = () => {
localStorage.removeItem('beatfridge_current_user');
localStorage.removeItem('isLoggedIn');
localStorage.removeItem('currentUserId');
window.location.href = 'index.html';
};
const signUp = (userData) => {
try {
const users = JSON.parse(localStorage.getItem('beatfridge_users') || '[]');
if (users.find(u => u.username.toLowerCase() === userData.username.toLowerCase())) {
return { success: false, error: 'Username is already taken' };
}
if (users.find(u => u.email.toLowerCase() === userData.email.toLowerCase())) {
return { success: false, error: 'Email is already registered' };
}
const role = userData.role || 'fan';
const newUser = {
id: (role === 'producer' ? 'producer_' : 'fan_') + Date.now(),
username: userData.username,
email: userData.email,
password: userData.password,
displayName: userData.displayName || userData.username,
avatar: userData.avatar || 'http://static.photos/people/200x200/' + Math.floor(Math.random() * 100),
role: role,
isArtist: role === 'producer',
createdAt: new Date().toISOString(),
bio: '',
location: '',
followers: 0,
following: [],
tracks: [],
likes: 0,
reposts: 0
};
users.push(newUser);
localStorage.setItem('beatfridge_users', JSON.stringify(users));
localStorage.setItem('beatfridge_current_user', JSON.stringify(newUser));
localStorage.setItem('isLoggedIn', 'true');
localStorage.setItem('currentUserId', newUser.id);
// Record referral if applicable
try {
const pendingRef = sessionStorage.getItem('bf_pending_referral');
if (pendingRef) { recordReferralSignup(pendingRef); sessionStorage.removeItem('bf_pending_referral'); }
} catch {}
return { success: true, user: newUser };
} catch (e) {
return { success: false, error: 'Sign up failed: ' + e.message };
}
};
// ===== TRACKS =====
const getAllTracks = () => {
try {
const userTracks = JSON.parse(localStorage.getItem('userTracks') || '[]');
const bfTracks = JSON.parse(localStorage.getItem('beatfridge_tracks') || '[]');
const seen = new Set();
const all = [...defaultTracks, ...userTracks, ...bfTracks];
return all.filter(t => {
if (seen.has(t.id)) return false;
seen.add(t.id);
return true;
});
} catch { return [...defaultTracks]; }
};
const getArtists = () => {
try {
const user = getCurrentUser();
if (user && (user.role === 'producer' || (!user.role && user.isArtist))) {
const exists = defaultArtists.find(a => a.id === user.id);
if (!exists) {
return [{ id: user.id, name: user.displayName || user.username, followers: user.followers || "0", image: user.avatar || 'http://static.photos/people/200x200/42', genre: "Electronic", verified: false, isUser: true }, ...defaultArtists];
}
}
} catch (e) { console.error('getArtists error:', e); }
return [...defaultArtists];
};
const getGenres = () => [...genres];
const getTrendingTracks = () => {
const shareCounts = {};
try { Object.assign(shareCounts, JSON.parse(localStorage.getItem('bf_track_shares') || '{}')); } catch {}
const unlockCounts = {};
try { JSON.parse(localStorage.getItem('bf_download_states') || '[]').forEach(s => { if (s.unlocked) unlockCounts[s.trackId] = (unlockCounts[s.trackId] || 0) + 1; }); } catch {}
const recentActivity = {};
try { Object.assign(recentActivity, JSON.parse(localStorage.getItem('bf_recent_activity') || '{}')); } catch {}
const now = Date.now();
const HOUR = 3600000;
let prevRankings = {};
try { prevRankings = JSON.parse(localStorage.getItem('bf_prev_rankings') || '{}'); } catch {}
const ranked = getAllTracks().map(t => {
const p = parseFloat(t.plays || '0');
const plays = (t.plays || '').includes('K') ? p * 1000 : p;
const shares = shareCounts[t.id] || 0;
const unlocks = unlockCounts[t.id] || 0;
// Base score
const baseScore = plays + (unlocks * 10) + (shares * 5);
// Recency boost: recent activity gets exponential weight
const act = recentActivity[t.id] || { lastPlay: 0, lastUnlock: 0, recentPlays: 0, recentUnlocks: 0 };
const hoursSincePlay = act.lastPlay ? (now - act.lastPlay) / HOUR : Infinity;
const hoursSinceUnlock = act.lastUnlock ? (now - act.lastUnlock) / HOUR : Infinity;
let recencyBoost = 1;
if (hoursSincePlay < 24) recencyBoost *= 3;
else if (hoursSincePlay < 48) recencyBoost *= 2;
else if (hoursSincePlay < 72) recencyBoost *= 1.5;
if (hoursSinceUnlock < 24) recencyBoost *= 2.5;
else if (hoursSinceUnlock < 48) recencyBoost *= 1.8;
// Recent volume boost
const recentVolumeBoost = Math.min((act.recentPlays || 0) / 100, 5) + Math.min((act.recentUnlocks || 0) / 5, 3);
// New upload bonus
let uploadBonus = 0;
if (t.publishedAt) {
const hoursSinceUpload = (now - new Date(t.publishedAt).getTime()) / HOUR;
if (hoursSinceUpload < 24) uploadBonus = 500;
else if (hoursSinceUpload < 48) uploadBonus = 300;
else if (hoursSinceUpload < 72) uploadBonus = 100;
}
const trendScore = (baseScore * recencyBoost) + (recentVolumeBoost * 100) + uploadBonus;
const prevRank = prevRankings[t.id] || null;
return { ...t, _trendScore: trendScore, _recencyBoost: recencyBoost, _recentPlays: act.recentPlays || 0, _recentUnlocks: act.recentUnlocks || 0, _prevRank: prevRank };
}).sort((a, b) => b._trendScore - a._trendScore);
// Save current rankings for position-change tracking
const newRankings = {};
ranked.forEach((t, i) => { newRankings[t.id] = i + 1; });
try { localStorage.setItem('bf_current_rankings', JSON.stringify(newRankings)); } catch {}
return ranked.map((t, i) => ({
...t,
_rank: i + 1,
_rankChange: t._prevRank ? (t._prevRank - (i + 1)) : 0
}));
};
// ===== RISING BEATS =====
const getRisingBeats = () => {
const recentActivity = {};
try { Object.assign(recentActivity, JSON.parse(localStorage.getItem('bf_recent_activity') || '{}')); } catch {}
const shareCounts = {};
try { Object.assign(shareCounts, JSON.parse(localStorage.getItem('bf_track_shares') || '{}')); } catch {}
const unlockCounts = {};
try { JSON.parse(localStorage.getItem('bf_download_states') || '[]').forEach(s => { if (s.unlocked) unlockCounts[s.trackId] = (unlockCounts[s.trackId] || 0) + 1; }); } catch {}
const now = Date.now();
const HOUR = 3600000;
return getAllTracks().map(t => {
const p = parseFloat(t.plays || '0');
const totalPlays = (t.plays || '').includes('K') ? p * 1000 : p;
const shares = shareCounts[t.id] || 0;
const unlocks = unlockCounts[t.id] || 0;
const act = recentActivity[t.id] || { recentPlays: 0, recentUnlocks: 0, recentShares: 0 };
const recentScore = ((act.recentPlays || 0) * 1) + ((act.recentUnlocks || 0) * 10) + ((act.recentShares || 0) * 5);
// Velocity: how fast is it growing relative to total
const velocityScore = totalPlays > 0 ? (recentScore / totalPlays) * 1000 : (recentScore > 0 ? 500 : 0);
// New upload bonus β fresh tracks get a big boost
let uploadBonus = 0;
if (t.publishedAt) {
const hoursSinceUpload = (now - new Date(t.publishedAt).getTime()) / HOUR;
if (hoursSinceUpload < 12) uploadBonus = 800;
else if (hoursSinceUpload < 24) uploadBonus = 500;
else if (hoursSinceUpload < 48) uploadBonus = 300;
else if (hoursSinceUpload < 72) uploadBonus = 100;
}
// Also check date field for older tracks
if (!t.publishedAt && t.date) {
const d = t.date.toLowerCase();
if (d.includes('just') || d.includes('minute') || d.includes('hour')) uploadBonus = Math.max(uploadBonus, 400);
else if (d.includes('1 day') || d.includes('2 day')) uploadBonus = Math.max(uploadBonus, 200);
}
const risingScore = (recentScore * 3) + velocityScore + uploadBonus;
return {
...t,
_risingScore: risingScore,
_recentPlays: act.recentPlays || 0,
_recentUnlocks: act.recentUnlocks || 0,
_recentShares: act.recentShares || 0,
_velocity: velocityScore
};
})
.filter(t => t._risingScore > 10)
.sort((a, b) => b._risingScore - a._risingScore);
};
// ===== TREND INDICATOR =====
const getTrackTrendIndicator = (trackId) => {
try {
const prev = JSON.parse(localStorage.getItem('bf_prev_rankings') || '{}');
const cur = JSON.parse(localStorage.getItem('bf_current_rankings') || '{}');
const prevPos = prev[trackId];
const curPos = cur[trackId];
if (!prevPos && !curPos) return { direction: 'new', arrow: 'π', label: 'New', cssClass: 'text-gray-400' };
if (!prevPos) return { direction: 'new', arrow: 'π', label: 'New', cssClass: 'text-cyan-400' };
const change = prevPos - curPos;
if (change > 2) return { direction: 'up', arrow: 'β', label: '+' + change, cssClass: 'text-green-400' };
if (change > 0) return { direction: 'up', arrow: 'β', label: '+' + change, cssClass: 'text-green-400' };
if (change < -2) return { direction: 'down', arrow: 'β', label: '' + change, cssClass: 'text-red-400' };
if (change < 0) return { direction: 'down', arrow: 'β', label: '' + change, cssClass: 'text-red-400' };
return { direction: 'stable', arrow: 'β', label: 'β', cssClass: 'text-gray-600' };
} catch {
return { direction: 'stable', arrow: 'β', label: 'β', cssClass: 'text-gray-600' };
}
};
// ===== ACTIVITY RECORDING =====
const recordActivity = (trackId, type) => {
try {
let activity = JSON.parse(localStorage.getItem('bf_recent_activity') || '{}');
if (!activity[trackId]) activity[trackId] = { lastPlay: 0, lastUnlock: 0, lastShare: 0, recentPlays: 0, recentUnlocks: 0, recentShares: 0 };
const now = Date.now();
const cutoff = now - (48 * 3600000); // 48h window
// Reset counters if data is stale
if ((activity[trackId]._lastReset || 0) < cutoff) {
activity[trackId].recentPlays = 0;
activity[trackId].recentUnlocks = 0;
activity[trackId].recentShares = 0;
activity[trackId]._lastReset = now;
}
if (type === 'play') { activity[trackId].lastPlay = now; activity[trackId].recentPlays = (activity[trackId].recentPlays || 0) + 1; }
else if (type === 'unlock') { activity[trackId].lastUnlock = now; activity[trackId].recentUnlocks = (activity[trackId].recentUnlocks || 0) + 1; }
else if (type === 'share') { activity[trackId].lastShare = now; activity[trackId].recentShares = (activity[trackId].recentShares || 0) + 1; }
localStorage.setItem('bf_recent_activity', JSON.stringify(activity));
} catch {}
};
// ===== SIMULATE RECENT ACTIVITY (demo data) =====
const simulateRecentActivity = () => {
try {
let activity = JSON.parse(localStorage.getItem('bf_recent_activity') || '{}');
const allTracks = getAllTracks();
const now = Date.now();
const HOUR = 3600000;
// Generate plausible recent activity for top tracks
allTracks.forEach((t, i) => {
if (!activity[t.id]) activity[t.id] = { lastPlay: 0, lastUnlock: 0, lastShare: 0, recentPlays: 0, recentUnlocks: 0, recentShares: 0, _lastReset: now };
const p = parseFloat(t.plays || '0');
const totalPlays = (t.plays || '').includes('K') ? p * 1000 : p;
// Top tracks get more recent activity
if (i < 3) {
activity[t.id].recentPlays = Math.floor(200 + Math.random() * 400);
activity[t.id].recentUnlocks = Math.floor(10 + Math.random() * 25);
activity[t.id].recentShares = Math.floor(5 + Math.random() * 15);
activity[t.id].lastPlay = now - (Math.random() * 12 * HOUR);
activity[t.id].lastUnlock = now - (Math.random() * 24 * HOUR);
} else if (i < 6) {
activity[t.id].recentPlays = Math.floor(80 + Math.random() * 200);
activity[t.id].recentUnlocks = Math.floor(3 + Math.random() * 12);
activity[t.id].recentShares = Math.floor(2 + Math.random() * 8);
activity[t.id].lastPlay = now - (Math.random() * 24 * HOUR);
} else {
activity[t.id].recentPlays = Math.floor(10 + Math.random() * 80);
activity[t.id].recentUnlocks = Math.floor(Math.random() * 5);
activity[t.id].recentShares = Math.floor(Math.random() * 3);
}
// Freshly uploaded tracks get extra boost
if (t.date && (t.date.includes('Just') || t.date.includes('hour') || t.date.includes('minute'))) {
activity[t.id].recentPlays += Math.floor(100 + Math.random() * 300);
activity[t.id].recentUnlocks += Math.floor(5 + Math.random() * 15);
activity[t.id].lastPlay = now - (Math.random() * 4 * HOUR);
}
});
activity._simulated = true;
localStorage.setItem('bf_recent_activity', JSON.stringify(activity));
} catch {}
};
// ===== SAVE RANKINGS SNAPSHOT =====
const saveRankingSnapshot = () => {
try {
const current = JSON.parse(localStorage.getItem('bf_current_rankings') || '{}');
localStorage.setItem('bf_prev_rankings', JSON.stringify(current));
} catch {}
};
// ===== SHARE TRACKING =====
const trackShare = (trackId) => {
try {
let shares = JSON.parse(localStorage.getItem('bf_track_shares') || '{}');
shares[trackId] = (shares[trackId] || 0) + 1;
localStorage.setItem('bf_track_shares', JSON.stringify(shares));
recordActivity(trackId, 'share');
} catch {}
};
const getShareCount = (trackId) => {
try { return (JSON.parse(localStorage.getItem('bf_track_shares') || '{}'))[trackId] || 0; }
catch { return 0; }
};
const getUnlockCount = (trackId) => {
try { return JSON.parse(localStorage.getItem('bf_download_states') || '[]').filter(s => s.trackId === trackId && s.unlocked).length; }
catch { return 0; }
};
// ===== REFERRAL SYSTEM =====
const getReferralCode = () => {
const user = getCurrentUser();
if (!user) return null;
try {
let refs = JSON.parse(localStorage.getItem('bf_referral_codes') || '{}');
const uid = user.id;
if (refs[uid]) return refs[uid];
const prefix = (user.username || 'usr').substring(0, 3).toUpperCase();
const code = prefix + Math.floor(1000 + Math.random() * 9000);
refs[uid] = code;
localStorage.setItem('bf_referral_codes', JSON.stringify(refs));
return code;
} catch { return null; }
};
const recordReferralSignup = (referralCode) => {
if (!referralCode) return;
try {
let referrals = JSON.parse(localStorage.getItem('bf_referrals') || '[]');
referrals.push({ code: referralCode, newUserId: getCurrentUser()?.id, date: new Date().toISOString(), status: 'pending' });
localStorage.setItem('bf_referrals', JSON.stringify(referrals));
} catch {}
};
const getReferralStats = () => {
const user = getCurrentUser();
if (!user) return { code: null, clicks: 0, signups: 0, earnings: 0 };
const code = getReferralCode();
try {
const referrals = JSON.parse(localStorage.getItem('bf_referrals') || '[]');
const clicks = JSON.parse(localStorage.getItem('bf_referral_clicks') || '{}');
const userRefs = referrals.filter(r => r.code === code);
return { code, clicks: clicks[code] || 0, signups: userRefs.length, earnings: userRefs.filter(r => r.status === 'confirmed').length * 5, pendingEarnings: userRefs.filter(r => r.status === 'pending').length * 5 };
} catch { return { code, clicks: 0, signups: 0, earnings: 0 }; }
};
const trackReferralClick = (referralCode) => {
if (!referralCode) return;
try {
let clicks = JSON.parse(localStorage.getItem('bf_referral_clicks') || '{}');
clicks[referralCode] = (clicks[referralCode] || 0) + 1;
localStorage.setItem('bf_referral_clicks', JSON.stringify(clicks));
sessionStorage.setItem('bf_pending_referral', referralCode);
} catch {}
};
// ===== SHARE MODAL =====
const showShareModal = (trackTitle, artistName, trackId) => {
if (document.getElementById('bfShareModal')) return;
const baseUrl = window.location.origin;
let url = baseUrl + '/track.html?id=' + trackId;
if (isLoggedIn()) { const rc = getReferralCode(); if (rc) url += '&ref=' + rc; }
const shareText = 'Check out this beat on BeatFridge: ' + trackTitle + ' by ' + artistName;
const safeT = String(trackTitle).replace(/'/g, "\\'").replace(/"/g, '"');
const safeA = String(artistName).replace(/'/g, "\\'").replace(/"/g, '"');
const modal = document.createElement('div');
modal.id = 'bfShareModal';
modal.innerHTML = `
<div class="bf-signin-overlay" onclick="BF.closeShareModal()"></div>
<div class="bf-signin-modal">
<div class="bf-signin-card" style="max-width:380px">
<div class="flex items-center justify-between mb-5">
<h3 class="text-lg font-bold text-white flex items-center gap-2"><i data-lucide="share-2" class="w-5 h-5 text-purple-400"></i>Share This Beat</h3>
<button onclick="BF.closeShareModal()" class="text-gray-400 hover:text-white transition"><i data-lucide="x" class="w-5 h-5"></i></button>
</div>
<div class="flex items-center gap-3 mb-4 p-3 rounded-xl bg-white/5">
<i data-lucide="music" class="w-5 h-5 text-cyan-400 flex-shrink-0"></i>
<div class="min-w-0"><p class="text-sm font-medium text-white truncate">${trackTitle}</p><p class="text-xs text-gray-500">${artistName}</p></div>
</div>
<p class="text-xs text-gray-500 mb-4 px-1">"${shareText}"</p>
<div class="space-y-2 mb-4">
<button onclick="BF.shareViaWhatsApp(${trackId},'${safeT}','${safeA}')" class="bf-share-platform bg-green-500/5 border-green-500/20 hover:bg-green-500/10 hover:border-green-500/40">
<div class="w-10 h-10 rounded-full bg-green-500/15 flex items-center justify-center flex-shrink-0"><svg viewBox="0 0 24 24" class="w-5 h-5 text-green-400" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.981.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.88 11.88 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg></div>
<div><p class="text-sm font-semibold text-green-400">WhatsApp</p><p class="text-xs text-gray-500">Share via WhatsApp</p></div>
</button>
<button onclick="BF.shareViaFacebook(${trackId},'${safeT}','${safeA}')" class="bf-share-platform bg-blue-500/5 border-blue-500/20 hover:bg-blue-500/10 hover:border-blue-500/40">
<div class="w-10 h-10 rounded-full bg-blue-500/15 flex items-center justify-center flex-shrink-0"><i data-lucide="facebook" class="w-5 h-5 text-blue-400"></i></div>
<div><p class="text-sm font-semibold text-blue-400">Facebook</p><p class="text-xs text-gray-500">Share on your timeline</p></div>
</button>
<button onclick="BF.shareViaTwitter(${trackId},'${safeT}','${safeA}')" class="bf-share-platform bg-sky-500/5 border-sky-500/20 hover:bg-sky-500/10 hover:border-sky-500/40">
<div class="w-10 h-10 rounded-full bg-sky-500/15 flex items-center justify-center flex-shrink-0"><i data-lucide="twitter" class="w-5 h-5 text-sky-400"></i></div>
<div><p class="text-sm font-semibold text-sky-400">Twitter / X</p><p class="text-xs text-gray-500">Tweet this beat</p></div>
</button>
<button onclick="BF.copyTrackLink(${trackId},'${safeT}','${safeA}')" class="bf-share-platform bg-white/[0.03] border-white/10 hover:bg-white/[0.06] hover:border-white/20">
<div class="w-10 h-10 rounded-full bg-white/10 flex items-center justify-center flex-shrink-0"><i data-lucide="link" class="w-5 h-5 text-gray-400"></i></div>
<div><p class="text-sm font-semibold text-white">Copy Link</p><p class="text-xs text-gray-500">Copy track URL to clipboard</p></div>
</button>
</div>
${isLoggedIn() ? `<div class="p-3 rounded-xl bg-orange-500/5 border border-orange-500/15"><div class="flex items-center gap-2 mb-1"><i data-lucide="gift" class="w-4 h-4 text-orange-400"></i><p class="text-xs font-semibold text-orange-400">Share & Earn</p></div><p class="text-[11px] text-gray-500">Your link includes your referral code. Earn rewards when new users sign up through your shares.</p></div>` : ''}
</div>
</div>
`;
document.body.appendChild(modal);
if (window.lucide) lucide.createIcons();
};
const closeShareModal = () => { document.getElementById('bfShareModal')?.remove(); };
const shareViaWhatsApp = (trackId, trackTitle, artistName) => {
trackShare(trackId);
let url = window.location.origin + '/track.html?id=' + trackId;
if (isLoggedIn()) { const rc = getReferralCode(); if (rc) url += '&ref=' + rc; }
const text = 'Check out this beat on BeatFridge: ' + trackTitle + ' by ' + artistName + ' ' + url;
window.open('https://wa.me/?text=' + encodeURIComponent(text), '_blank');
closeShareModal();
showToast('Shared via WhatsApp π±');
};
const shareViaFacebook = (trackId, trackTitle, artistName) => {
trackShare(trackId);
let url = window.location.origin + '/track.html?id=' + trackId;
if (isLoggedIn()) { const rc = getReferralCode(); if (rc) url += '&ref=' + rc; }
window.open('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(url), '_blank');
closeShareModal();
showToast('Shared on Facebook π');
};
const shareViaTwitter = (trackId, trackTitle, artistName) => {
trackShare(trackId);
let url = window.location.origin + '/track.html?id=' + trackId;
if (isLoggedIn()) { const rc = getReferralCode(); if (rc) url += '&ref=' + rc; }
const text = 'Check out this beat on BeatFridge: ' + trackTitle + ' by ' + artistName + ' π΅ ' + url;
window.open('https://twitter.com/intent/tweet?text=' + encodeURIComponent(text), '_blank');
closeShareModal();
showToast('Shared on Twitter π¦');
};
const copyTrackLink = (trackId, trackTitle, artistName) => {
trackShare(trackId);
let url = window.location.origin + '/track.html?id=' + trackId;
if (isLoggedIn()) { const rc = getReferralCode(); if (rc) url += '&ref=' + rc; }
navigator.clipboard.writeText(url).then(() => {
closeShareModal();
showToast('Link copied! Share it anywhere π');
}).catch(() => {
const input = document.createElement('input');
input.value = url;
document.body.appendChild(input);
input.select();
document.execCommand('copy');
input.remove();
closeShareModal();
showToast('Link copied! π');
});
};
// ===== RENDER SHARE BUTTON =====
const renderShare = (trackId, trackTitle, artistName) => {
const safeTitle = String(trackTitle).replace(/'/g, "\\'").replace(/"/g, '"');
const safeArtist = String(artistName).replace(/'/g, "\\'").replace(/"/g, '"');
return `<button class="bf-share-btn" onclick="event.stopPropagation(); BF.showShareModal('${safeTitle}', '${safeArtist}', ${trackId})"><i data-lucide="share-2" class="w-3 h-3"></i>Share</button>`;
};
const getFreshUploads = () => {
return getAllTracks().filter(t => t.date && (t.date.includes('day') || t.date.includes('hour') || t.date.includes('Just') || t.date.includes('minute')));
};
const searchTracks = (query) => {
const q = query.toLowerCase().trim();
if (!q) return [];
return getAllTracks().filter(t => t.title.toLowerCase().includes(q) || t.artist.toLowerCase().includes(q) || (t.genre && t.genre.toLowerCase().includes(q)));
};
const searchArtists = (query) => {
const q = query.toLowerCase().trim();
if (!q) return [];
return getArtists().filter(a => a.name.toLowerCase().includes(q) || (a.genre && a.genre.toLowerCase().includes(q)));
};
// ===== UI: STYLES =====
const injectStyles = () => {
if (document.getElementById('bf-app-styles')) return;
const style = document.createElement('style');
style.id = 'bf-app-styles';
style.textContent = `
.bottom-tab-bar {
position: fixed; bottom: 0; left: 0; right: 0; z-index: 60;
display: flex; align-items: center; justify-content: space-around;
height: 56px; background: rgba(15,15,15,0.95); backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px); border-top: 1px solid rgba(255,255,255,0.08);
padding: 0 8px; padding-bottom: env(safe-area-inset-bottom, 0px);
}
.bottom-tab {
display: flex; flex-direction: column; align-items: center; justify-content: center;
flex: 1; height: 100%; text-decoration: none; color: #6b7280;
transition: color 0.2s; font-size: 10px; gap: 2px; position: relative;
}
.bottom-tab i, .bottom-tab svg { width: 20px; height: 20px; }
.bottom-tab.active { color: #00d4ff; }
.bottom-tab:hover { color: #9ca3af; }
.bottom-tab.active:hover { color: #00d4ff; }
.bottom-tab-center {
position: relative; top: -10px;
background: linear-gradient(135deg, #00d4ff, #7c3aed);
border-radius: 50%; width: 48px; height: 48px; flex: none;
display: flex; align-items: center; justify-content: center;
box-shadow: 0 0 20px rgba(0,212,255,0.3); margin: 0 4px;
}
.bottom-tab-center i, .bottom-tab-center svg { width: 24px; height: 24px; color: #000; }
.bottom-tab-center span { display: none; }
.bottom-tab-center.active { box-shadow: 0 0 30px rgba(0,212,255,0.5); }
@media (min-width: 768px) {
.bottom-tab-bar { display: none; }
}
.bf-signin-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.8); backdrop-filter: blur(8px); z-index: 70; }
.bf-signin-modal { position: fixed; top: 50%; left: 50%; transform: translate(-50%,-50%); z-index: 71; width: 100%; max-width: 420px; padding: 0 1rem; }
.bf-signin-card { background: #111; border: 1px solid rgba(255,255,255,0.1); border-radius: 1rem; padding: 1.5rem; }
.bf-content-shift { padding-bottom: 0 !important; }
@media (max-width: 767px) {
.sticky-player { bottom: 56px !important; }
body { padding-bottom: 120px !important; }
}
.bf-locked-overlay { position: absolute; inset: 0; background: rgba(0,0,0,0.6); backdrop-filter: blur(3px); display: flex; flex-direction: column; align-items: center; justify-content: center; border-radius: inherit; z-index: 10; pointer-events: none; }
.bf-superfan-badge { background: linear-gradient(135deg, #f97316, #ef4444); color: white; font-size: 10px; font-weight: 600; padding: 3px 10px; border-radius: 9999px; display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; }
.bf-superfan-btn { transition: all 0.2s ease; }
.bf-superfan-btn:hover { transform: scale(1.02); }
.bf-payment-input {
width: 100%; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);
border-radius: 0.75rem; padding: 0.75rem 1rem; font-size: 0.875rem;
color: white; outline: none; transition: border-color 0.2s, background 0.2s;
}
.bf-payment-input:focus { border-color: rgba(249,115,22,0.5); background: rgba(255,255,255,0.07); }
.bf-payment-input::placeholder { color: #4b5563; }
.bf-payment-input.error { border-color: rgba(239,68,68,0.5); }
@keyframes bf-spin { to { transform: rotate(360deg); } }
.bf-download-btn {
display: inline-flex; align-items: center; gap: 4px;
font-size: 11px; font-weight: 500; color: #9ca3af;
background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);
cursor: pointer; padding: 4px 10px; border-radius: 6px;
transition: all 0.2s;
}
.bf-download-btn:hover { color: #00d4ff; border-color: rgba(0,212,255,0.3); background: rgba(0,212,255,0.05); }
.bf-download-btn.bf-dl-free { color: #f97316; border-color: rgba(249,115,22,0.3); background: rgba(249,115,22,0.08); }
.bf-download-btn.bf-dl-free:hover { color: #fb923c; border-color: rgba(249,115,22,0.5); background: rgba(249,115,22,0.12); }
.bf-download-btn.bf-dl-unlocked { color: #22c55e; border-color: rgba(34,197,94,0.3); background: rgba(34,197,94,0.08); }
.bf-download-btn.bf-dl-unlocked:hover { color: #4ade80; border-color: rgba(34,197,94,0.5); background: rgba(34,197,94,0.12); }
.bf-unlock-btn {
display: inline-flex; align-items: center; gap: 4px;
font-size: 11px; font-weight: 600; color: #f97316;
background: linear-gradient(135deg, rgba(249,115,22,0.12), rgba(239,68,68,0.08));
border: 1px solid rgba(249,115,22,0.3);
cursor: pointer; padding: 5px 12px; border-radius: 8px;
transition: all 0.2s;
box-shadow: 0 0 10px rgba(249,115,22,0.08);
}
.bf-unlock-btn:hover {
background: linear-gradient(135deg, rgba(249,115,22,0.2), rgba(239,68,68,0.12));
border-color: rgba(249,115,22,0.5);
box-shadow: 0 0 16px rgba(249,115,22,0.15);
transform: translateY(-1px);
}
.bf-sf-free-label {
display: inline-flex; align-items: center; gap: 3px;
font-size: 9px; color: #f97316; font-weight: 600; margin-top: 2px;
background: rgba(249,115,22,0.08); padding: 2px 8px; border-radius: 4px;
border: 1px solid rgba(249,115,22,0.15);
}
.bf-quick-amount {
flex: 1; padding: 10px 0; border-radius: 10px;
background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);
color: #d1d5db; font-size: 14px; font-weight: 600;
cursor: pointer; transition: all 0.2s; text-align: center;
}
.bf-quick-amount:hover { background: rgba(0,212,255,0.1); border-color: rgba(0,212,255,0.3); color: #00d4ff; }
.bf-quick-amount.active { background: rgba(0,212,255,0.15); border-color: rgba(0,212,255,0.5); color: #00d4ff; box-shadow: 0 0 12px rgba(0,212,255,0.1); }
@keyframes bfSuccessPulse { 0% { transform: scale(0.5); opacity: 0; } 50% { transform: scale(1.15); } 100% { transform: scale(1); opacity: 1; } }
@keyframes bfSuccessFade { 0% { opacity: 0; transform: translateY(8px); } 100% { opacity: 1; transform: translateY(0); } }
.bf-success-pulse { animation: bfSuccessPulse 0.4s cubic-bezier(0.34, 1.56, 0.64, 1) forwards; }
.bf-pay-success h3, .bf-pay-success p, .bf-pay-success div:not(.bf-success-pulse) { animation: bfSuccessFade 0.35s ease forwards; }
.bf-pay-success h3 { animation-delay: 0.1s; opacity: 0; }
.bf-pay-success p { animation-delay: 0.2s; opacity: 0; }
.bf-pay-success .bf-success-pulse + div { animation-delay: 0.3s; opacity: 0; }
.bf-share-btn {
display: inline-flex; align-items: center; gap: 4px;
font-size: 11px; font-weight: 500; color: #9ca3af;
background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);
cursor: pointer; padding: 4px 10px; border-radius: 6px;
transition: all 0.2s;
}
.bf-share-btn:hover { color: #a78bfa; border-color: rgba(167,139,250,0.3); background: rgba(167,139,250,0.08); }
.bf-share-platform { width: 100%; padding: 12px 16px; border-radius: 12px; display: flex; align-items: center; gap: 12px; cursor: pointer; transition: all 0.2s; border: 1px solid transparent; }
.bf-share-platform:hover { transform: translateX(2px); }
.bf-social-proof { display: flex; align-items: center; gap: 6px; font-size: 11px; color: #f97316; font-weight: 600; background: rgba(249,115,22,0.08); padding: 4px 10px; border-radius: 6px; border: 1px solid rgba(249,115,22,0.15); }
.bf-urgency-badge { display: inline-flex; align-items: center; gap: 4px; font-size: 10px; color: #f97316; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; background: rgba(249,115,22,0.06); padding: 3px 8px; border-radius: 4px; animation: bfUrgencyPulse 2s ease-in-out infinite; }
@keyframes bfUrgencyPulse { 0%,100% { opacity: 1; } 50% { opacity: 0.7; } }
.bf-preview-snippet { position: relative; height: 52px; background: rgba(255,255,255,0.03); border-radius: 10px; overflow: hidden; cursor: pointer; border: 1px solid rgba(255,255,255,0.06); transition: border-color 0.2s; }
.bf-preview-snippet:hover { border-color: rgba(0,212,255,0.3); }
.bf-preview-highlight { position: absolute; top: 0; bottom: 0; background: rgba(0,212,255,0.06); border-left: 2px solid rgba(0,212,255,0.4); border-right: 2px solid rgba(0,212,255,0.4); pointer-events: none; }
.bf-preview-play { position: absolute; left: 10px; top: 50%; transform: translateY(-50%); width: 30px; height: 30px; border-radius: 50%; background: rgba(0,212,255,0.9); display: flex; align-items: center; justify-content: center; cursor: pointer; z-index: 2; transition: transform 0.15s, box-shadow 0.15s; box-shadow: 0 0 12px rgba(0,212,255,0.25); }
.bf-preview-play:hover { transform: translateY(-50%) scale(1.1); box-shadow: 0 0 20px rgba(0,212,255,0.4); }
.bf-preview-wave { display: flex; align-items: center; gap: 1.5px; height: 100%; padding: 0 12px 0 50px; }
.bf-preview-wave span { width: 2px; border-radius: 1px; flex-shrink: 0; background: rgba(255,255,255,0.1); transition: background 0.3s; }
.bf-preview-snippet.bf-preview-active .bf-preview-wave span { animation: bfPreviewWave 0.35s ease-in-out infinite alternate; }
.bf-preview-snippet.bf-preview-active .bf-preview-highlight + .bf-preview-wave span { background: rgba(255,255,255,0.12); }
@keyframes bfPreviewWave { 0% { transform: scaleY(0.3); } 100% { transform: scaleY(1); } }
@keyframes bfUnlockCelebrate { 0% { transform: scale(0) rotate(-10deg); opacity: 0; } 60% { transform: scale(1.15) rotate(3deg); opacity: 1; } 100% { transform: scale(1) rotate(0); opacity: 1; } }
@keyframes bfDownloadProgress { 0% { width: 0; } 100% { width: 100%; } }
@keyframes bfConfettiDrop { 0% { transform: translateY(0) rotate(0deg); opacity: 1; } 100% { transform: translateY(60px) rotate(360deg); opacity: 0; } }
.bf-unlock-success-icon { animation: bfUnlockCelebrate 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards; }
.bf-download-progress { height: 4px; background: rgba(255,255,255,0.08); border-radius: 3px; overflow: hidden; margin-top: 16px; width: 80%; margin-left: auto; margin-right: auto; }
.bf-download-progress-bar { height: 100%; background: linear-gradient(90deg, #22c55e, #4ade80); border-radius: 3px; animation: bfDownloadProgress 1.8s ease forwards; }
.bf-confetti-particle { position: absolute; width: 6px; height: 6px; border-radius: 50%; animation: bfConfettiDrop 1.2s ease forwards; pointer-events: none; }
.bf-support-cta { font-size: 12px; color: #9ca3af; display: flex; align-items: center; gap: 6px; margin-bottom: 12px; }
.bf-support-cta strong { color: #f97316; }
.bf-like-btn { display: inline-flex; align-items: center; gap: 4px; font-size: 11px; font-weight: 500; color: #9ca3af; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); cursor: pointer; padding: 4px 10px; border-radius: 6px; transition: all 0.2s; }
.bf-like-btn:hover { color: #f97316; border-color: rgba(249,115,22,0.3); background: rgba(249,115,22,0.08); }
.bf-like-btn.bf-liked { color: #f97316; border-color: rgba(249,115,22,0.3); background: rgba(249,115,22,0.1); }
.bf-replay-btn { display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; border-radius: 50%; background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.1); cursor: pointer; transition: all 0.2s; color: #9ca3af; }
.bf-replay-btn:hover { background: rgba(0,212,255,0.15); border-color: rgba(0,212,255,0.4); color: #00d4ff; transform: scale(1.08); }
.bf-rec-card { transition: all 0.3s cubic-bezier(0.4,0,0.2,1); cursor: pointer; }
.bf-rec-card:hover { transform: translateY(-3px); box-shadow: 0 12px 24px -6px rgba(0,212,255,0.12); }
.bf-player-ctrl { width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.15s; border: none; color: #9ca3af; background: transparent; }
.bf-player-ctrl:hover { color: #ffffff; background: rgba(255,255,255,0.08); }
.bf-player-ctrl:active { transform: scale(0.9); }
`;
document.head.appendChild(style);
};
// ===== UI: BOTTOM NAV =====
const injectBottomNav = (activeTab) => {
if (document.getElementById('bottomTabBar')) return;
const loggedIn = isLoggedIn();
const user = getCurrentUser();
const role = user ? (user.role || (user.isArtist ? 'producer' : null)) : null;
let tabs;
if (role === 'fan') {
tabs = [
{ id: 'home', icon: 'home', label: 'Home', href: 'index.html' },
{ id: 'search', icon: 'search', label: 'Search', href: 'search.html' },
{ id: 'library', icon: 'library', label: 'Library', href: 'library.html' },
{ id: 'profile', icon: 'user', label: 'Profile', href: 'profile.html' }
];
} else if (role === 'producer') {
tabs = [
{ id: 'home', icon: 'home', label: 'Home', href: 'index.html' },
{ id: 'search', icon: 'search', label: 'Search', href: 'search.html' },
{ id: 'upload', icon: 'plus', label: 'Upload', href: 'upload.html', center: true },
{ id: 'profile', icon: 'user', label: 'Profile', href: 'profile.html' }
];
} else {
tabs = [
{ id: 'home', icon: 'home', label: 'Home', href: 'index.html' },
{ id: 'search', icon: 'search', label: 'Search', href: 'search.html' },
{ id: 'upload', icon: 'plus', label: 'Upload', href: '#', center: true, action: 'BF.showSignInModal(); return false;' },
{ id: 'signin', icon: 'log-in', label: 'Sign In', href: '#', action: 'BF.showSignInModal(); return false;' }
];
}
const nav = document.createElement('nav');
nav.className = 'bottom-tab-bar';
nav.id = 'bottomTabBar';
nav.innerHTML = tabs.map(tab => {
const isActive = activeTab === tab.id;
const isCenter = tab.center;
const action = tab.action ? `onclick="${tab.action}"` : '';
return `<a href="${tab.href}" class="bottom-tab${isCenter ? ' bottom-tab-center' : ''}${isActive ? ' active' : ''}" ${action}>
<i data-lucide="${tab.icon}"></i><span>${tab.label}</span>
</a>`;
}).join('');
document.body.appendChild(nav);
};
// ===== UI: SIGN IN / SIGN UP MODAL =====
let _signUpRole = 'producer';
const showSignInModal = () => {
if (document.getElementById('bfSignInModal')) return;
const modal = document.createElement('div');
modal.id = 'bfSignInModal';
modal.innerHTML = `
<div class="bf-signin-overlay" onclick="BF.closeSignInModal()"></div>
<div class="bf-signin-modal">
<div class="bf-signin-card">
<div class="flex items-center justify-between mb-6">
<h3 class="text-xl font-bold text-white" id="bfModalTitle">Welcome to BeatFridge</h3>
<button onclick="BF.closeSignInModal()" class="text-gray-400 hover:text-white transition"><i data-lucide="x" class="w-6 h-6"></i></button>
</div>
<!-- Step 1: Choose Account Type -->
<div id="bfStepChooseType">
<p class="text-gray-400 text-sm mb-6">What would you like to do?</p>
<div class="space-y-3 mb-6">
<button onclick="BF.showSignUpForm('producer')" class="w-full p-4 rounded-xl bg-white/5 border border-white/10 hover:border-cyan-500/50 hover:bg-cyan-500/5 transition text-left group">
<div class="flex items-center gap-3">
<div class="w-12 h-12 rounded-full bg-cyan-500/20 flex items-center justify-center flex-shrink-0">
<i data-lucide="music" class="w-6 h-6 text-cyan-400"></i>
</div>
<div>
<p class="font-semibold text-white group-hover:text-cyan-400 transition">I want to upload music</p>
<p class="text-xs text-gray-500 mt-1">Create a Producer account to share your tracks</p>
</div>
</div>
</button>
<button onclick="BF.showSignUpForm('fan')" class="w-full p-4 rounded-xl bg-white/5 border border-white/10 hover:border-purple-500/50 hover:bg-purple-500/5 transition text-left group">
<div class="flex items-center gap-3">
<div class="w-12 h-12 rounded-full bg-purple-500/20 flex items-center justify-center flex-shrink-0">
<i data-lucide="headphones" class="w-6 h-6 text-purple-400"></i>
</div>
<div>
<p class="font-semibold text-white group-hover:text-purple-400 transition">I just want to listen</p>
<p class="text-xs text-gray-500 mt-1">Create a Fan account to discover and enjoy music</p>
</div>
</div>
</button>
</div>
<div class="text-center">
<p class="text-sm text-gray-500">Already have an account? <button onclick="BF.showSignInForm()" class="text-cyan-400 hover:underline">Sign In</button></p>
</div>
</div>
<!-- Step 2: Sign Up Form -->
<div id="bfStepSignUp" class="hidden">
<div class="flex items-center gap-2 mb-4">
<span class="px-3 py-1 rounded-full text-xs font-medium" id="bfRoleBadge"></span>
</div>
<div class="space-y-4">
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Display Name</label>
<input type="text" id="bfSignupName" placeholder="Your display name" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 text-white">
</div>
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Username</label>
<input type="text" id="bfSignupUsername" placeholder="Choose a username" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 text-white">
</div>
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Email</label>
<input type="email" id="bfSignupEmail" placeholder="your@email.com" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 text-white">
</div>
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Password</label>
<input type="password" id="bfSignupPassword" placeholder="Create a password (min 8 chars)" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 text-white" onkeydown="if(event.key==='Enter')BF.handleSignUp()">
</div>
<div id="bfSignupError" class="hidden text-red-400 text-sm"></div>
<button onclick="BF.handleSignUp()" class="w-full py-3 bg-cyan-500 hover:bg-cyan-400 text-black font-semibold rounded-xl transition" id="bfSignupBtn">Create Account</button>
<button onclick="BF.showChooseType()" class="w-full py-2 text-sm text-gray-500 hover:text-white transition">β Back</button>
</div>
</div>
<!-- Step 3: Sign In Form -->
<div id="bfStepSignIn" class="hidden">
<div class="space-y-4">
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Username or Email</label>
<input type="text" id="bfSigninId" placeholder="Enter username or email" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 text-white">
</div>
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Password</label>
<input type="password" id="bfSigninPw" placeholder="Enter password" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 text-white" onkeydown="if(event.key==='Enter')BF.handleSignIn()">
</div>
<div id="bfSigninError" class="hidden text-red-400 text-sm"></div>
<button onclick="BF.handleSignIn()" class="w-full py-3 bg-cyan-500 hover:bg-cyan-400 text-black font-semibold rounded-xl transition">Sign In</button>
<p class="text-sm text-gray-500 text-center">No account? <button onclick="BF.showChooseType()" class="text-cyan-400 hover:underline">Create one</button></p>
</div>
</div>
</div>
</div>
`;
document.body.appendChild(modal);
if (window.lucide) lucide.createIcons();
};
const showSignUpForm = (role) => {
_signUpRole = role;
document.getElementById('bfStepChooseType').classList.add('hidden');
document.getElementById('bfStepSignUp').classList.remove('hidden');
document.getElementById('bfStepSignIn').classList.add('hidden');
document.getElementById('bfModalTitle').textContent = role === 'producer' ? 'Create Producer Account' : 'Create Fan Account';
const badge = document.getElementById('bfRoleBadge');
if (role === 'producer') {
badge.textContent = 'π΅ Producer';
badge.className = 'px-3 py-1 rounded-full text-xs font-medium bg-cyan-500/20 text-cyan-400 border border-cyan-500/30';
document.getElementById('bfSignupBtn').textContent = 'Create Producer Account';
document.getElementById('bfSignupBtn').className = 'w-full py-3 bg-cyan-500 hover:bg-cyan-400 text-black font-semibold rounded-xl transition';
} else {
badge.textContent = 'π§ Fan';
badge.className = 'px-3 py-1 rounded-full text-xs font-medium bg-purple-500/20 text-purple-400 border border-purple-500/30';
document.getElementById('bfSignupBtn').textContent = 'Create Fan Account';
document.getElementById('bfSignupBtn').className = 'w-full py-3 bg-purple-500 hover:bg-purple-400 text-black font-semibold rounded-xl transition';
}
document.getElementById('bfSignupName')?.focus();
if (window.lucide) lucide.createIcons();
};
const showSignInForm = () => {
document.getElementById('bfStepChooseType').classList.add('hidden');
document.getElementById('bfStepSignUp').classList.add('hidden');
document.getElementById('bfStepSignIn').classList.remove('hidden');
document.getElementById('bfModalTitle').textContent = 'Sign In to BeatFridge';
document.getElementById('bfSigninId')?.focus();
};
const showChooseType = () => {
document.getElementById('bfStepChooseType').classList.remove('hidden');
document.getElementById('bfStepSignUp').classList.add('hidden');
document.getElementById('bfStepSignIn').classList.add('hidden');
document.getElementById('bfModalTitle').textContent = 'Welcome to BeatFridge';
};
const handleSignUp = () => {
const name = document.getElementById('bfSignupName')?.value.trim();
const username = document.getElementById('bfSignupUsername')?.value.trim();
const email = document.getElementById('bfSignupEmail')?.value.trim();
const password = document.getElementById('bfSignupPassword')?.value;
const err = document.getElementById('bfSignupError');
if (!username || !email || !password) { err.textContent = 'Please fill in all fields'; err.classList.remove('hidden'); return; }
if (username.length < 3) { err.textContent = 'Username must be at least 3 characters'; err.classList.remove('hidden'); return; }
if (!/^[a-zA-Z0-9_]+$/.test(username)) { err.textContent = 'Username can only contain letters, numbers, and underscores'; err.classList.remove('hidden'); return; }
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { err.textContent = 'Please enter a valid email'; err.classList.remove('hidden'); return; }
if (password.length < 8) { err.textContent = 'Password must be at least 8 characters'; err.classList.remove('hidden'); return; }
const result = signUp({ username, email, password, role: _signUpRole, displayName: name || username });
if (result.success) {
closeSignInModal();
const isProd = result.user.role === 'producer';
showToast(`Welcome, ${result.user.username}! π ${isProd ? 'Start uploading your tracks!' : 'Discover amazing music!'}`);
setTimeout(() => window.location.reload(), 500);
} else {
err.textContent = result.error;
err.classList.remove('hidden');
}
};
const closeSignInModal = () => {
document.getElementById('bfSignInModal')?.remove();
};
const handleSignIn = () => {
const id = document.getElementById('bfSigninId')?.value.trim();
const pw = document.getElementById('bfSigninPw')?.value;
const err = document.getElementById('bfSigninError');
if (!id || !pw) { err.textContent = 'Please fill in all fields'; err.classList.remove('hidden'); return; }
const result = signIn(id, pw);
if (result.success) {
closeSignInModal();
showToast('Welcome back, ' + result.user.username + '!');
setTimeout(() => window.location.reload(), 500);
} else {
err.textContent = result.error;
err.classList.remove('hidden');
}
};
// ===== UI: TOAST =====
const showToast = (message) => {
const toast = document.createElement('div');
toast.className = 'fixed bottom-24 left-1/2 -translate-x-1/2 bg-cyan-500 text-black px-4 py-2 rounded-full text-sm font-medium z-[80] whitespace-nowrap';
toast.style.boxShadow = '0 0 20px rgba(0,212,255,0.3)';
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => { toast.style.opacity = '0'; toast.style.transition = 'opacity 0.3s'; setTimeout(() => toast.remove(), 300); }, 2500);
};
// ===== PLAYER SYNC =====
const syncPlayer = () => {
try {
const track = JSON.parse(localStorage.getItem('currentTrack'));
const playing = localStorage.getItem('isPlaying') === 'true';
const t = document.getElementById('playerTitle');
const a = document.getElementById('playerArtist');
const i = document.getElementById('playerArt');
const p = document.getElementById('playIcon');
if (track && t) t.textContent = track.title;
if (track && a) a.textContent = track.artist;
if (track && i) i.src = track.image;
if (p) { p.setAttribute('data-lucide', playing ? 'pause' : 'play'); if (window.lucide) lucide.createIcons(); }
} catch {}
};
// ===== PLAYER CONTROLS =====
const playTrack = (track, fromQueue) => {
localStorage.setItem('currentTrack', JSON.stringify(track));
localStorage.setItem('isPlaying', 'true');
recordActivity(track.id, 'play');
syncPlayer();
// Update queue context if track is in queue
if (!fromQueue) {
try {
const queue = JSON.parse(localStorage.getItem('bf_play_queue') || '[]');
const idx = queue.findIndex(t => t.id === track.id);
if (idx > -1) {
_queueIndex = idx;
localStorage.setItem('bf_queue_index', String(idx));
}
} catch {}
}
// Add to recently played
try {
let rp = JSON.parse(localStorage.getItem('recentlyPlayed') || '[]');
rp = rp.filter(t => t.id !== track.id);
rp.unshift({ ...track, playedAt: new Date().toISOString() });
if (rp.length > 50) rp.pop();
localStorage.setItem('recentlyPlayed', JSON.stringify(rp));
} catch {}
// Dispatch track change event for UI updates
try { window.dispatchEvent(new CustomEvent('bf:trackChange', { detail: track })); } catch {}
};
const togglePlay = () => {
const current = localStorage.getItem('isPlaying') === 'true';
localStorage.setItem('isPlaying', current ? 'false' : 'true');
syncPlayer();
};
// ===== TOP NAV AUTH UPDATE =====
const updateTopNav = () => {
const user = getCurrentUser();
const avatarEl = document.getElementById('topNavAvatar');
if (avatarEl && user) {
avatarEl.src = user.avatar || `http://static.photos/people/200x200/42`;
avatarEl.onclick = () => { window.location.href = 'profile.html'; };
}
};
// ===== TOP NAV ROLE ADJUSTMENT =====
const adjustTopNav = () => {
const user = getCurrentUser();
const role = user ? (user.role || (user.isArtist ? 'producer' : null)) : null;
if (role === 'fan') {
document.querySelectorAll('a[href="upload.html"]').forEach(el => el.style.display = 'none');
document.querySelectorAll('a[href="analytics.html"]').forEach(el => el.style.display = 'none');
}
};
// ===== SUPER FAN STATE =====
const migrateSuperFanData = () => {
const key = 'bf_superfan';
try {
let subs = JSON.parse(localStorage.getItem(key) || '[]');
if (subs.length && typeof subs[0] === 'string') {
const migrated = subs.map(slug => ({
slug: slug,
name: slug.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' '),
image: '',
date: new Date().toISOString(),
active: true
}));
localStorage.setItem(key, JSON.stringify(migrated));
}
} catch (e) { console.error('Super Fan migration error:', e); }
};
const getSuperFanSubscriptions = () => {
try {
migrateSuperFanData();
const subs = JSON.parse(localStorage.getItem('bf_superfan') || '[]');
return subs.filter(s => typeof s !== 'string' && s.active !== false);
} catch { return []; }
};
const cancelSuperFanSubscription = (artistSlug) => {
const key = 'bf_superfan';
migrateSuperFanData();
let subs = [];
try { subs = JSON.parse(localStorage.getItem(key) || '[]'); } catch { subs = []; }
const index = subs.findIndex(s => typeof s === 'string' ? s === artistSlug : s.slug === artistSlug);
if (index > -1) {
const name = typeof subs[index] === 'string' ? artistSlug : subs[index].name;
subs.splice(index, 1);
localStorage.setItem(key, JSON.stringify(subs));
updateSuperFanButtons();
showToast('Super Fan subscription cancelled for ' + name);
return true;
}
return false;
};
// ===== SUPER FAN UI =====
let _sfArtistName = '';
let _sfArtistImage = '';
let _sfRetryAttempt = 0;
let _dlTrackTitle = '';
let _dlArtistName = '';
let _dlTrackId = null;
let _dlAmount = null;
const showSuperFanModal = (artistName, artistImage) => {
if (document.getElementById('bfSuperFanModal')) return;
if (isSuperFanOf(artistName)) {
showToast('You are already a Super Fan of ' + artistName + ' \ud83c\udfa7');
return;
}
_sfArtistName = artistName;
_sfArtistImage = artistImage;
const modal = document.createElement('div');
modal.id = 'bfSuperFanModal';
modal.innerHTML = `
<div class="bf-signin-overlay" onclick="BF.closeSuperFanModal()"></div>
<div class="bf-signin-modal">
<div class="bf-signin-card" style="max-width:420px">
<div class="flex items-center justify-between mb-6">
<h3 class="text-xl font-bold text-white">Become a Super Fan</h3>
<button onclick="BF.closeSuperFanModal()" class="text-gray-400 hover:text-white transition"><i data-lucide="x" class="w-6 h-6"></i></button>
</div>
<!-- Step 1: Summary -->
<div id="bfSfStep1">
<div class="flex items-center gap-4 mb-6">
<div class="w-16 h-16 rounded-full overflow-hidden border-2 border-orange-500/50 flex-shrink-0">
<img src="${artistImage}" class="w-full h-full object-cover">
</div>
<div class="min-w-0">
<p class="font-semibold text-white text-lg truncate">${artistName}</p>
<p class="text-sm text-gray-400">Support this artist and unlock exclusive content</p>
</div>
</div>
<div class="p-4 rounded-xl bg-gradient-to-r from-orange-500/10 to-red-500/10 border border-orange-500/20 mb-6">
<div class="flex items-center justify-between mb-4">
<span class="text-sm text-gray-300">Monthly subscription</span>
<span class="text-xl font-bold text-orange-400">$25<span class="text-sm text-gray-500 font-normal">/mo</span></span>
</div>
<div class="space-y-2.5">
<div class="flex items-center gap-2 text-sm text-gray-300">
<i data-lucide="unlock" class="w-4 h-4 text-orange-400 flex-shrink-0"></i>
<span>Early access to new music</span>
</div>
<div class="flex items-center gap-2 text-sm text-gray-300">
<i data-lucide="music" class="w-4 h-4 text-orange-400 flex-shrink-0"></i>
<span>Exclusive tracks & content</span>
</div>
<div class="flex items-center gap-2 text-sm text-gray-300">
<i data-lucide="headphones" class="w-4 h-4 text-orange-400 flex-shrink-0"></i>
<span>High-quality audio</span>
</div>
<div class="flex items-center gap-2 text-sm text-gray-300">
<i data-lucide="heart" class="w-4 h-4 text-orange-400 flex-shrink-0"></i>
<span>Direct support for the creator</span>
</div>
</div>
</div>
<button onclick="BF.showSuperFanPaymentStep()" class="w-full py-3 bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-400 hover:to-red-400 text-white font-semibold rounded-xl transition flex items-center justify-center gap-2" style="box-shadow: 0 0 20px rgba(249,115,22,0.3)">
<i data-lucide="credit-card" class="w-5 h-5"></i>
Continue to Payment
</button>
<p class="text-xs text-gray-600 text-center mt-3">Recurring monthly \u2022 Cancel anytime</p>
</div>
<!-- Step 2: Payment Form (shown directly for 2-click flow) -->
<div id="bfSfStep2" class="hidden">
<div class="flex items-center gap-3 mb-4 p-3 rounded-xl bg-white/5">
<div class="w-10 h-10 rounded-full overflow-hidden border border-orange-500/30 flex-shrink-0">
<img src="${artistImage}" class="w-full h-full object-cover">
</div>
<div class="flex-1 min-w-0">
<p class="text-sm font-semibold text-white truncate">${artistName}</p>
<p class="text-xs text-orange-400 font-medium">$25/mo</p>
</div>
</div>
<div class="flex flex-wrap items-center gap-x-3 gap-y-1 mb-4 px-1 text-xs text-gray-400">
<span class="flex items-center gap-1"><i data-lucide="download" class="w-3 h-3 text-orange-400"></i>Free downloads</span>
<span class="flex items-center gap-1"><i data-lucide="unlock" class="w-3 h-3 text-orange-400"></i>No paywalls</span>
<span class="flex items-center gap-1"><i data-lucide="music" class="w-3 h-3 text-orange-400"></i>Exclusive content</span>
</div>
<div class="space-y-4">
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Name on card</label>
<input type="text" id="bfSfCardName" placeholder="John Doe" class="bf-payment-input">
</div>
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Card number</label>
<div class="relative">
<input type="text" id="bfSfCardNumber" placeholder="4242 4242 4242 4242" class="bf-payment-input" style="padding-right:4.5rem" maxlength="19" oninput="BF.formatCardNumber(this)">
<div class="absolute right-3 top-1/2 -translate-y-1/2 flex items-center gap-1.5 text-gray-600">
<svg width="28" height="18" viewBox="0 0 28 18" fill="none"><rect width="28" height="18" rx="2" fill="#1A1F71"/><path d="M11 5.5L8.5 12.5h2l.5-1.5h2.5l.5 1.5h2L13 5.5h-2zm.8 4.5l1-3 1 3h-2z" fill="#fff"/></svg>
</div>
</div>
</div>
<div class="flex gap-3">
<div class="flex-1">
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Expiry</label>
<input type="text" id="bfSfCardExpiry" placeholder="MM/YY" class="bf-payment-input" maxlength="5" oninput="BF.formatCardExpiry(this)">
</div>
<div class="w-24">
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">CVC</label>
<input type="text" id="bfSfCardCvc" placeholder="123" class="bf-payment-input" maxlength="4" oninput="this.value=this.value.replace(/[^0-9]/g,'')">
</div>
</div>
<div id="bfSfPaymentError" class="hidden text-red-400 text-sm"></div>
<button onclick="BF.confirmSuperFanPayment()" class="w-full py-3 bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-400 hover:to-red-400 text-white font-semibold rounded-xl transition flex items-center justify-center gap-2" style="box-shadow: 0 0 20px rgba(249,115,22,0.3)">
<i data-lucide="lock" class="w-5 h-5"></i>
Confirm Subscription \u2022 $25/mo
</button>
<button onclick="BF.showSuperFanSummaryStep()" class="w-full py-2 text-sm text-gray-500 hover:text-white transition">\u2190 Back</button>
</div>
<div class="flex items-center justify-center gap-4 mt-4 pt-4 border-t border-white/5">
<div class="flex items-center gap-1.5 text-xs text-gray-600">
<i data-lucide="shield-check" class="w-3.5 h-3.5"></i>
<span>Encrypted</span>
</div>
<div class="flex items-center gap-1.5 text-xs text-gray-600">
<i data-lucide="lock" class="w-3.5 h-3.5"></i>
<span>Secure</span>
</div>
<div class="flex items-center gap-1.5 text-xs text-gray-600">
<i data-lucide="credit-card" class="w-3.5 h-3.5"></i>
<span>PCI Compliant</span>
</div>
</div>
</div>
<!-- Step 3: Processing -->
<div id="bfSfStep3" class="hidden">
<div class="py-12 text-center">
<div class="w-16 h-16 rounded-full border-4 border-orange-500/20 border-t-orange-500 mx-auto mb-6" style="animation: bf-spin 1s linear infinite;"></div>
<h4 class="text-lg font-semibold text-white mb-2">Processing payment...</h4>
<p class="text-sm text-gray-500">Please wait while we confirm your subscription</p>
</div>
</div>
<!-- Step 4: Success -->
<div id="bfSfStep4" class="hidden">
<div class="py-8 text-center">
<div class="w-20 h-20 rounded-full bg-green-500/20 flex items-center justify-center mx-auto mb-6">
<i data-lucide="check-circle" class="w-10 h-10 text-green-400"></i>
</div>
<h4 class="text-xl font-bold text-white mb-2">You are now a Super Fan \ud83c\udfa7</h4>
<p class="text-sm text-gray-400 mb-1">Subscription to <span class="text-orange-400 font-medium">${artistName}</span> is active</p>
<p class="text-xs text-gray-600">Exclusive content has been unlocked</p>
</div>
</div>
</div>
</div>
`;
document.body.appendChild(modal);
if (window.lucide) lucide.createIcons();
// Auto-advance to payment form (2-click flow: open β pay)
_sfRetryAttempt = 0;
showSuperFanPaymentStep();
// Pre-fill saved card if available
try {
const savedCard = JSON.parse(localStorage.getItem('bf_saved_card') || 'null');
if (savedCard) {
const nameInput = document.getElementById('bfSfCardName');
const numberInput = document.getElementById('bfSfCardNumber');
const expiryInput = document.getElementById('bfSfCardExpiry');
if (nameInput && savedCard.name) nameInput.value = savedCard.name;
if (numberInput && savedCard.last4) numberInput.value = 'Β·Β·Β·Β· Β·Β·Β·Β· Β·Β·Β·Β· ' + savedCard.last4;
if (expiryInput && savedCard.expiry) expiryInput.value = savedCard.expiry;
}
} catch (e) {}
};
const closeSuperFanModal = () => {
document.getElementById('bfSuperFanModal')?.remove();
};
// ===== DOWNLOAD ACCESS CONTROL =====
const isDownloadUnlocked = (trackId, artistName) => {
if (isSuperFanOf(artistName)) return true;
try {
const states = JSON.parse(localStorage.getItem('bf_download_states') || '[]');
return states.some(s => s.trackId === trackId && s.unlocked);
} catch { return false; }
};
const unlockTrackDownload = (trackId, trackTitle, artistName, amount) => {
try {
let states = JSON.parse(localStorage.getItem('bf_download_states') || '[]');
const existing = states.findIndex(s => s.trackId === trackId);
const entry = { trackId, trackTitle, artistName, amount, unlocked: true, date: new Date().toISOString() };
if (existing > -1) { states[existing] = entry; } else { states.push(entry); }
localStorage.setItem('bf_download_states', JSON.stringify(states));
return true;
} catch { return false; }
};
const getDownloadStates = () => {
try { return JSON.parse(localStorage.getItem('bf_download_states') || '[]'); } catch { return []; }
};
const showDownloadModal = (trackTitle, artistName, trackId) => {
if (document.getElementById('bfDownloadModal')) return;
if (!isLoggedIn()) { showSignInModal(); return; }
_dlTrackTitle = trackTitle;
_dlArtistName = artistName;
_dlTrackId = trackId || 0;
const unlocked = isDownloadUnlocked(_dlTrackId, artistName);
const isSuperFan = isSuperFanOf(artistName);
const modal = document.createElement('div');
modal.id = 'bfDownloadModal';
let bodyContent;
if (unlocked) {
// Auto-download for unlocked tracks β 1-click experience
processMockDownload();
bodyContent = `
<div class="flex flex-col items-center justify-center py-8 text-center bf-pay-success">
<div class="w-16 h-16 rounded-full ${isSuperFan ? 'bg-orange-500/20' : 'bg-green-500/20'} flex items-center justify-center mx-auto mb-4 bf-success-pulse" style="box-shadow: 0 0 24px ${isSuperFan ? 'rgba(249,115,22,0.3)' : 'rgba(34,197,94,0.3)'}">
<i data-lucide="${isSuperFan ? 'zap' : 'check-circle'}" class="w-8 h-8 ${isSuperFan ? 'text-orange-400' : 'text-green-400'}"></i>
</div>
<h3 class="text-xl font-bold text-white mb-1">${isSuperFan ? 'Super Fan Download' : 'Unlocked β Downloading now'}</h3>
<p class="text-sm text-gray-400 mb-1">${trackTitle} Β· ${artistName}</p>
<p class="text-xs text-gray-600 mb-3">${isSuperFan ? 'Free with your Super Fan subscription' : 'Already unlocked'}</p>
<div class="bf-download-progress">
<div class="bf-download-progress-bar"></div>
</div>
<div class="mt-3 flex items-center gap-2 ${isSuperFan ? 'text-orange-400' : 'text-green-400'} text-sm font-medium">
<i data-lucide="download" class="w-4 h-4"></i>
<span>Downloading...</span>
</div>
</div>`;
// Auto-close after brief display
setTimeout(() => {
closeDownloadModal();
showToast('Beat unlocked successfully β');
}, 1500);
} else {
const unlockCount = getUnlockCount(_dlTrackId);
const socialProofHtml = unlockCount > 0
? `<div class="flex items-center justify-between mb-3"><div class="bf-social-proof"><i data-lucide="flame" class="w-3.5 h-3.5"></i>${unlockCount} people unlocked this</div><span class="bf-urgency-badge"><i data-lucide="clock" class="w-3 h-3"></i>Limited time</span></div>`
: `<div class="flex items-center justify-end mb-3"><span class="bf-urgency-badge"><i data-lucide="clock" class="w-3 h-3"></i>Limited time</span></div>`;
// Generate preview snippet waveform bars
let previewWaveBars = '';
const totalBars = 60;
const dropStart = Math.floor(totalBars * 0.35);
const dropEnd = dropStart + Math.floor(totalBars * 0.15); // ~8-12 sec of a ~4min track
for (let b = 0; b < totalBars; b++) {
let h;
if (b >= dropStart && b <= dropEnd) {
h = 50 + Math.random() * 50; // Drop section: taller bars
} else {
h = 15 + Math.random() * 40;
}
const inDrop = (b >= dropStart && b <= dropEnd) ? '1' : '0';
previewWaveBars += '<span style="height:' + h + '%;animation-delay:' + (b * 0.02).toFixed(2) + 's" data-in-drop="' + inDrop + '"></span>';
}
const highlightLeft = ((dropStart / totalBars) * 100).toFixed(1);
const highlightWidth = (((dropEnd - dropStart) / totalBars) * 100).toFixed(1);
bodyContent = `
${socialProofHtml}
<div class="flex items-center gap-4 mb-4">
<div class="w-12 h-12 rounded-lg bg-cyan-500/20 flex items-center justify-center flex-shrink-0">
<i data-lucide="music" class="w-6 h-6 text-cyan-400"></i>
</div>
<div class="min-w-0">
<p class="font-semibold text-white truncate">${trackTitle}</p>
<p class="text-sm text-gray-400 truncate">${artistName}</p>
</div>
</div>
<!-- Preview Snippet Hook -->
<div class="bf-preview-snippet mb-4" id="bfPreviewSnippet" onclick="BF.playPreviewSnippet()">
<div class="bf-preview-highlight" style="left:${highlightLeft}%;width:${highlightWidth}%"></div>
<button class="bf-preview-play" id="bfPreviewPlayBtn"><i data-lucide="play" class="w-3.5 h-3.5 text-black fill-current ml-0.5" id="bfPreviewPlayIcon"></i></button>
<div class="bf-preview-wave">${previewWaveBars}</div>
<div style="position:absolute;right:10px;top:50%;transform:translateY(-50%);display:flex;align-items:center;gap:6px;z-index:3">
<span style="font-size:10px;color:#6b7280" id="bfPreviewTime">Preview Β· 0:10</span>
<span style="font-size:9px;color:#00d4ff;font-weight:600;background:rgba(0,212,255,0.1);padding:2px 6px;border-radius:4px">DROP</span>
</div>
</div>
<div class="bf-support-cta">
<i data-lucide="heart-handshake" class="w-3.5 h-3.5 text-orange-400 flex-shrink-0"></i>
<span>Support this creator & <strong>download instantly</strong></span>
</div>
<div class="p-4 rounded-xl bg-gradient-to-r from-orange-500/10 to-cyan-500/10 border border-orange-500/20 mb-5">
<div class="flex items-center gap-2 mb-3">
<i data-lucide="zap" class="w-4 h-4 text-orange-400"></i>
<p class="text-sm font-semibold text-white">Unlock this beat instantly</p>
</div>
<p class="text-xs text-gray-400 mb-4">Pay what you want β minimum $0.50</p>
<div class="flex gap-2 mb-4">
<button class="bf-quick-amount active" onclick="BF.selectQuickAmount(0.50)">$0.50</button>
<button class="bf-quick-amount" onclick="BF.selectQuickAmount(1)">$1</button>
<button class="bf-quick-amount" onclick="BF.selectQuickAmount(5)">$5</button>
<button class="bf-quick-amount" onclick="BF.selectQuickAmount(0)">Custom</button>
</div>
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Custom amount</label>
<div class="relative">
<span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 text-sm">$</span>
<input type="number" id="bfDownloadAmount" value="0.50" min="0.50" step="0.01" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 pl-7 text-sm focus:outline-none focus:border-orange-500/50 text-white" oninput="BF.onCustomAmountInput()" autofocus>
</div>
<p id="bfDownloadError" class="text-red-400 text-xs mt-2 hidden"></p>
</div>
</div>
<button id="bfDownloadCta" class="w-full py-3.5 bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-400 hover:to-red-400 text-white font-bold rounded-xl transition flex items-center justify-center gap-2 text-base" style="box-shadow: 0 0 24px rgba(249,115,22,0.25)" onclick="BF.handleDownloadUnlock()">
<i data-lucide="lock" class="w-5 h-5"></i>
Unlock & Download Β· $0.50
</button>
<div class="flex items-center justify-center gap-4 mt-3">
<div class="flex items-center gap-1.5 text-xs text-gray-600">
<i data-lucide="heart" class="w-3 h-3"></i>
<span>Artist gets 85%</span>
</div>
<div class="flex items-center gap-1.5 text-xs text-gray-600">
<i data-lucide="shield-check" class="w-3 h-3"></i>
<span>Secure</span>
</div>
</div>`;
}
modal.innerHTML = `
<div class="bf-signin-overlay" onclick="BF.closeDownloadModal()"></div>
<div class="bf-signin-modal">
<div class="bf-signin-card" style="max-width:400px">
<div class="flex items-center justify-between mb-6">
<h3 class="text-xl font-bold text-white flex items-center gap-2">
<i data-lucide="download" class="w-5 h-5 text-cyan-400"></i>
Download
</h3>
<button onclick="BF.closeDownloadModal()" class="text-gray-400 hover:text-white transition"><i data-lucide="x" class="w-6 h-6"></i></button>
</div>
${bodyContent}
</div>
</div>
`;
document.body.appendChild(modal);
if (window.lucide) lucide.createIcons();
};
const closeDownloadModal = () => {
document.getElementById('bfDownloadModal')?.remove();
};
const handleDownloadUnlock = () => {
const amountInput = document.getElementById('bfDownloadAmount');
const errorEl = document.getElementById('bfDownloadError');
if (!amountInput) return;
const amount = parseFloat(amountInput.value);
if (!amount || isNaN(amount)) {
if (errorEl) { errorEl.textContent = 'Please enter an amount'; errorEl.classList.remove('hidden'); }
amountInput.classList.add('border-red-500/50');
return;
}
if (amount < 0.50) {
if (errorEl) { errorEl.textContent = 'Minimum amount is $0.50'; errorEl.classList.remove('hidden'); }
amountInput.classList.add('border-red-500/50');
return;
}
if (errorEl) errorEl.classList.add('hidden');
amountInput.classList.remove('border-red-500/50');
// Store unlock state (mock payment)
unlockTrackDownload(_dlTrackId, _dlTrackTitle, _dlArtistName, amount);
// Store amount for flow continuity
_dlAmount = amount;
// Record transaction with full metadata
try {
const config = getMonetizationConfig();
const fee = +(amount * config.platformFeePercent / 100).toFixed(2);
const user = getCurrentUser();
const transactions = JSON.parse(localStorage.getItem('transactions') || '[]');
const tx = {
type: 'download',
amount: amount,
artist: _dlArtistName,
track: _dlTrackTitle,
trackId: _dlTrackId,
date: new Date().toISOString(),
fee: fee,
currency: config.currency,
paymentMethod: 'card',
cardLast4: '4242',
status: 'completed',
userId: user ? user.id : null
};
transactions.push(tx);
localStorage.setItem('transactions', JSON.stringify(transactions));
// Record creator earning
recordCreatorEarning(tx);
} catch {}
// Auto-download + instant success feedback
processMockDownload();
const card = document.querySelector('#bfDownloadModal .bf-signin-card');
if (card) {
// Generate confetti particles
const confettiColors = ['#22c55e', '#4ade80', '#00d4ff', '#f97316', '#a78bfa', '#facc15'];
let confettiHtml = '';
for (let i = 0; i < 18; i++) {
const color = confettiColors[Math.floor(Math.random() * confettiColors.length)];
const left = (5 + Math.random() * 90).toFixed(0);
const delay = (Math.random() * 0.5).toFixed(2);
const size = (4 + Math.random() * 4).toFixed(0);
confettiHtml += '<div class="bf-confetti-particle" style="left:' + left + '%;top:-8px;width:' + size + 'px;height:' + size + 'px;background:' + color + ';animation-delay:' + delay + 's;animation-duration:' + (0.8 + Math.random() * 0.6).toFixed(2) + 's"></div>';
}
card.innerHTML = `
<div class="flex flex-col items-center justify-center py-8 text-center bf-pay-success" style="position:relative;overflow:hidden">
${confettiHtml}
<div class="w-20 h-20 rounded-full bg-green-500/20 flex items-center justify-center mx-auto mb-5 bf-unlock-success-icon" style="box-shadow: 0 0 30px rgba(34,197,94,0.3)">
<i data-lucide="check-circle" class="w-10 h-10 text-green-400"></i>
</div>
<h3 class="text-xl font-bold text-white mb-1" style="animation-delay:0.1s">Unlocked β Downloading now</h3>
<p class="text-sm text-gray-400 mb-1" style="animation-delay:0.2s">${_dlTrackTitle} Β· ${_dlArtistName}</p>
<p class="text-xs text-green-400 font-medium mb-1" style="animation-delay:0.25s">Paid ${amount.toFixed(2)} Β· Creator receives ${(amount * 0.85).toFixed(2)}</p>
<div class="bf-download-progress" style="animation-delay:0.3s">
<div class="bf-download-progress-bar"></div>
</div>
<div class="mt-4 flex items-center gap-2 text-green-400 text-sm font-medium" style="animation-delay:0.35s">
<i data-lucide="download" class="w-4 h-4"></i>
<span>Download starting...</span>
</div>
</div>
`;
lucide.createIcons();
}
// Auto-close after brief success display
setTimeout(() => {
closeDownloadModal();
showToast('Unlocked β Downloading now β');
}, 2200);
};
const processMockDownload = () => {
showToast('β¬οΈ Downloading: ' + _dlTrackTitle + ' β ' + _dlArtistName);
};
const showSuperFanPaymentStep = () => {
const step1 = document.getElementById('bfSfStep1');
const step2 = document.getElementById('bfSfStep2');
if (step1) step1.classList.add('hidden');
if (step2) step2.classList.remove('hidden');
const nameInput = document.getElementById('bfSfCardName');
if (nameInput) nameInput.focus();
};
const showSuperFanSummaryStep = () => {
const step1 = document.getElementById('bfSfStep1');
const step2 = document.getElementById('bfSfStep2');
if (step2) step2.classList.add('hidden');
if (step1) step1.classList.remove('hidden');
};
const formatCardNumber = (input) => {
let v = input.value.replace(/\D/g, '').substring(0, 16);
let formatted = v.match(/.{1,4}/g);
input.value = formatted ? formatted.join(' ') : '';
};
const formatCardExpiry = (input) => {
let v = input.value.replace(/\D/g, '').substring(0, 4);
if (v.length >= 2) {
v = v.substring(0, 2) + '/' + v.substring(2);
}
input.value = v;
};
const confirmSuperFanPayment = () => {
const name = document.getElementById('bfSfCardName')?.value.trim();
const number = document.getElementById('bfSfCardNumber')?.value.replace(/\s/g, '');
const expiry = document.getElementById('bfSfCardExpiry')?.value.trim();
const cvc = document.getElementById('bfSfCardCvc')?.value.trim();
const errEl = document.getElementById('bfSfPaymentError');
// Validate fields
if (!name) {
if (errEl) { errEl.textContent = 'Please enter the name on your card'; errEl.classList.remove('hidden'); }
document.getElementById('bfSfCardName')?.classList.add('error');
return;
}
document.getElementById('bfSfCardName')?.classList.remove('error');
if (!number || number.length < 13) {
if (errEl) { errEl.textContent = 'Please enter a valid card number'; errEl.classList.remove('hidden'); }
document.getElementById('bfSfCardNumber')?.classList.add('error');
return;
}
document.getElementById('bfSfCardNumber')?.classList.remove('error');
if (!expiry || !/^\d{2}\/\d{2}$/.test(expiry)) {
if (errEl) { errEl.textContent = 'Please enter a valid expiry date (MM/YY)'; errEl.classList.remove('hidden'); }
document.getElementById('bfSfCardExpiry')?.classList.add('error');
return;
}
document.getElementById('bfSfCardExpiry')?.classList.remove('error');
if (!cvc || cvc.length < 3) {
if (errEl) { errEl.textContent = 'Please enter a valid CVC'; errEl.classList.remove('hidden'); }
document.getElementById('bfSfCardCvc')?.classList.add('error');
return;
}
document.getElementById('bfSfCardCvc')?.classList.remove('error');
// Hide error, show processing
if (errEl) errEl.classList.add('hidden');
document.getElementById('bfSfStep2')?.classList.add('hidden');
document.getElementById('bfSfStep3')?.classList.remove('hidden');
// Simulate payment processing (1.5s delay for speed)
const last4 = number.replace(/\s/g, '').slice(-4);
// Save card for quick re-use
try {
localStorage.setItem('bf_saved_card', JSON.stringify({
name: name,
last4: last4,
expiry: expiry
}));
} catch (e) {}
setTimeout(() => {
// Simulate random payment failure (~15% on first attempt, 0% on retry)
if (_sfRetryAttempt === 0 && Math.random() < 0.15) {
_sfRetryAttempt++;
document.getElementById('bfSfStep3')?.classList.add('hidden');
const step2 = document.getElementById('bfSfStep2');
if (step2) {
step2.classList.remove('hidden');
const errEl = document.getElementById('bfSfPaymentError');
if (errEl) {
errEl.textContent = 'Payment declined β please try again or use a different card';
errEl.classList.remove('hidden');
}
// Show retry button
const existingBtn = step2.querySelector('.bf-retry-btn');
if (!existingBtn) {
const retryBtn = document.createElement('button');
retryBtn.className = 'bf-retry-btn w-full py-3 bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-400 hover:to-red-400 text-white font-semibold rounded-xl transition flex items-center justify-center gap-2 mt-3';
retryBtn.style.boxShadow = '0 0 20px rgba(249,115,22,0.3)';
retryBtn.innerHTML = '<i data-lucide="refresh-cw" class="w-5 h-5"></i> Retry Payment Β· $25/mo';
retryBtn.onclick = () => confirmSuperFanPayment();
const confirmBtn = step2.querySelector('button[onclick="BF.confirmSuperFanPayment()"]');
if (confirmBtn) confirmBtn.parentElement.insertBefore(retryBtn, confirmBtn.nextSibling);
lucide.createIcons();
}
}
return;
}
// Activate subscription with rich data
const key = 'bf_superfan';
let subs = [];
try { subs = JSON.parse(localStorage.getItem(key) || '[]'); } catch { subs = []; }
migrateSuperFanData();
const slug = _sfArtistName.toLowerCase().replace(/\s+/g, '-');
const existing = subs.find(s => typeof s === 'string' ? s === slug : s.slug === slug);
if (!existing) {
subs.push({
slug: slug,
name: _sfArtistName,
image: _sfArtistImage,
date: new Date().toISOString(),
active: true,
payment: { last4: last4, amount: 25, currency: 'USD' }
});
localStorage.setItem(key, JSON.stringify(subs));
}
// Record transaction
try {
const transactions = JSON.parse(localStorage.getItem('transactions') || '[]');
transactions.push({
type: 'subscription',
amount: 25,
artist: _sfArtistName,
tier: 'Super Fan',
date: new Date().toISOString(),
fee: 3.75,
currency: 'USD',
paymentMethod: 'card',
cardLast4: last4,
status: 'completed',
userId: getCurrentUser()?.id || null
});
localStorage.setItem('transactions', JSON.stringify(transactions));
} catch {}
// Record creator earning
recordCreatorEarning({
type: 'subscription',
amount: 25,
artist: _sfArtistName,
track: null,
trackId: null,
fee: 3.75,
currency: 'USD',
paymentMethod: 'card',
cardLast4: last4,
status: 'completed',
date: new Date().toISOString()
});
// Show success step
document.getElementById('bfSfStep3')?.classList.add('hidden');
document.getElementById('bfSfStep4')?.classList.remove('hidden');
if (window.lucide) lucide.createIcons();
// Update all Super Fan buttons on page
updateSuperFanButtons();
// Auto-close modal after 1.8s and show toast
setTimeout(() => {
closeSuperFanModal();
showToast('You are now a Super Fan of ' + _sfArtistName + ' \ud83c\udfa7');
if (window.lucide) lucide.createIcons();
}, 1800);
}, 2000);
};
const isSuperFanOf = (artistName) => {
try {
migrateSuperFanData();
const subs = JSON.parse(localStorage.getItem('bf_superfan') || '[]');
const slug = artistName.toLowerCase().replace(/\s+/g, '-');
return subs.some(s => {
if (typeof s === 'string') return s === slug;
return s.slug === slug && s.active !== false;
});
} catch { return false; }
};
const updateSuperFanButtons = () => {
document.querySelectorAll('[data-superfan-artist]').forEach(btn => {
const artist = btn.getAttribute('data-superfan-artist');
const isActive = isSuperFanOf(artist);
const isSmall = btn.getAttribute('data-superfan-size') === 'small';
if (isActive) {
if (isSmall) {
btn.innerHTML = '<i data-lucide="check-circle" class="w-3.5 h-3.5"></i><span>Super Fan Active \u2713</span>';
} else {
btn.innerHTML = '<i data-lucide="check-circle" class="w-4 h-4"></i><span>Super Fan Active \u2713</span>';
}
btn.className = btn.className.replace(/bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-400 hover:to-red-400 text-white/g, '');
btn.classList.remove('bg-gradient-to-r', 'from-orange-500', 'to-red-500', 'hover:from-orange-400', 'hover:to-red-400', 'text-white', 'bf-superfan-btn');
btn.classList.add('bg-green-500/20', 'text-green-400', 'border', 'border-green-500/30');
if (!isSmall) btn.style.boxShadow = '0 0 20px rgba(34,197,94,0.2)';
else btn.style.boxShadow = '';
} else {
if (isSmall) {
btn.innerHTML = '<i data-lucide="zap" class="w-3.5 h-3.5"></i><span>Super Fan</span>';
} else {
btn.innerHTML = '<i data-lucide="zap" class="w-4 h-4"></i><span>Become Super Fan</span>';
}
btn.classList.remove('bg-green-500/20', 'text-green-400', 'border', 'border-green-500/30');
btn.classList.add('bg-gradient-to-r', 'from-orange-500', 'to-red-500', 'hover:from-orange-400', 'hover:to-red-400', 'text-white', 'bf-superfan-btn');
if (!isSmall) btn.style.boxShadow = '0 0 20px rgba(249,115,22,0.3)';
else btn.style.boxShadow = '';
}
});
};
// ===== ROLE SYSTEM =====
const ROLES = { GUEST: 'guest', USER: 'user', CREATOR: 'creator', SUPERFAN: 'superfan' };
const getUserRole = () => {
if (!isLoggedIn()) return ROLES.GUEST;
const user = getCurrentUser();
if (!user) return ROLES.GUEST;
if (getSuperFanSubscriptions().length > 0) return ROLES.SUPERFAN;
if (user.role === 'producer' || user.isArtist) return ROLES.CREATOR;
return ROLES.USER;
};
const canBrowse = () => true;
const canDownload = () => isLoggedIn();
const canUpload = () => { const r = getUserRole(); return r === ROLES.CREATOR || r === ROLES.SUPERFAN; };
const canEarn = () => getUserRole() === ROLES.CREATOR;
const hasFreeDownloads = (artistName) => isSuperFanOf(artistName);
// ===== MONETIZATION CONFIG =====
const MONETIZATION_DEFAULTS = {
minimumPrice: 0.50,
platformFeePercent: 15,
creatorPayoutPercent: 85,
currency: 'USD',
superFanMonthlyPrice: 25
};
const getMonetizationConfig = () => {
try { return JSON.parse(localStorage.getItem('bf_monetization_config')) || { ...MONETIZATION_DEFAULTS }; }
catch { return { ...MONETIZATION_DEFAULTS }; }
};
// ===== TRACK MONETIZATION =====
const getTrackMonetization = (trackId) => {
try {
const states = JSON.parse(localStorage.getItem('bf_track_monetization') || '[]');
return states.find(s => s.trackId === trackId) || null;
} catch { return null; }
};
const setTrackMonetization = (trackId, config) => {
try {
let states = JSON.parse(localStorage.getItem('bf_track_monetization') || '[]');
const idx = states.findIndex(s => s.trackId === trackId);
const entry = {
trackId,
isMonetized: config.isMonetized !== false,
minimumPrice: config.minimumPrice || MONETIZATION_DEFAULTS.minimumPrice,
suggestedPrice: config.suggestedPrice || 2.99,
isLocked: config.isLocked !== false,
superFanFree: config.superFanFree !== false,
currency: config.currency || MONETIZATION_DEFAULTS.currency,
updatedAt: new Date().toISOString()
};
if (idx > -1) states[idx] = entry; else states.push(entry);
localStorage.setItem('bf_track_monetization', JSON.stringify(states));
return entry;
} catch (e) { return null; }
};
const isTrackLocked = (trackId, artistName) => {
if (isSuperFanOf(artistName)) return false;
if (isDownloadUnlocked(trackId, artistName)) return false;
const m = getTrackMonetization(trackId);
return m ? m.isLocked : false;
};
// ===== CREATOR EARNINGS =====
const getCreatorEarnings = (creatorId) => {
try {
const earnings = JSON.parse(localStorage.getItem('bf_creator_earnings') || '[]');
return creatorId ? earnings.filter(e => e.creatorId === creatorId) : earnings;
} catch { return []; }
};
const recordCreatorEarning = (tx) => {
try {
let earnings = JSON.parse(localStorage.getItem('bf_creator_earnings') || '[]');
const config = getMonetizationConfig();
const fee = tx.fee || +(tx.amount * config.platformFeePercent / 100).toFixed(2);
const user = getCurrentUser();
const earning = {
id: 'earn_' + Date.now(),
creatorId: tx.creatorId || tx.artist,
creatorName: tx.artist,
source: tx.type,
grossAmount: tx.amount,
platformFee: fee,
netAmount: +(tx.amount - fee).toFixed(2),
currency: tx.currency || config.currency,
trackId: tx.trackId || null,
trackTitle: tx.track || null,
userId: user ? user.id : null,
date: tx.date || new Date().toISOString(),
status: 'completed',
paymentMethod: tx.paymentMethod || 'card',
cardLast4: tx.cardLast4 || null
};
earnings.push(earning);
localStorage.setItem('bf_creator_earnings', JSON.stringify(earnings));
return earning;
} catch (e) { return null; }
};
const getCreatorEarningsSummary = (creatorId) => {
const earnings = getCreatorEarnings(creatorId);
const summary = {
totalGross: 0,
totalNet: 0,
totalFees: 0,
bySource: {},
byMonth: {},
transactionCount: earnings.length
};
earnings.forEach(e => {
summary.totalGross += e.grossAmount;
summary.totalNet += e.netAmount;
summary.totalFees += e.platformFee;
summary.bySource[e.source] = (summary.bySource[e.source] || 0) + e.grossAmount;
const month = e.date.substring(0, 7);
summary.byMonth[month] = (summary.byMonth[month] || 0) + e.grossAmount;
});
summary.totalGross = +summary.totalGross.toFixed(2);
summary.totalNet = +summary.totalNet.toFixed(2);
summary.totalFees = +summary.totalFees.toFixed(2);
return summary;
};
// ===== ENHANCED TRANSACTIONS =====
const getTransactionHistory = (filters) => {
try {
let transactions = JSON.parse(localStorage.getItem('transactions') || '[]');
if (filters) {
if (filters.type) transactions = transactions.filter(t => t.type === filters.type);
if (filters.artist) transactions = transactions.filter(t => t.artist === filters.artist);
if (filters.status) transactions = transactions.filter(t => t.status === filters.status);
if (filters.userId) transactions = transactions.filter(t => t.userId === filters.userId);
}
return transactions.sort((a, b) => new Date(b.date) - new Date(a.date));
} catch { return []; }
};
// ===== MONETIZATION PRESETS =====
const MonetizationPresets = {
free: { isMonetized: false, isLocked: false, minimumPrice: 0, suggestedPrice: 0, superFanFree: true },
payWhatYouWant: { isMonetized: true, isLocked: true, minimumPrice: 0.50, suggestedPrice: 0, superFanFree: true },
fixedPrice: { isMonetized: true, isLocked: true, minimumPrice: 0.99, suggestedPrice: 2.99, superFanFree: true },
superFanExclusive: { isMonetized: true, isLocked: true, minimumPrice: 0, suggestedPrice: 0, superFanFree: false },
premium: { isMonetized: true, isLocked: true, minimumPrice: 4.99, suggestedPrice: 9.99, superFanFree: true }
};
// ===== UNIFIED PAYMENT PROCESSING =====
const processTip = (artistName, amount, options = {}) => {
if (!isLoggedIn()) return { success: false, error: 'Must be logged in to tip' };
if (!amount || isNaN(amount) || amount < MONETIZATION_DEFAULTS.minimumPrice) {
return { success: false, error: 'Minimum tip is
const init = (activeTab) => {
injectStyles();
injectBottomNav(activeTab);
migrateSuperFanData();
syncPlayer();
updateTopNav();
adjustTopNav();
updateSuperFanButtons();
if (window.lucide) lucide.createIcons();
// Check for referral parameter in URL
try {
const urlParams = new URLSearchParams(window.location.search);
const refCode = urlParams.get('ref');
if (refCode) trackReferralClick(refCode);
} catch {}
// Re-sync player every 2 seconds
setInterval(syncPlayer, 2000);
};
return {
isLoggedIn, isProducer, isFan, getCurrentUser, signIn, signOut, signUp,
getAllTracks, getArtists, getGenres, getTrendingTracks, getFreshUploads,
searchTracks, searchArtists,
init, showSignInModal, closeSignInModal, handleSignIn,
showSignUpForm, showSignInForm, showChooseType, handleSignUp,
adjustTopNav, showToast, syncPlayer, playTrack, togglePlay,
showSuperFanModal, closeSuperFanModal, confirmSuperFanPayment, showSuperFanPaymentStep, showSuperFanSummaryStep, formatCardNumber, formatCardExpiry, isSuperFanOf, updateSuperFanButtons,
getSuperFanSubscriptions, cancelSuperFanSubscription,
showDownloadModal, closeDownloadModal, isDownloadUnlocked, unlockTrackDownload, getDownloadStates, handleDownloadUnlock, processMockDownload,
// Role system
ROLES, getUserRole, canBrowse, canDownload, canUpload, canEarn, hasFreeDownloads,
// Monetization
MONETIZATION_DEFAULTS, getMonetizationConfig,
getTrackMonetization, setTrackMonetization, isTrackLocked,
// Creator earnings
getCreatorEarnings, recordCreatorEarning, getCreatorEarningsSummary,
// Enhanced transactions
getTransactionHistory,
// Monetization presets
MonetizationPresets,
// Unified payment processing
processTip, processSubscription,
// User capabilities
getUserCapabilities,
// Track publishing with monetization
publishTrackWithMonetization,
// Creator dashboard
getCreatorDashboard,
// Download button renderer
renderDL,
// Share button renderer
renderShare,
// Share system
showShareModal, closeShareModal,
shareViaWhatsApp, shareViaFacebook, shareViaTwitter, copyTrackLink,
trackShare, getShareCount, getUnlockCount,
// Referral system
getReferralCode, recordReferralSignup, getReferralStats, trackReferralClick,
// Quick amount selector
selectQuickAmount, onCustomAmountInput,
// Preview snippet
playPreviewSnippet,
// Like system
toggleLike, isLiked, getLikedTracks, renderLikeBtn, handleLikeClick,
// Recommendations
getRecommendations,
// Queue / continuous playback
setPlayQueue, getPlayQueue, playNext, playPrevious, replayTrack,
// Creator onboarding & incentives
isFirstTimeCreator, getOnboardingState, getCreatorBadges,
getTopCreatorsThisWeek, getMotivationalPrompt,
dismissOnboarding, isOnboardingDismissed,
// Trending algorithm
getRisingBeats, getTrackTrendIndicator, recordActivity,
simulateRecentActivity, saveRankingSnapshot
};
})(); + MONETIZATION_DEFAULTS.minimumPrice };
}
try {
const config = getMonetizationConfig();
const fee = +(amount * config.platformFeePercent / 100).toFixed(2);
const user = getCurrentUser();
const last4 = options.cardLast4 || '4242';
const tx = {
type: 'tip',
amount: amount,
artist: artistName,
date: new Date().toISOString(),
fee: fee,
currency: options.currency || config.currency,
paymentMethod: options.paymentMethod || 'card',
cardLast4: last4,
status: 'completed',
userId: user ? user.id : null,
message: options.message || null
};
const transactions = JSON.parse(localStorage.getItem('transactions') || '[]');
transactions.push(tx);
localStorage.setItem('transactions', JSON.stringify(transactions));
recordCreatorEarning(tx);
if (options.deductFromWallet !== false) {
const balance = parseFloat(localStorage.getItem('walletBalance') || '0');
if (balance >= amount) {
localStorage.setItem('walletBalance', (balance - amount).toFixed(2));
}
}
return { success: true, transaction: tx };
} catch (e) {
return { success: false, error: 'Tip processing failed' };
}
};
const processSubscription = (artistName, amount, tier, options = {}) => {
if (!isLoggedIn()) return { success: false, error: 'Must be logged in to subscribe' };
try {
const config = getMonetizationConfig();
const fee = +(amount * config.platformFeePercent / 100).toFixed(2);
const user = getCurrentUser();
const last4 = options.cardLast4 || '4242';
const tx = {
type: 'subscription',
amount: amount,
artist: artistName,
tier: tier,
date: new Date().toISOString(),
fee: fee,
currency: options.currency || config.currency,
paymentMethod: options.paymentMethod || 'card',
cardLast4: last4,
status: 'completed',
userId: user ? user.id : null
};
const transactions = JSON.parse(localStorage.getItem('transactions') || '[]');
transactions.push(tx);
localStorage.setItem('transactions', JSON.stringify(transactions));
recordCreatorEarning(tx);
return { success: true, transaction: tx };
} catch (e) {
return { success: false, error: 'Subscription processing failed' };
}
};
// ===== USER CAPABILITIES =====
const getUserCapabilities = () => {
const role = getUserRole();
const user = getCurrentUser();
const isCreatorRole = user && (user.role === 'producer' || user.isArtist);
const isSuperFanRole = role === ROLES.SUPERFAN;
const isCreator = isCreatorRole || isSuperFanRole;
const isGuest = role === ROLES.GUEST;
const compositeRoles = [];
if (isCreatorRole) compositeRoles.push(ROLES.CREATOR);
if (isSuperFanRole) compositeRoles.push(ROLES.SUPERFAN);
if (!isCreatorRole && !isSuperFanRole && !isGuest) compositeRoles.push(ROLES.USER);
if (isGuest) compositeRoles.push(ROLES.GUEST);
return {
role: role,
roles: compositeRoles,
canBrowse: true,
canPlay: true,
canDownload: !isGuest,
canUpload: isCreator,
canEarn: isCreatorRole,
canMonetize: isCreatorRole,
hasFreeDownloads: isSuperFanRole,
canComment: !isGuest,
canFollow: !isGuest,
canLike: !isGuest,
canCreatePlaylist: !isGuest,
canViewAnalytics: isCreatorRole,
canSetPricing: isCreatorRole,
canManageTracks: isCreatorRole,
canUpgradeRole: !isGuest,
maxUploadSize: isCreator ? 500 : 0,
maxTracks: isCreator ? (localStorage.getItem('isPro') === 'true' ? Infinity : 10) : 0
};
};
// ===== PUBLISH TRACK WITH MONETIZATION =====
const publishTrackWithMonetization = (trackData, monetizationConfig = null) => {
try {
let allTracks = JSON.parse(localStorage.getItem('beatfridge_tracks') || '[]');
allTracks.push(trackData);
localStorage.setItem('beatfridge_tracks', JSON.stringify(allTracks));
let userTracks = JSON.parse(localStorage.getItem('userTracks') || '[]');
userTracks.push(trackData);
localStorage.setItem('userTracks', JSON.stringify(userTracks));
if (monetizationConfig && monetizationConfig.isMonetized) {
setTrackMonetization(trackData.id, monetizationConfig);
} else if (monetizationConfig) {
setTrackMonetization(trackData.id, {
isMonetized: false,
isLocked: false,
superFanFree: true,
...monetizationConfig
});
}
return { success: true, track: trackData };
} catch (e) {
return { success: false, error: 'Publish failed: ' + e.message };
}
};
// ===== CREATOR DASHBOARD DATA =====
const getCreatorDashboard = (creatorId) => {
const earnings = getCreatorEarnings(creatorId);
const summary = getCreatorEarningsSummary(creatorId);
const allTransactions = getTransactionHistory({});
const creatorTransactions = allTransactions.filter(t => t.artist === creatorId || t.artistId === creatorId);
const tracks = getAllTracks().filter(t => t.artistId === creatorId || t.artist === creatorId);
const config = getMonetizationConfig();
const trackStats = tracks.map(track => {
const monetization = getTrackMonetization(track.id);
const trackEarnings = earnings.filter(e => e.trackId === track.id);
const trackRevenue = trackEarnings.reduce((sum, e) => sum + e.netAmount, 0);
return {
trackId: track.id,
title: track.title,
plays: track.plays,
revenue: +trackRevenue.toFixed(2),
monetization: monetization,
isLocked: monetization ? monetization.isLocked : false,
downloadCount: trackEarnings.filter(e => e.source === 'download').length,
tipCount: trackEarnings.filter(e => e.source === 'tip').length
};
});
return {
summary,
tracks: trackStats,
recentTransactions: creatorTransactions.slice(0, 20),
monetizationConfig: config,
payoutRate: config.creatorPayoutPercent + '%',
pendingPayout: summary.totalNet,
lastUpdated: new Date().toISOString()
};
};
// ===== RENDER DOWNLOAD BUTTON =====
const renderDL = (trackId, trackTitle, artistName) => {
const safeTitle = String(trackTitle).replace(/'/g, "\\'").replace(/"/g, '"');
const safeArtist = String(artistName).replace(/'/g, "\\'").replace(/"/g, '"');
const unlockCount = getUnlockCount(trackId);
if (isSuperFanOf(artistName)) {
return `<button class="bf-download-btn bf-dl-free" onclick="event.stopPropagation(); BF.showDownloadModal('${safeTitle}', '${safeArtist}', ${trackId})"><i data-lucide="download" class="w-3 h-3"></i>Free</button>`;
}
if (isDownloadUnlocked(trackId, artistName)) {
return `<button class="bf-download-btn bf-dl-unlocked" onclick="event.stopPropagation(); BF.showDownloadModal('${safeTitle}', '${safeArtist}', ${trackId})"><i data-lucide="download" class="w-3 h-3"></i>Download</button>`;
}
const proofHtml = unlockCount > 0 ? `<span class="bf-social-proof" style="margin-top:3px"><i data-lucide="users" class="w-3 h-3"></i>${unlockCount} unlocked</span>` : '';
return `<div style="display:inline-flex;flex-direction:column;align-items:flex-end;gap:2px"><button class="bf-unlock-btn" onclick="event.stopPropagation(); BF.showDownloadModal('${safeTitle}', '${safeArtist}', ${trackId})"><i data-lucide="lock" class="w-3 h-3"></i>Unlock from $0.50</button>${proofHtml}</div>`;
};
// ===== LIKE SYSTEM =====
const toggleLike = (trackId, trackTitle, trackArtist) => {
try {
let liked = JSON.parse(localStorage.getItem('bf_liked_tracks') || '[]');
const idx = liked.findIndex(t => t.id === trackId);
if (idx > -1) {
liked.splice(idx, 1);
localStorage.setItem('bf_liked_tracks', JSON.stringify(liked));
return { liked: false, count: liked.length };
}
liked.unshift({ id: trackId, title: trackTitle, artist: trackArtist, likedAt: new Date().toISOString() });
if (liked.length > 200) liked.pop();
localStorage.setItem('bf_liked_tracks', JSON.stringify(liked));
return { liked: true, count: liked.length };
} catch { return { liked: false, count: 0 }; }
};
const isLiked = (trackId) => {
try { return JSON.parse(localStorage.getItem('bf_liked_tracks') || '[]').some(t => t.id === trackId); }
catch { return false; }
};
const getLikedTracks = () => {
try { return JSON.parse(localStorage.getItem('bf_liked_tracks') || '[]'); }
catch { return []; }
};
const renderLikeBtn = (trackId, trackTitle, trackArtist) => {
const liked = isLiked(trackId);
const sT = String(trackTitle).replace(/'/g, "\\'").replace(/"/g, '"');
const sA = String(trackArtist).replace(/'/g, "\\'").replace(/"/g, '"');
return '<button class="bf-like-btn' + (liked ? ' bf-liked' : '') + '" onclick="event.stopPropagation();BF.handleLikeClick(' + trackId + ',\'' + sT + '\',\'' + sA + '\',this)"><i data-lucide="heart" class="w-3 h-3' + (liked ? ' fill-current' : '') + '"></i>' + (liked ? 'Liked' : 'Like') + '</button>';
};
const handleLikeClick = (trackId, trackTitle, trackArtist, btn) => {
const result = toggleLike(trackId, trackTitle, trackArtist);
if (btn) {
if (result.liked) {
btn.classList.add('bf-liked');
btn.innerHTML = '<i data-lucide="heart" class="w-3 h-3 fill-current"></i>Liked';
showToast('Added to your likes β€οΈ');
} else {
btn.classList.remove('bf-liked');
btn.innerHTML = '<i data-lucide="heart" class="w-3 h-3"></i>Like';
showToast('Removed from likes');
}
if (window.lucide) lucide.createIcons();
}
return result;
};
// ===== RECOMMENDATIONS =====
const getRecommendations = (track, limit) => {
limit = limit || 6;
const allTracks = getAllTracks();
if (!track) return allTracks.slice(0, limit);
return allTracks
.filter(t => t.id !== track.id)
.map(t => {
let score = 0;
if (t.genre && track.genre && t.genre.toLowerCase() === track.genre.toLowerCase()) score += 50;
if (t.artist && track.artist && t.artist.toLowerCase() === track.artist.toLowerCase()) score += 25;
if (t.artistId && track.artistId && t.artistId === track.artistId) score += 20;
const tp = parseFloat((t.plays || '0').replace('K', '')) * ((t.plays || '').includes('K') ? 1000 : 1);
score += Math.min(tp / 1000, 10);
score += Math.random() * 8;
return { ...t, _recScore: score };
})
.sort((a, b) => b._recScore - a._recScore)
.slice(0, limit);
};
// ===== QUEUE / CONTINUOUS PLAYBACK =====
let _playQueue = [];
let _queueIndex = -1;
const setPlayQueue = (tracks, startIndex) => {
startIndex = startIndex || 0;
_playQueue = tracks.map(t => ({ ...t }));
_queueIndex = startIndex;
try {
localStorage.setItem('bf_play_queue', JSON.stringify(_playQueue));
localStorage.setItem('bf_queue_index', String(_queueIndex));
} catch {}
};
const getPlayQueue = () => {
try {
if (!_playQueue.length) {
_playQueue = JSON.parse(localStorage.getItem('bf_play_queue') || '[]');
_queueIndex = parseInt(localStorage.getItem('bf_queue_index') || '-1');
}
return { queue: _playQueue, index: _queueIndex };
} catch { return { queue: [], index: -1 }; }
};
const playNext = () => {
const { queue, index } = getPlayQueue();
if (!queue.length) return false;
const repeat = localStorage.getItem('bf_repeat') === 'true';
let nextIdx = index + 1;
if (nextIdx >= queue.length) {
if (!repeat) return false;
nextIdx = 0;
}
_queueIndex = nextIdx;
try { localStorage.setItem('bf_queue_index', String(_queueIndex)); } catch {}
playTrack(queue[nextIdx], true);
return true;
};
const playPrevious = () => {
const { queue, index } = getPlayQueue();
if (!queue.length) return false;
let prevIdx = index - 1;
if (prevIdx < 0) prevIdx = queue.length - 1;
_queueIndex = prevIdx;
try { localStorage.setItem('bf_queue_index', String(_queueIndex)); } catch {}
playTrack(queue[prevIdx], true);
return true;
};
const replayTrack = () => {
try {
const track = JSON.parse(localStorage.getItem('currentTrack'));
if (track) { playTrack(track); return true; }
} catch {}
return false;
};
// ===== PREVIEW SNIPPET =====
let _previewTimer = null;
let _previewPlaying = false;
const playPreviewSnippet = () => {
const snippet = document.getElementById('bfPreviewSnippet');
const playIcon = document.getElementById('bfPreviewPlayIcon');
const timeLabel = document.getElementById('bfPreviewTime');
if (!snippet) return;
if (_previewPlaying) {
// Stop preview
_previewPlaying = false;
snippet.classList.remove('bf-preview-active');
if (playIcon) { playIcon.setAttribute('data-lucide', 'play'); playIcon.classList.add('ml-0.5'); }
if (timeLabel) timeLabel.textContent = 'Preview Β· 0:10';
if (_previewTimer) { clearTimeout(_previewTimer); _previewTimer = null; }
lucide.createIcons();
return;
}
// Start preview β simulate 10-second snippet
_previewPlaying = true;
snippet.classList.add('bf-preview-active');
if (playIcon) { playIcon.setAttribute('data-lucide', 'pause'); playIcon.classList.remove('ml-0.5'); }
let secondsLeft = 10;
if (timeLabel) timeLabel.textContent = 'Playing Β· 0:' + String(secondsLeft).padStart(2, '0');
lucide.createIcons();
_previewTimer = setInterval(() => {
secondsLeft--;
if (secondsLeft <= 0) {
// Auto-stop after 10 seconds
_previewPlaying = false;
snippet.classList.remove('bf-preview-active');
if (playIcon) { playIcon.setAttribute('data-lucide', 'play'); playIcon.classList.add('ml-0.5'); }
if (timeLabel) timeLabel.textContent = 'Preview Β· 0:10';
clearInterval(_previewTimer);
_previewTimer = null;
lucide.createIcons();
return;
}
if (timeLabel) timeLabel.textContent = 'Playing Β· 0:' + String(secondsLeft).padStart(2, '0');
}, 1000);
};
// ===== QUICK AMOUNT SELECTOR =====
const selectQuickAmount = (amount) => {
const input = document.getElementById('bfDownloadAmount');
if (input) input.value = amount > 0 ? amount.toFixed(2) : '';
document.querySelectorAll('.bf-quick-amount').forEach(btn => {
const btnVal = parseFloat(btn.textContent.replace('
injectStyles();
injectBottomNav(activeTab);
migrateSuperFanData();
syncPlayer();
updateTopNav();
adjustTopNav();
updateSuperFanButtons();
if (window.lucide) lucide.createIcons();
// Re-sync player every 2 seconds
setInterval(syncPlayer, 2000);
};
return {
isLoggedIn, isProducer, isFan, getCurrentUser, signIn, signOut, signUp,
getAllTracks, getArtists, getGenres, getTrendingTracks, getFreshUploads,
searchTracks, searchArtists,
init, showSignInModal, closeSignInModal, handleSignIn,
showSignUpForm, showSignInForm, showChooseType, handleSignUp,
adjustTopNav, showToast, syncPlayer, playTrack, togglePlay,
showSuperFanModal, closeSuperFanModal, confirmSuperFanPayment, showSuperFanPaymentStep, showSuperFanSummaryStep, formatCardNumber, formatCardExpiry, isSuperFanOf, updateSuperFanButtons,
getSuperFanSubscriptions, cancelSuperFanSubscription,
showDownloadModal, closeDownloadModal, isDownloadUnlocked, unlockTrackDownload, getDownloadStates, handleDownloadUnlock, processMockDownload,
// Role system
ROLES, getUserRole, canBrowse, canDownload, canUpload, canEarn, hasFreeDownloads,
// Monetization
MONETIZATION_DEFAULTS, getMonetizationConfig,
getTrackMonetization, setTrackMonetization, isTrackLocked,
// Creator earnings
getCreatorEarnings, recordCreatorEarning, getCreatorEarningsSummary,
// Enhanced transactions
getTransactionHistory
};
})();, ''));
btn.classList.toggle('active', amount > 0 && btnVal === amount);
});
const cta = document.getElementById('bfDownloadCta');
if (cta) {
if (amount > 0) {
cta.innerHTML = '<i data-lucide="lock" class="w-5 h-5"></i> Unlock & Download Β·
injectStyles();
injectBottomNav(activeTab);
migrateSuperFanData();
syncPlayer();
updateTopNav();
adjustTopNav();
updateSuperFanButtons();
if (window.lucide) lucide.createIcons();
// Re-sync player every 2 seconds
setInterval(syncPlayer, 2000);
};
return {
isLoggedIn, isProducer, isFan, getCurrentUser, signIn, signOut, signUp,
getAllTracks, getArtists, getGenres, getTrendingTracks, getFreshUploads,
searchTracks, searchArtists,
init, showSignInModal, closeSignInModal, handleSignIn,
showSignUpForm, showSignInForm, showChooseType, handleSignUp,
adjustTopNav, showToast, syncPlayer, playTrack, togglePlay,
showSuperFanModal, closeSuperFanModal, confirmSuperFanPayment, showSuperFanPaymentStep, showSuperFanSummaryStep, formatCardNumber, formatCardExpiry, isSuperFanOf, updateSuperFanButtons,
getSuperFanSubscriptions, cancelSuperFanSubscription,
showDownloadModal, closeDownloadModal, isDownloadUnlocked, unlockTrackDownload, getDownloadStates, handleDownloadUnlock, processMockDownload,
// Role system
ROLES, getUserRole, canBrowse, canDownload, canUpload, canEarn, hasFreeDownloads,
// Monetization
MONETIZATION_DEFAULTS, getMonetizationConfig,
getTrackMonetization, setTrackMonetization, isTrackLocked,
// Creator earnings
getCreatorEarnings, recordCreatorEarning, getCreatorEarningsSummary,
// Enhanced transactions
getTransactionHistory
};
})(); + amount.toFixed(2);
} else {
cta.innerHTML = '<i data-lucide="lock" class="w-5 h-5"></i> Unlock & Download';
}
if (window.lucide) lucide.createIcons();
}
if (amount === 0 && input) input.focus();
};
const onCustomAmountInput = () => {
const input = document.getElementById('bfDownloadAmount');
const val = parseFloat(input?.value);
document.querySelectorAll('.bf-quick-amount').forEach(btn => btn.classList.remove('active'));
const cta = document.getElementById('bfDownloadCta');
if (cta) {
if (val && val >= 0.50) {
cta.innerHTML = '<i data-lucide="lock" class="w-5 h-5"></i> Unlock & Download Β·
injectStyles();
injectBottomNav(activeTab);
migrateSuperFanData();
syncPlayer();
updateTopNav();
adjustTopNav();
updateSuperFanButtons();
if (window.lucide) lucide.createIcons();
// Re-sync player every 2 seconds
setInterval(syncPlayer, 2000);
};
return {
isLoggedIn, isProducer, isFan, getCurrentUser, signIn, signOut, signUp,
getAllTracks, getArtists, getGenres, getTrendingTracks, getFreshUploads,
searchTracks, searchArtists,
init, showSignInModal, closeSignInModal, handleSignIn,
showSignUpForm, showSignInForm, showChooseType, handleSignUp,
adjustTopNav, showToast, syncPlayer, playTrack, togglePlay,
showSuperFanModal, closeSuperFanModal, confirmSuperFanPayment, showSuperFanPaymentStep, showSuperFanSummaryStep, formatCardNumber, formatCardExpiry, isSuperFanOf, updateSuperFanButtons,
getSuperFanSubscriptions, cancelSuperFanSubscription,
showDownloadModal, closeDownloadModal, isDownloadUnlocked, unlockTrackDownload, getDownloadStates, handleDownloadUnlock, processMockDownload,
// Role system
ROLES, getUserRole, canBrowse, canDownload, canUpload, canEarn, hasFreeDownloads,
// Monetization
MONETIZATION_DEFAULTS, getMonetizationConfig,
getTrackMonetization, setTrackMonetization, isTrackLocked,
// Creator earnings
getCreatorEarnings, recordCreatorEarning, getCreatorEarningsSummary,
// Enhanced transactions
getTransactionHistory
};
})(); + val.toFixed(2);
} else {
cta.innerHTML = '<i data-lucide="lock" class="w-5 h-5"></i> Unlock & Download';
}
if (window.lucide) lucide.createIcons();
}
};
// ===== CREATOR ONBOARDING =====
const isFirstTimeCreator = () => {
const user = getCurrentUser();
if (!user || (user.role !== 'producer' && !user.isArtist)) return false;
const userTracks = getAllTracks().filter(t => t.artistId === user.id || t.artist === (user.displayName || user.username));
return userTracks.length === 0;
};
const getOnboardingState = () => {
const user = getCurrentUser();
if (!user) return { isOnboarding: false, steps: [], completedCount: 0, totalCount: 4 };
const userTracks = getAllTracks().filter(t => t.artistId === user.id || t.artist === (user.displayName || user.username));
const earnings = getCreatorEarningsSummary(user.id || (user.displayName || user.username));
const totalPlays = userTracks.reduce((s, t) => { const p = parseFloat(t.plays || '0'); return s + ((t.plays || '').includes('K') ? p * 1000 : p); }, 0);
const steps = [
{ id: 'signup', label: 'Create Producer account', icon: 'user-plus', completed: true },
{ id: 'first_upload', label: 'Upload your first beat', icon: 'upload-cloud', completed: userTracks.length > 0 },
{ id: 'earn_10', label: 'Earn your first $10', icon: 'dollar-sign', completed: earnings.totalNet >= 10 },
{ id: 'get_plays', label: 'Get 100 plays', icon: 'play-circle', completed: totalPlays >= 100 }
];
return { isOnboarding: !steps.every(s => s.completed), steps, completedCount: steps.filter(s => s.completed).length, totalCount: steps.length };
};
const getCreatorBadges = () => {
const user = getCurrentUser();
if (!user) return [];
const userTracks = getAllTracks().filter(t => t.artistId === user.id || t.artist === (user.displayName || user.username));
const earnings = getCreatorEarningsSummary(user.id || (user.displayName || user.username));
const totalPlays = userTracks.reduce((s, t) => { const p = parseFloat(t.plays || '0'); return s + ((t.plays || '').includes('K') ? p * 1000 : p); }, 0);
const badges = [];
if (userTracks.length >= 1) badges.push({ id: 'first_upload', icon: 'π΅', label: 'First Upload', description: 'Uploaded your first track', earned: true });
if (earnings.totalNet >= 10) badges.push({ id: 'earn_10', icon: 'π°', label: 'First $10', description: 'Earned your first $10', earned: true });
if (earnings.totalNet >= 50) badges.push({ id: 'earn_50', icon: 'π₯', label: '$50 Club', description: 'Earned $50 on the platform', earned: true });
if (earnings.totalNet >= 100) badges.push({ id: 'earn_100', icon: 'π', label: '$100 Club', description: 'Earned $100 on the platform', earned: true });
if (userTracks.length >= 5) badges.push({ id: '5_tracks', icon: 'πΉ', label: '5 Tracks', description: 'Uploaded 5 tracks', earned: true });
if (userTracks.length >= 10) badges.push({ id: '10_tracks', icon: 'ποΈ', label: '10 Tracks', description: 'Uploaded 10 tracks', earned: true });
if (totalPlays >= 1000) badges.push({ id: '1k_plays', icon: 'π§', label: '1K Plays', description: 'Reached 1,000 total plays', earned: true });
if (totalPlays >= 10000) badges.push({ id: '10k_plays', icon: 'π', label: '10K Plays', description: 'Reached 10,000 total plays', earned: true });
if (!badges.find(b => b.id === 'earn_10')) badges.push({ id: 'earn_10', icon: 'π°', label: 'First $10', description: 'Earn your first $10', earned: false });
if (!badges.find(b => b.id === '5_tracks')) badges.push({ id: '5_tracks', icon: 'πΉ', label: '5 Tracks', description: 'Upload 5 tracks', earned: false });
if (!badges.find(b => b.id === '1k_plays')) badges.push({ id: '1k_plays', icon: 'π§', label: '1K Plays', description: 'Reach 1,000 total plays', earned: false });
return badges;
};
const getTopCreatorsThisWeek = () => {
return [
{ name: 'Aurora Void', image: 'http://static.photos/people/200x200/77', tracks: 247, earnings: '$1,247', genre: 'Techno', change: '+23%', rank: 1 },
{ name: 'Neon Prophet', image: 'http://static.photos/people/200x200/10', tracks: 89, earnings: '$834', genre: 'Techno', change: '+18%', rank: 2 },
{ name: 'Cyber Dreamer', image: 'http://static.photos/people/200x200/11', tracks: 56, earnings: '$612', genre: 'Synthwave', change: '+31%', rank: 3 },
{ name: 'Deep Frequencies', image: 'http://static.photos/people/200x200/13', tracks: 34, earnings: '$428', genre: 'Ambient', change: '+12%', rank: 4 },
{ name: 'Bass Architect', image: 'http://static.photos/people/200x200/14', tracks: 67, earnings: '$389', genre: 'D&B', change: '+9%', rank: 5 }
];
};
const getMotivationalPrompt = () => {
const prompts = [
'Your beat could be someone\'s next hit π΅',
'Every upload brings you closer to your first $10 π°',
'Top creators started with just one track π',
'Share your sound β the world is listening π§',
'One upload today could change everything β¨',
'Your music deserves to be heard πΆ',
'The next chart-topper starts with you π',
'Don\'t let your beats stay on your hard drive π€'
];
return prompts[Math.floor(Math.random() * prompts.length)];
};
const dismissOnboarding = () => {
localStorage.setItem('bf_onboarding_dismissed', 'true');
};
const isOnboardingDismissed = () => {
return localStorage.getItem('bf_onboarding_dismissed') === 'true';
};
// ===== INIT =====
const init = (activeTab) => {
injectStyles();
injectBottomNav(activeTab);
migrateSuperFanData();
syncPlayer();
updateTopNav();
adjustTopNav();
updateSuperFanButtons();
if (window.lucide) lucide.createIcons();
// Re-sync player every 2 seconds
setInterval(syncPlayer, 2000);
};
return {
isLoggedIn, isProducer, isFan, getCurrentUser, signIn, signOut, signUp,
getAllTracks, getArtists, getGenres, getTrendingTracks, getFreshUploads,
searchTracks, searchArtists,
init, showSignInModal, closeSignInModal, handleSignIn,
showSignUpForm, showSignInForm, showChooseType, handleSignUp,
adjustTopNav, showToast, syncPlayer, playTrack, togglePlay,
showSuperFanModal, closeSuperFanModal, confirmSuperFanPayment, showSuperFanPaymentStep, showSuperFanSummaryStep, formatCardNumber, formatCardExpiry, isSuperFanOf, updateSuperFanButtons,
getSuperFanSubscriptions, cancelSuperFanSubscription,
showDownloadModal, closeDownloadModal, isDownloadUnlocked, unlockTrackDownload, getDownloadStates, handleDownloadUnlock, processMockDownload,
// Role system
ROLES, getUserRole, canBrowse, canDownload, canUpload, canEarn, hasFreeDownloads,
// Monetization
MONETIZATION_DEFAULTS, getMonetizationConfig,
getTrackMonetization, setTrackMonetization, isTrackLocked,
// Creator earnings
getCreatorEarnings, recordCreatorEarning, getCreatorEarningsSummary,
// Enhanced transactions
getTransactionHistory
};
})(); |