<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>ARTEE</title>
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Arabic:wght@300;400;500;600&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap" rel="stylesheet"/>
<style>
:root{
  --gold:#7C7454;
  --beige:#E0DCCD;
  --offwhite:#F9F8F7;
  --white:#FFFFFF;
  --dark:#232323;
  --black:#000000;
  --font-ar:'IBM Plex Arabic',sans-serif;
  --font-en:'IBM Plex Sans',sans-serif;
  --bg-hero:#232323;
  --bg-about:#1a1a1a;
  --bg-services:#1a1a1a;
  --bg-cta:#000000;
  --nav-bg:rgba(35,35,35,0.96);
  --nav-border:rgba(124,116,84,0.3);
  --text-main:#232323;
}
body.light-mode{
  --bg-hero:#F9F8F7;
  --bg-about:#F5F3EE;
  --bg-services:#FFFFFF;
  --bg-cta:#000000;
  --nav-bg:rgba(249,248,247,0.96);
  --nav-border:rgba(35,35,35,0.14);
  --text-main:#232323;
}
*{margin:0;padding:0;box-sizing:border-box;}
html{scroll-behavior:smooth;}
body{background:var(--offwhite);color:var(--dark);font-family:var(--font-ar);direction:rtl;transition:background .4s,color .4s;}
body.lang-en{font-family:var(--font-en);direction:ltr;}
.site-announcement{position:fixed;z-index:99;top:64px;inset-inline:0;min-height:38px;display:flex;align-items:center;justify-content:center;padding:8px 18px;background:var(--gold);color:var(--offwhite);font-size:13px;text-align:center;box-shadow:0 10px 30px rgba(0,0,0,.18)}
.site-announcement[hidden]{display:none}.site-announcement-active .hero{padding-top:102px}.site-announcement-active .mobile-menu{top:102px}
body[data-site-theme="national_day"] .hero::after{content:"";position:absolute;inset:0;pointer-events:none;background:radial-gradient(circle at 12% 15%,rgba(255,255,255,.08),transparent 25%),linear-gradient(135deg,rgba(11,107,72,.14),transparent 55%)}
body[data-site-theme="founding_day"] .hero::after{content:"";position:absolute;inset:0;pointer-events:none;background:radial-gradient(circle at 88% 18%,rgba(241,223,197,.10),transparent 28%)}
body[data-site-theme="ramadan"] .hero::after{content:"";position:absolute;inset:0;pointer-events:none;background:radial-gradient(circle at 50% 0,rgba(117,90,155,.18),transparent 36%)}
a{text-decoration:none;color:inherit;}

/* NAV */
nav{position:fixed;top:0;width:100%;z-index:100;background:var(--nav-bg);border-bottom:1px solid var(--nav-border);padding:0 48px;backdrop-filter:blur(12px);transition:background .4s,border-color .4s;}
.nav-inner{max-width:1200px;margin:0 auto;display:flex;align-items:center;justify-content:space-between;height:64px;gap:16px;}
.logo-mark{display:flex;align-items:center;gap:10px;flex-shrink:0;}
.brand-logo{display:block;width:auto;object-fit:contain;}
.nav-brand-logo{height:52px;max-width:105px;}
.nav-links{display:flex;gap:28px;list-style:none;}
.nav-links a{font-size:11px;letter-spacing:3px;color:rgba(224,220,205,0.65);text-transform:uppercase;transition:color .2s;}
body.light-mode .nav-links a{color:rgba(35,35,35,0.55);}
.nav-links a:hover{color:var(--gold);}
.nav-right{display:flex;align-items:center;gap:12px;flex-shrink:0;}
.nav-lang{font-size:11px;letter-spacing:2px;color:rgba(224,220,205,0.5);cursor:pointer;border:1px solid rgba(124,116,84,0.3);padding:5px 12px;border-radius:3px;transition:all .2s;background:transparent;font-family:var(--font-ar);}
body.light-mode .nav-lang{color:rgba(35,35,35,0.5);}
.nav-lang:hover{color:var(--gold);border-color:var(--gold);}
.nav-notify,.nav-cart{width:34px;height:34px;border:1px solid rgba(124,116,84,0.3);border-radius:3px;display:none;align-items:center;justify-content:center;position:relative;transition:all .2s;background:transparent;color:var(--gold);cursor:pointer;}
.nav-notify.visible,.nav-cart.visible{display:flex;}
.nav-notify:hover,.nav-cart:hover{border-color:var(--gold);background:rgba(124,116,84,.08);}
.nav-notify svg,.nav-cart svg{width:16px;height:16px;stroke:currentColor;fill:none;stroke-width:1.6;}
.nav-notify-badge,.nav-cart-badge{position:absolute;top:6px;right:6px;width:7px;height:7px;border-radius:50%;background:var(--gold);box-shadow:0 0 12px rgba(124,116,84,.8);}
.nav-cart-badge{width:auto;min-width:15px;height:15px;top:-5px;right:-5px;display:grid;place-items:center;padding:0 4px;color:var(--offwhite);font-size:9px;line-height:1;}
body.light-mode .nav-notify,body.light-mode .nav-cart{color:var(--gold);}
.nav-mode{width:34px;height:34px;border:1px solid rgba(124,116,84,0.3);border-radius:3px;display:flex;align-items:center;justify-content:center;cursor:pointer;transition:all .2s;background:transparent;}
.nav-mode:hover{border-color:var(--gold);}
.nav-mode svg{width:16px;height:16px;stroke:var(--gold);fill:none;stroke-width:1.5;}
.nav-login{font-size:11px;letter-spacing:3px;text-transform:uppercase;border:1px solid var(--gold);color:var(--gold);padding:7px 18px;border-radius:3px;transition:all .2s;white-space:nowrap;}
.nav-login:hover{background:var(--gold);color:var(--offwhite);}
.nav-login.logged-in{display:flex;align-items:center;gap:8px;letter-spacing:1px;text-transform:none;padding:5px 12px;}
.account-avatar{width:24px;height:24px;border-radius:50%;background:var(--gold);color:var(--offwhite);display:inline-flex;align-items:center;justify-content:center;font-size:11px;font-weight:600;}
.account-menu{position:fixed;z-index:9999;min-width:230px;padding:10px;border:1px solid rgba(124,116,84,.34);border-radius:10px;background:rgba(18,18,18,.92);box-shadow:0 24px 70px rgba(0,0,0,.28);backdrop-filter:blur(16px);display:none;transform:translateY(8px);opacity:0;transition:opacity .18s ease,transform .18s ease;}
.account-menu.open{display:grid;gap:6px;opacity:1;transform:translateY(0);}
.account-menu a{display:flex;align-items:center;justify-content:space-between;gap:12px;border:1px solid transparent;border-radius:7px;padding:10px 11px;color:rgba(224,220,205,.72);font-size:13px;letter-spacing:0;text-transform:none;transition:all .18s ease;}
.account-menu a:hover{border-color:rgba(124,116,84,.32);background:rgba(124,116,84,.12);color:var(--gold);}
.account-menu a span{font-size:10px;letter-spacing:2px;color:rgba(124,116,84,.9);}
body.light-mode .account-menu{background:rgba(249,248,247,.94);box-shadow:0 24px 70px rgba(35,35,35,.12);}
body.light-mode .account-menu a{color:rgba(35,35,35,.66);}
body.light-mode .account-menu a:hover{color:var(--gold);}
.hamburger{display:none;flex-direction:column;gap:5px;cursor:pointer;padding:4px;}
.hamburger span{width:22px;height:1.5px;background:var(--gold);display:block;transition:all .3s;}

/* HERO */
.hero{min-height:100vh;background:var(--bg-hero);display:flex;align-items:center;position:relative;overflow:hidden;padding:0 48px;transition:background .4s;}
.hero-pattern{position:absolute;inset:0;opacity:.04;background-image:radial-gradient(circle,var(--gold) 1px,transparent 1px);background-size:48px 48px;transition:transform .1s ease-out;}
.hero-line-v{position:absolute;left:40%;top:0;bottom:0;width:1px;background:rgba(124,116,84,0.12);}
.hero-line-h{position:absolute;top:55%;left:0;right:0;height:1px;background:rgba(124,116,84,0.08);}
.hero-circle{position:absolute;left:38%;top:50%;transform:translate(-50%,-50%);width:440px;height:440px;border:1px solid rgba(124,116,84,0.1);border-radius:50%;transition:transform .15s ease-out;}
.hero-circle2{position:absolute;left:38%;top:50%;transform:translate(-50%,-50%);width:280px;height:280px;border:1px solid rgba(124,116,84,0.07);border-radius:50%;transition:transform .15s ease-out;}
.hero-inner{max-width:1200px;margin:0 auto;width:100%;display:grid;grid-template-columns:1fr 1fr;gap:64px;align-items:center;position:relative;z-index:2;padding-top:64px;}
.hero-label{font-size:10px;letter-spacing:4px;text-transform:uppercase;color:var(--gold);margin-bottom:24px;}
.hero-title{font-size:52px;font-weight:600;color:var(--beige);line-height:1.15;margin-bottom:24px;}
body.light-mode .hero-title{color:var(--dark);}
.hero-title span{color:var(--gold);}
.hero-sub{font-size:15px;color:rgba(224,220,205,0.55);line-height:1.9;margin-bottom:40px;max-width:420px;}
body.light-mode .hero-sub{color:rgba(35,35,35,0.6);}
.hero-actions{display:flex;gap:16px;align-items:center;flex-wrap:wrap;}
.btn-primary{font-size:11px;letter-spacing:3px;text-transform:uppercase;background:var(--gold);color:var(--offwhite);padding:14px 32px;border-radius:3px;transition:all .2s;}
.btn-primary:hover{background:#9a9068;}
.btn-ghost{font-size:11px;letter-spacing:3px;text-transform:uppercase;border:1px solid rgba(224,220,205,0.3);color:rgba(224,220,205,0.6);padding:14px 32px;border-radius:3px;transition:all .2s;}
body.light-mode .btn-ghost{border-color:rgba(35,35,35,0.3);color:rgba(35,35,35,0.6);}
.btn-ghost:hover{border-color:var(--gold);color:var(--gold);}
.hero-scroll{position:absolute;bottom:32px;left:50%;transform:translateX(-50%);display:flex;flex-direction:column;align-items:center;gap:8px;color:rgba(224,220,205,0.3);font-size:9px;letter-spacing:3px;text-transform:uppercase;}
body.light-mode .hero-scroll{color:rgba(35,35,35,.32);}
.scroll-line{width:1px;height:40px;background:rgba(124,116,84,0.4);}

/* 3D CARD */
.hero-visual{display:flex;justify-content:center;align-items:center;}
.card-scene{perspective:1100px;width:410px;padding:34px;}
.card-wrapper{position:relative;transform-style:preserve-3d;cursor:pointer;border-radius:6px;}
.card-glow{position:absolute;inset:-2px;border-radius:8px;background:radial-gradient(ellipse at 50% 50%,rgba(124,116,84,0.25),transparent 70%);opacity:0;transition:opacity .3s;pointer-events:none;filter:blur(8px);}
.card-scene:hover .card-glow{opacity:1;}
.card-panel{background:rgba(255,255,255,0.04);border:1px solid rgba(124,116,84,0.3);border-radius:6px;padding:42px 46px 46px;min-height:430px;position:relative;overflow:visible;transform-style:preserve-3d;box-shadow:0 28px 55px rgba(0,0,0,.24);display:flex;flex-direction:column;justify-content:center;}
.card-panel::before{content:'';position:absolute;inset:0;background:repeating-linear-gradient(45deg,rgba(124,116,84,0.025) 0,rgba(124,116,84,0.025) 1px,transparent 1px,transparent 10px);pointer-events:none;}
.card-depth-layer{position:absolute;inset:8px;border:1px solid rgba(124,116,84,0.08);border-radius:4px;transform:translateZ(8px);pointer-events:none;}
.card-tabs{display:flex;gap:0;margin-bottom:42px;border:1px solid rgba(124,116,84,0.25);border-radius:3px;overflow:hidden;position:relative;transform:translateZ(32px);}
.card-tab{flex:1;padding:9px 8px;font-size:10px;line-height:1.45;letter-spacing:.1px;text-align:center;color:rgba(224,220,205,0.4);cursor:pointer;transition:all .25s;background:transparent;border:none;font-family:var(--font-ar);}
.card-tab.active{background:var(--gold);color:var(--offwhite);}
.card-tab:hover:not(.active){color:var(--gold);}
.display-nfc{display:block;}
.display-3d{display:none;}
.display-nfc.active,.display-3d.active{display:flex;flex-direction:column;align-items:center;position:relative;transform-style:preserve-3d;}
.nfc-card-img{width:246px;height:151px;background:#050505;border:1px solid rgba(124,116,84,0.38);border-radius:14px;overflow:hidden;position:relative;display:flex;align-items:center;justify-content:center;transform:translate3d(0,0,18px) scale(.78);box-shadow:0 8px 16px rgba(0,0,0,.22);transition:transform .16s ease-out,box-shadow .2s ease-out;will-change:transform;}
.nfc-card-img img,.nfc-card-img picture{width:100%;height:100%;display:block;}
.nfc-card-img img{object-fit:contain;object-position:center;background:#050505;}
.nfc-sparkle{position:absolute;inset:0;background:linear-gradient(125deg,transparent 30%,rgba(124,116,84,0.15) 50%,transparent 70%);animation:shimmer 3s infinite;}
@keyframes shimmer{0%{transform:translateX(-100%)}100%{transform:translateX(200%)}}
.nfc-card-text{width:100%;margin-top:24px;position:relative;transform:translateZ(48px);}
.nfc-card-name{font-size:12px;letter-spacing:3px;color:var(--beige);font-weight:500;margin-bottom:4px;}
.nfc-card-sub{font-size:10px;letter-spacing:.2px;line-height:1.7;color:rgba(224,220,205,0.42);max-width:260px;margin:0 auto;}
.cube-scene{width:246px;height:151px;perspective:680px;margin:0 auto 8px;transform:translate3d(0,0,18px) scale(.78);filter:drop-shadow(0 8px 16px rgba(0,0,0,.22));transition:filter .28s ease,transform .16s ease-out;will-change:filter,transform;display:flex;align-items:center;justify-content:center;}
.card-scene:hover .display-3d.active .cube-scene{filter:drop-shadow(0 0 18px rgba(224,220,205,.2)) drop-shadow(0 18px 18px rgba(0,0,0,.44));}
.cube{--cube-size:150px;--cubie:60px;--half:30px;--metal-a:#e5e7e5;--metal-b:#909696;--metal-c:#2d3334;--edge-dark:#060708;--shift-x:0px;--shift-y:0px;width:var(--cube-size);height:var(--cube-size);position:relative;margin:0 auto;transform-style:preserve-3d;transform:rotateX(-27deg) rotateY(-38deg) rotateZ(-5deg);transition:transform .18s ease-out;will-change:transform;}
.cube::before{content:'';position:absolute;inset:22px;border-radius:50%;background:radial-gradient(circle,rgba(224,220,205,.18),transparent 70%);transform:translateZ(-92px);filter:blur(22px);opacity:.7;}
.cubie{position:absolute;left:50%;top:50%;width:var(--cubie);height:var(--cubie);transform-style:preserve-3d;transform:translate3d(var(--tx),var(--ty),var(--tz)) translate(-50%,-50%);transition:transform .18s ease-out;}
.cubie:nth-child(odd){transform:translate3d(calc(var(--tx) + var(--shift-x)),calc(var(--ty) + var(--shift-y)),var(--tz)) translate(-50%,-50%);}
.cubie:nth-child(even){transform:translate3d(calc(var(--tx) - var(--shift-x)),calc(var(--ty) - var(--shift-y)),var(--tz)) translate(-50%,-50%);}
.c-side{position:absolute;inset:0;border:10px solid var(--metal-b);border-radius:0;background:transparent;box-shadow:inset 5px 5px 9px rgba(0,0,0,.4),inset -4px -4px 8px rgba(255,255,255,.17),0 4px 8px rgba(0,0,0,.4);backface-visibility:hidden;}
.c-side::before{content:'';position:absolute;inset:-10px;border-radius:0;border:1px solid rgba(255,255,255,.22);box-shadow:inset 2px 2px 5px rgba(255,255,255,.2),inset -6px -6px 9px rgba(0,0,0,.34);pointer-events:none;}
.c-front{border-color:#8e9494;transform:translateZ(var(--half));}
.c-back{border-color:#303637;transform:rotateY(180deg) translateZ(var(--half));}
.c-front{--side-light:#d0d4d2;--side-mid:#8d9393;--side-dark:#303637;}
.c-back{--side-light:#858b8b;--side-mid:#4a5050;--side-dark:#1c2021;}
.c-right{--side-light:#eef0ee;--side-mid:#b4b9b8;--side-dark:#5b6262;transform:rotateY(90deg) translateZ(var(--half));}
.c-left{--side-light:#6e7575;--side-mid:#303637;--side-dark:#151819;transform:rotateY(-90deg) translateZ(var(--half));}
.c-top{--side-light:#f7f8f6;--side-mid:#c4c9c8;--side-dark:#697070;transform:rotateX(90deg) translateZ(var(--half));}
.c-bottom{--side-light:#596060;--side-mid:#252a2b;--side-dark:#101314;transform:rotateX(-90deg) translateZ(var(--half));}
.cube-label{display:none;}
body.light-mode .display-3d.active .cube-scene{filter:drop-shadow(0 18px 14px rgba(35,35,35,.18));}
body.light-mode .cube{--tile-a:#f3f4f2;--tile-b:#a4aaaa;--tile-c:#373d3e;--grid-line:rgba(35,35,35,.82);--groove-shadow:rgba(35,35,35,.52);}
body.light-mode .cube::before{background:radial-gradient(circle,rgba(35,35,35,.16),transparent 66%);opacity:.52;}
body.light-mode .card-scene:hover .display-3d.active .cube-scene{filter:drop-shadow(0 0 18px rgba(35,35,35,.18)) drop-shadow(0 18px 18px rgba(35,35,35,.16));}

/* ABOUT */
.about{padding:120px 48px;background:var(--bg-about);transition:background .4s;}
.about-grid{max-width:1200px;margin:0 auto;display:grid;grid-template-columns:minmax(0,.92fr) minmax(0,1.08fr);gap:26px 64px;align-items:stretch;}
.about-question{grid-column:1/-1;}
.about-visual{position:relative;min-height:100%;}
.about-box-main{background:rgba(255,255,255,0.04);border:1px solid rgba(124,116,84,0.2);border-radius:6px;padding:46px;min-height:100%;display:flex;flex-direction:column;justify-content:space-between;align-items:flex-start;overflow:hidden;position:relative;}
.about-brand-logo{width:76%;height:auto;max-height:360px;object-fit:contain;align-self:center;margin:auto;filter:drop-shadow(0 24px 30px rgba(0,0,0,.2));transition:transform .6s cubic-bezier(.2,.75,.2,1);}
.about-box-main:hover .about-brand-logo{transform:scale(1.06) translateY(-6px);}
.about-founded{font-size:11px;letter-spacing:3px;color:rgba(224,220,205,0.25);margin-top:16px;}
body.light-mode .about-founded{color:rgba(35,35,35,0.3);}
.about-accent,.about-accent2{display:none;}
.section-label{font-size:10px;letter-spacing:4px;text-transform:uppercase;color:var(--gold);margin-bottom:16px;}
.section-title{font-size:34px;font-weight:600;line-height:1.3;}
.section-title.on-dark{color:var(--beige);}
.section-title.on-light{color:var(--dark);}
.section-title span{color:var(--gold);}
.about-question,.services-question{display:flex;align-items:flex-start;justify-content:flex-start;gap:10px;color:var(--white);font-size:64px;font-weight:600;line-height:1;margin-bottom:8px;padding-bottom:24px;border-bottom:1px solid rgba(124,116,84,.18);}
.about-question span{display:inline-block;color:var(--gold);font-size:72px;font-weight:300;transform:rotate(-16deg) translateY(-10px);transition:transform .35s;}
.about-question:hover span{transform:rotate(12deg) translateY(-14px);}
.services-question span{color:var(--gold);font-weight:300;margin:0 6px;}
.section-rule{width:48px;height:1px;background:var(--gold);margin-top:24px;margin-bottom:32px;}
.about-body{font-size:15px;color:rgba(224,220,205,0.55);line-height:1.9;margin-bottom:40px;}
.about-content{display:flex;flex-direction:column;justify-content:flex-start;padding-top:4px;}
body.light-mode .about-body{color:rgba(35,35,35,0.6);}
.about-pillars{display:flex;gap:8px;height:180px;}
.pillar{position:relative;flex:1;min-width:0;border:1px solid rgba(124,116,84,.25);border-radius:4px;padding:22px 16px;overflow:hidden;cursor:pointer;background:rgba(255,255,255,.025);transition:flex .55s cubic-bezier(.2,.75,.2,1),background .35s,border-color .35s;}
.pillar:hover,.pillar.active{flex:3.4;background:rgba(124,116,84,.12);border-color:rgba(124,116,84,.55);}
.pillar-title{font-size:13px;font-weight:500;color:var(--beige);margin-bottom:14px;white-space:nowrap;}
body.light-mode .pillar-title{color:var(--dark);}
.pillar-title::after{content:'+';display:grid;place-items:center;width:22px;height:22px;line-height:1;color:var(--gold);font-size:18px;margin-top:10px;transform:rotate(0);transform-origin:50% 50%;transition:transform .3s;}
.pillar:hover .pillar-title::after,.pillar.active .pillar-title::after{transform:rotate(45deg);}
.pillar-sub{font-size:12px;color:rgba(224,220,205,0.4);line-height:1.8;min-width:180px;opacity:0;transform:translateY(12px);transition:opacity .3s .12s,transform .35s .12s;}
.pillar:hover .pillar-sub,.pillar.active .pillar-sub{opacity:1;transform:none;}
body.light-mode .pillar-sub{color:rgba(35,35,35,0.5);}

/* SERVICES */
.services{padding:96px 48px 120px;background:var(--bg-services);transition:background .4s;position:relative;overflow:hidden;}
.services::before,.services::after{display:none;}
.services-inner{max-width:1200px;margin:0 auto;position:relative;z-index:1;}
.services-header{margin-bottom:64px;}
.services-question{margin-bottom:0;}
.services-switcher{display:grid;grid-template-columns:minmax(0,1fr) 190px;min-height:1040px;gap:12px;transition:grid-template-columns .65s cubic-bezier(.2,.75,.2,1);}
.services-switcher[data-active="products"]{grid-template-columns:190px minmax(0,1fr);}
.services-switcher[data-active="products"] .switch-panel[data-panel="products"],
.services-switcher[data-active="products"] .switch-panel[data-panel="products"] .switch-content{min-height:1040px;}
.switch-panel{position:relative;overflow:hidden;border:1px solid rgba(124,116,84,.24);background:rgba(255,255,255,.035);transition:background .45s,border-color .45s;cursor:pointer;backdrop-filter:blur(10px);}
.switch-panel.active{cursor:default;border-color:rgba(124,116,84,.38);min-height:1040px;}
.switch-gate{position:absolute;inset:0;width:100%;border:0;display:flex;flex-direction:column;justify-content:space-between;padding:36px 28px;background:#181818;color:var(--beige);font-family:var(--font-ar);text-align:right;cursor:pointer;transition:opacity .3s,transform .6s cubic-bezier(.2,.75,.2,1);z-index:3;}
.switch-panel:not(.active):hover .switch-gate,.switch-panel:not(.active):focus-within .switch-gate{background:#211f1a;color:#fff;box-shadow:inset 0 0 0 1px rgba(224,220,205,.18),inset 0 0 52px rgba(143,133,93,.18);}
.switch-panel:not(.active):hover .gate-title,.switch-panel:not(.active):focus-within .gate-title{color:#fff;text-shadow:0 0 12px rgba(224,220,205,.75),0 0 30px rgba(143,133,93,.55);}
.switch-panel:not(.active):hover .gate-action,.switch-panel:not(.active):focus-within .gate-action{color:var(--beige);}
.switch-panel.active .switch-gate{opacity:0;pointer-events:none;transform:scale(1.05);}
.gate-num{font-size:10px;letter-spacing:4px;color:var(--gold);}
.gate-title{font-size:30px;font-weight:500;writing-mode:vertical-rl;transform:rotate(180deg);letter-spacing:2px;}
.gate-action{font-size:10px;letter-spacing:3px;color:rgba(224,220,205,.45);}
.switch-content{height:100%;padding:52px;opacity:0;visibility:hidden;transform:translateY(18px);transition:opacity .45s .2s,transform .55s .2s,visibility 0s .2s;}
.switch-panel.active .switch-content{opacity:1;visibility:visible;transform:none;min-height:1040px;display:block;}
.switch-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:24px;margin-bottom:36px;padding-bottom:22px;border-bottom:1px solid rgba(124,116,84,.2);}
.switch-title{font-size:34px;font-weight:600;color:var(--beige);}
.switch-count{font-size:10px;letter-spacing:4px;color:var(--gold);}
.items-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;}
.switch-panel.active .items-grid{align-content:start;grid-auto-rows:auto;}
.section-anchor{position:absolute;top:0;right:0;width:1px;height:1px;pointer-events:none;}
.service-item{min-height:205px;padding:26px;border:1px solid rgba(124,116,84,.18);border-radius:4px;background:rgba(255,255,255,.025);transition:background .3s,transform .3s,border-color .3s,opacity .55s,filter .55s;opacity:0;transform:translateY(30px);filter:blur(5px);cursor:pointer;position:relative;}
.service-item.is-coming,.service-item.is-soldout{opacity:1!important;filter:none!important;background:rgba(255,255,255,.016);border-color:rgba(124,116,84,.13)}
.service-item.is-coming > :not(.si-status-orb),.service-item.is-soldout > :not(.si-status-orb){opacity:.42;filter:grayscale(.35) saturate(.72)}
.service-item.is-coming:hover,.service-item.is-soldout:hover{transform:none!important;border-color:rgba(124,116,84,.18);background:rgba(255,255,255,.025)}
.switch-panel.active .service-item.revealed{opacity:1;transform:none;filter:none;}
.service-item:hover{background:var(--dark);transform:translateY(-5px)!important;border-color:var(--dark);}
.service-item.is-soft-source{opacity:1!important;filter:none!important;transform:translateY(-6px) scale(1.015)!important;border-color:rgba(124,116,84,.58)!important;box-shadow:0 20px 55px rgba(0,0,0,.16);}
.service-item:hover .si-title{color:var(--beige);}
.service-item:hover .si-body{color:rgba(224,220,205,0.45);}
.service-item:hover .si-num{color:rgba(124,116,84,0.35);}
.service-item:hover .si-icon{border-color:rgba(124,116,84,0.5);}
.si-icon{width:44px;height:44px;border:1px solid rgba(124,116,84,0.3);border-radius:4px;display:flex;align-items:center;justify-content:center;margin-bottom:20px;transition:all .25s;}
.si-icon svg{width:20px;height:20px;stroke:var(--gold);fill:none;stroke-width:1.5;}
.si-head{display:flex;align-items:center;gap:12px;margin-bottom:20px}.si-head .si-icon{margin-bottom:0;flex:0 0 44px}.si-thumb{width:72px;height:44px;margin-inline-start:auto;object-fit:contain;border:1px solid rgba(124,116,84,.18);border-radius:6px;background:rgba(255,255,255,.025);padding:4px}.service-item.is-coming .si-thumb,.service-item.is-soldout .si-thumb{opacity:.18}
.si-num{font-size:10px;letter-spacing:3px;color:rgba(124,116,84,.45);margin-bottom:8px;text-transform:uppercase;}
.si-title{font-size:20px;font-weight:600;color:var(--beige);margin-bottom:12px;}
.si-body{font-size:14px;color:rgba(224,220,205,.5);line-height:1.9;}
.si-status-orb{position:absolute;left:26px;right:auto;top:28px;width:max-content;max-width:calc(100% - 116px);text-align:left;color:#f8f5ec;font-family:var(--font-ar);font-size:clamp(34px,2.65vw,48px);line-height:1.05;font-weight:700;letter-spacing:.4px;text-transform:uppercase;pointer-events:none;z-index:1;text-shadow:0 0 12px rgba(248,245,236,.98),0 0 32px rgba(248,245,236,.58),0 0 64px rgba(124,116,84,.34);filter:drop-shadow(0 14px 24px rgba(0,0,0,.35))}
.si-status-orb.sale{top:26px;padding:9px 20px;border:1px solid rgba(248,245,236,.78);border-radius:999px;background:linear-gradient(135deg,rgba(248,245,236,.15),rgba(124,116,84,.13));color:#fff7df;font-size:clamp(22px,1.85vw,32px);line-height:1;font-weight:700;letter-spacing:.6px;text-shadow:0 0 9px rgba(255,247,223,.72),0 0 24px rgba(124,116,84,.26);box-shadow:inset 0 0 0 1px rgba(255,255,255,.08),0 0 18px rgba(248,245,236,.13),0 14px 24px rgba(0,0,0,.34);filter:none;transform:none}
.si-status-orb.sale::after{content:'';position:absolute;inset:4px;border:1px solid rgba(255,247,223,.24);border-radius:inherit;pointer-events:none}
.si-status-orb.soldout{color:#ff4b4b;text-shadow:none;filter:drop-shadow(0 12px 18px rgba(0,0,0,.42));letter-spacing:.1px}
.si-status-orb.coming{color:#f8f5ec;text-shadow:0 0 12px rgba(248,245,236,.98),0 0 32px rgba(248,245,236,.58),0 0 64px rgba(124,116,84,.34)}
body.lang-en .si-status-orb{left:auto;right:26px;text-align:right;font-size:clamp(32px,2.5vw,46px);font-weight:800;letter-spacing:3px;max-width:calc(100% - 112px)}
body.lang-en .si-status-orb.sale{font-size:clamp(22px,1.85vw,32px);font-weight:850;letter-spacing:3.4px;transform:none}
body.lang-en .si-status-orb.soldout{font-weight:850;letter-spacing:3px}
.si-icon{z-index:2}
.si-price{display:flex;align-items:center;gap:8px;margin-top:14px;color:var(--beige);font-size:13px}
.si-old-price{text-decoration:line-through;color:rgba(224,220,205,.34)}
.si-link{display:inline-flex;align-items:center;gap:8px;font-size:10px;letter-spacing:3px;text-transform:uppercase;color:var(--gold);margin-top:20px;}

/* ORDER MODAL */
.order-modal{position:fixed;inset:0;z-index:160;display:none;align-items:center;justify-content:center;padding:24px;background:rgba(14,14,14,.10);backdrop-filter:blur(12px) saturate(120%);}
.order-modal.open{display:flex;}
.order-modal.soft-opening{animation:orderVeilIn .52s cubic-bezier(.18,.72,.18,1) both;}
.order-dialog{width:min(520px,100%);max-height:calc(100vh - 42px);overflow:auto;background:linear-gradient(180deg,rgba(255,255,255,.14),rgba(255,255,255,.055));border:1px solid rgba(224,220,205,.22);border-radius:12px;padding:12px;box-shadow:0 28px 80px rgba(0,0,0,.24);position:relative;transform-origin:var(--order-origin-x,50%) var(--order-origin-y,50%);backdrop-filter:blur(24px) saturate(135%);}
.order-modal.soft-opening .order-dialog{animation:orderSoftIn .58s cubic-bezier(.14,.82,.18,1) both;}
.order-dialog::before{content:'';position:absolute;inset:0;border-radius:inherit;background:linear-gradient(145deg,rgba(255,255,255,.18),transparent 38%,rgba(124,116,84,.06));pointer-events:none;}
@keyframes orderSoftIn{0%{opacity:0;transform:translate3d(var(--order-start-x,0px),var(--order-start-y,18px),0) scale(.935);filter:blur(10px);}62%{opacity:1;filter:blur(.6px);}100%{opacity:1;transform:none;filter:none;}}
@keyframes orderVeilIn{from{background:rgba(14,14,14,.02);backdrop-filter:blur(2px) saturate(110%);}to{background:rgba(14,14,14,.10);backdrop-filter:blur(12px) saturate(120%);}}
.order-close{position:absolute;top:18px;left:18px;z-index:2;width:32px;height:32px;border:1px solid rgba(224,220,205,.24);border-radius:50%;background:rgba(12,12,12,.24);color:var(--gold);cursor:pointer;font-size:18px;backdrop-filter:blur(10px);}
.order-kicker{display:none;}
.order-title{position:relative;z-index:1;font-size:16px;color:var(--beige);line-height:1.35;margin:0;padding:12px 10px 14px 46px;border-bottom:1px solid rgba(224,220,205,.14);}
.order-desc{font-size:13px;color:rgba(224,220,205,.52);line-height:1.75;margin-bottom:18px;}
.order-dialog>.order-desc{display:none;}
.order-preview{position:relative;z-index:1;display:flex;flex-direction:column;gap:0;margin-bottom:0;}
.order-image{height:min(60vh,420px);min-height:330px;border:1px solid rgba(224,220,205,.16);border-top:0;border-radius:0 0 10px 10px;background:linear-gradient(135deg,rgba(255,255,255,.09),rgba(124,116,84,.12));display:flex;align-items:center;justify-content:center;overflow:hidden;position:relative;}
.order-image::after{content:'';position:absolute;inset:0;background:linear-gradient(180deg,rgba(255,255,255,.07),transparent 26%,rgba(0,0,0,.10));pointer-events:none;}
.order-image img{width:100%;height:100%;object-fit:contain;display:none;padding:16px;}
.order-modal[data-order-kind="service"] .order-image img{width:46%;height:auto;max-height:180px;filter:drop-shadow(0 20px 28px rgba(0,0,0,.24));opacity:.82;}
.order-modal[data-order-kind="product"] .order-image img{padding:14px;border-radius:12px;object-fit:contain;}
.order-image.has-image img{display:block;}
.order-image span{font-size:38px;color:rgba(124,116,84,.55);}
.order-image.has-image span{display:none;}
.order-info{display:flex;flex-direction:column;justify-content:center;padding:14px 6px 2px;}
.order-info .order-desc{display:block;margin:0 0 10px;color:rgba(224,220,205,.68);line-height:1.8;}
.order-meta{display:none;}
.order-pill{display:none;}
.order-price{color:var(--gold);font-size:18px;font-weight:600;margin:0 0 10px;}
.order-form{position:relative;z-index:1;display:grid;grid-template-columns:1fr;gap:10px;padding:0 6px 6px;}
.order-form label{display:flex;flex-direction:column;gap:7px;font-size:10px;letter-spacing:1.8px;text-transform:uppercase;color:var(--gold);}
.order-form input,.order-form textarea,.order-form select{width:100%;border:1px solid rgba(224,220,205,.18);border-radius:8px;background:rgba(255,255,255,.075);color:var(--beige);font-family:var(--font-ar);font-size:13px;padding:12px 13px;outline:none;transition:border-color .2s,background .2s,box-shadow .2s;backdrop-filter:blur(8px);}
.order-form input:focus,.order-form textarea:focus,.order-form select:focus{border-color:rgba(124,116,84,.70);background:rgba(255,255,255,.10);box-shadow:0 0 0 3px rgba(124,116,84,.10);}
.order-form input[type="file"]{padding:10px;background:rgba(255,255,255,.055);font-size:12px;}
.order-form textarea{grid-column:1/-1;min-height:92px;resize:vertical;}
.order-form label.order-error{color:#d98b8b;}
.order-form label.order-error textarea{border-color:rgba(217,139,139,.82);background:rgba(120,40,40,.12);box-shadow:0 0 0 3px rgba(217,139,139,.08);}
.order-form label.order-error input{border-color:rgba(217,139,139,.82);background:rgba(120,40,40,.12);box-shadow:0 0 0 3px rgba(217,139,139,.08);}
.order-help{color:rgba(224,220,205,.46);font-size:10px;letter-spacing:0;text-transform:none;line-height:1.7;}
.order-note.order-note-error{color:#d98b8b;}
#orderOption{display:none;}
.order-option-groups{display:grid;gap:14px;margin-top:8px}.order-option-group{display:grid;gap:7px}.order-option-group-head{display:flex;justify-content:space-between;gap:10px;align-items:center;color:var(--beige);font-size:12px}.order-option-group-head small{color:rgba(224,220,205,.48);font-size:10px}.order-option-group.order-error{border:1px solid rgba(217,139,139,.65);border-radius:10px;padding:10px;background:rgba(120,40,40,.08)}
.order-options{display:flex;flex-wrap:wrap;gap:8px;margin-top:2px;}
.order-option-pill{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:38px;border:1px solid rgba(224,220,205,.18);border-radius:999px;background:rgba(255,255,255,.055);color:rgba(224,220,205,.70);font-family:var(--font-ar);font-size:12px;padding:9px 15px;cursor:pointer;transition:background .22s,border-color .22s,color .22s,transform .22s,box-shadow .22s;backdrop-filter:blur(8px);}
.order-option-pill:hover{transform:translateY(-1px);border-color:rgba(124,116,84,.48);color:var(--beige);}
.order-option-pill.active{background:rgba(124,116,84,.88);border-color:rgba(224,220,205,.28);color:var(--offwhite);box-shadow:0 12px 28px rgba(0,0,0,.16);}
.order-option-price{font-size:10px;letter-spacing:1.4px;color:rgba(255,255,255,.72);}
.order-option-pill.active .order-option-price{color:rgba(255,255,255,.86);}
.product-config{border:1px solid rgba(224,220,205,.14);border-radius:12px;background:rgba(255,255,255,.035);padding:12px;display:grid;gap:10px;}
.product-config-title{color:var(--beige);font-size:13px;margin:0;}
.product-config-hint{color:rgba(224,220,205,.50);font-size:11px;line-height:1.7;margin:-4px 0 0;}
#productContentMode{display:none;}
.order-shipping{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;border:1px solid rgba(224,220,205,.14);border-radius:12px;background:rgba(255,255,255,.035);padding:12px;}
.order-shipping-title{grid-column:1/-1;color:var(--beige);font-size:13px;letter-spacing:0;text-transform:none;margin:0 0 2px;}
.order-shipping-hint{grid-column:1/-1;margin:-2px 0 4px;color:rgba(224,220,205,.50);font-size:11px;line-height:1.7;letter-spacing:0;text-transform:none;}
.order-shipping .full{grid-column:1/-1;}
.order-shipping label{letter-spacing:1px;}
.order-field-wide{grid-column:1/-1;}
.order-hidden{display:none!important;}
.order-submit{grid-column:1/-1;border:0;background:var(--gold);color:var(--offwhite);font-family:var(--font-ar);padding:13px 22px;border-radius:8px;cursor:pointer;font-size:11px;letter-spacing:3px;text-transform:uppercase;transition:transform .2s,background .2s;}
.order-submit:hover{transform:translateY(-2px);background:#9a9068;}
.order-note{grid-column:1/-1;color:rgba(224,220,205,.58);font-size:12px;line-height:1.7;}
.cart-modal{position:fixed;inset:0;z-index:9998;display:none;align-items:center;justify-content:center;padding:24px;background:rgba(8,8,8,.46);backdrop-filter:blur(12px);}
.cart-modal.open{display:flex;}
.cart-dialog{width:min(620px,100%);border:1px solid rgba(124,116,84,.30);border-radius:16px;background:linear-gradient(180deg,rgba(28,28,28,.92),rgba(18,18,18,.94));box-shadow:0 30px 90px rgba(0,0,0,.34);padding:22px;position:relative;}
.cart-close{position:absolute;top:12px;left:12px;width:34px;height:34px;border:1px solid rgba(124,116,84,.28);border-radius:50%;background:rgba(255,255,255,.04);color:var(--gold);font-size:18px;cursor:pointer;}
.cart-title{font-size:26px;color:var(--beige);margin-bottom:6px;}
.cart-sub{color:rgba(224,220,205,.50);font-size:13px;margin-bottom:16px;}
.cart-list{display:grid;gap:10px;max-height:46vh;overflow:auto;padding-inline-end:4px;}
.cart-list[hidden]{display:none;}
.cart-item{border:1px solid rgba(124,116,84,.22);border-radius:12px;background:rgba(255,255,255,.035);padding:12px;display:grid;grid-template-columns:58px 1fr auto;gap:12px;align-items:center;}
.cart-item img{width:58px;height:44px;object-fit:cover;border-radius:8px;border:1px solid rgba(124,116,84,.18);}
.cart-item strong{display:block;color:var(--beige);font-size:14px;}
.cart-item small{display:block;color:rgba(224,220,205,.45);font-size:11px;margin-top:3px;}
.cart-remove{border:1px solid rgba(180,80,80,.34);color:#d89b9b;background:rgba(180,80,80,.08);border-radius:8px;padding:7px 9px;font-family:inherit;cursor:pointer;}
.cart-step{display:grid;gap:10px;padding-inline-end:4px;}
.cart-step[hidden]{display:none;}
.cart-step-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;}
.cart-step label{font-size:11px;color:rgba(224,220,205,.55);letter-spacing:.4px;display:grid;gap:6px;}
.cart-step input{width:100%;border:1px solid rgba(124,116,84,.24);background:rgba(255,255,255,.035);color:var(--beige);border-radius:9px;padding:10px 12px;font-family:inherit;outline:none;}
.cart-step .full{grid-column:1/-1;}
.cart-step label.order-error input{border-color:rgba(220,90,90,.72);box-shadow:0 0 0 1px rgba(220,90,90,.18);}
.cart-validation-note{min-height:18px;color:#d98b8b;font-size:12px;line-height:1.65;}
.cart-validation-note:empty{display:none;}
.cart-payment-box{border:1px solid rgba(124,116,84,.22);border-radius:12px;background:rgba(255,255,255,.035);padding:14px;color:rgba(224,220,205,.72);line-height:1.9;}
.cart-payment-box strong{display:block;color:var(--beige);font-size:18px;margin-top:6px;}
.cart-footer{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:16px;border-top:1px solid rgba(124,116,84,.18);padding-top:14px;}
.cart-total{color:var(--beige);font-size:14px;}
.cart-checkout{border:0;background:var(--gold);color:var(--offwhite);font-family:inherit;border-radius:9px;padding:11px 16px;cursor:pointer;}
.cart-empty{border:1px dashed rgba(124,116,84,.28);border-radius:12px;padding:22px;color:rgba(224,220,205,.50);text-align:center;}
.notify-dialog{width:min(440px,100%);border:1px solid rgba(124,116,84,.30);border-radius:16px;background:linear-gradient(180deg,rgba(28,28,28,.94),rgba(18,18,18,.96));box-shadow:0 30px 90px rgba(0,0,0,.34);padding:24px;position:relative;text-align:right;}
.notify-title{font-size:24px;color:var(--beige);margin-bottom:8px;}
.notify-sub{color:rgba(224,220,205,.56);font-size:13px;line-height:1.8;margin-bottom:18px;}
.notify-actions{display:flex;gap:10px;justify-content:flex-start;flex-wrap:wrap;}
.notify-actions button{border:1px solid rgba(124,116,84,.30);background:transparent;color:rgba(224,220,205,.72);border-radius:999px;padding:10px 16px;font-family:inherit;cursor:pointer;}
.notify-actions .primary{border:0;background:var(--gold);color:var(--offwhite);}
body.light-mode .order-dialog{background:linear-gradient(180deg,rgba(255,255,255,.76),rgba(255,255,255,.44));border-color:rgba(35,35,35,.16);box-shadow:0 24px 70px rgba(35,35,35,.13);}
body.light-mode .order-title{color:var(--dark);}
body.light-mode .order-desc,body.light-mode .order-note{color:rgba(35,35,35,.58);}
body.light-mode .order-info .order-desc{color:rgba(35,35,35,.68);}
body.light-mode .order-pill{color:rgba(35,35,35,.62);border-color:rgba(35,35,35,.18);}
body.light-mode .order-image{background:linear-gradient(135deg,rgba(255,255,255,.82),rgba(242,239,231,.58));border-color:rgba(35,35,35,.14);}
body.light-mode .order-image::after{background:linear-gradient(180deg,rgba(255,255,255,.22),transparent 30%,rgba(35,35,35,.035));}
body.light-mode .order-form input,body.light-mode .order-form textarea,body.light-mode .order-form select{background:rgba(255,255,255,.62);color:var(--dark);border-color:rgba(35,35,35,.18);}
body.light-mode .order-option-pill{background:rgba(255,255,255,.55);border-color:rgba(35,35,35,.16);color:rgba(35,35,35,.66);}
body.light-mode .order-option-pill:hover{border-color:rgba(124,116,84,.54);color:var(--dark);}
body.light-mode .order-option-pill.active{background:rgba(124,116,84,.92);border-color:rgba(124,116,84,.26);color:#fff;}
body.light-mode .product-config{background:rgba(255,255,255,.48);border-color:rgba(35,35,35,.14);}
body.light-mode .product-config-title{color:var(--dark);}
body.light-mode .product-config-hint{color:rgba(35,35,35,.56);}
body.light-mode .order-shipping{background:rgba(255,255,255,.48);border-color:rgba(35,35,35,.14);}
body.light-mode .cart-dialog{background:linear-gradient(180deg,rgba(255,255,255,.92),rgba(249,248,247,.88));border-color:rgba(35,35,35,.16);box-shadow:0 24px 70px rgba(35,35,35,.13);}
body.light-mode .cart-title,body.light-mode .cart-item strong,body.light-mode .cart-total{color:var(--dark);}
body.light-mode .cart-sub,body.light-mode .cart-item small,body.light-mode .cart-empty{color:rgba(35,35,35,.58);}
body.light-mode .cart-item{background:rgba(255,255,255,.55);border-color:rgba(35,35,35,.13);}
body.light-mode .notify-dialog{background:linear-gradient(180deg,rgba(255,255,255,.94),rgba(249,248,247,.92));border-color:rgba(35,35,35,.16);box-shadow:0 24px 70px rgba(35,35,35,.13);}
body.light-mode .notify-title{color:var(--dark);}
body.light-mode .notify-sub{color:rgba(35,35,35,.62);}
body.light-mode .notify-actions button{color:rgba(35,35,35,.7);border-color:rgba(35,35,35,.22);}

/* THEME BALANCE */
body.light-mode .hero{background:linear-gradient(180deg,#FFFFFF 0%,#F9F8F7 58%,#F5F3EE 100%);}
body.light-mode .hero-pattern{opacity:.035;background-image:radial-gradient(circle,rgba(35,35,35,.34) 1px,transparent 1px);}
body.light-mode .hero-line-v{background:rgba(35,35,35,.22);}
body.light-mode .hero-line-h{background:rgba(35,35,35,.15);}
body.light-mode .hero-circle{border-color:rgba(35,35,35,.18);}
body.light-mode .hero-circle2{border-color:rgba(35,35,35,.13);}
body.light-mode .card-panel{background:rgba(255,255,255,.72);border-color:rgba(35,35,35,.24);box-shadow:0 28px 55px rgba(35,35,35,.10);}
body.light-mode .card-panel::before{background:repeating-linear-gradient(45deg,rgba(35,35,35,.045) 0,rgba(35,35,35,.045) 1px,transparent 1px,transparent 10px);}
body.light-mode .card-depth-layer{border-color:rgba(35,35,35,.10);}
body.light-mode .card-tabs{border-color:rgba(35,35,35,.22);}
body.light-mode .card-tab{color:rgba(35,35,35,.48);}
body.light-mode .card-tab:hover:not(.active){color:var(--gold);}
body.light-mode .nfc-card-name{color:var(--dark);}
body.light-mode .nfc-card-sub,body.light-mode .cube-label{color:rgba(35,35,35,.42);}
body.light-mode .about-question,body.light-mode .services-question,body.light-mode .section-title.on-dark,body.light-mode .pillar-title{color:var(--dark);}
body.light-mode .about-question,body.light-mode .services-question{border-bottom-color:rgba(35,35,35,.20);}
body.light-mode .about-box-main{background:rgba(255,255,255,.74);border-color:rgba(35,35,35,.24);box-shadow:0 28px 55px rgba(35,35,35,.09);}
body.light-mode .about-founded{color:rgba(35,35,35,.34);}
body.light-mode .about-body{color:rgba(35,35,35,.62);}
body.light-mode .pillar{background:#FFFFFF;border-color:rgba(35,35,35,.18);}
body.light-mode .pillar:hover,body.light-mode .pillar.active{background:#F9F8F7;border-color:rgba(35,35,35,.35);}
body.light-mode .pillar:hover .pillar-title,body.light-mode .pillar.active .pillar-title{color:var(--dark);}
body.light-mode .pillar-sub{color:rgba(35,35,35,.55);}
body.light-mode .pillar:hover .pillar-sub,body.light-mode .pillar.active .pillar-sub{color:rgba(35,35,35,.58);}
body.light-mode .about{background:linear-gradient(180deg,#F5F3EE 0%,#FFFFFF 46%,#F4F1EA 100%);}
body.light-mode .services{background:linear-gradient(180deg,#F4F1EA 0%,#FFFFFF 42%,#F9F8F7 100%);}
body.light-mode .switch-panel{background:#FFFFFF;border-color:rgba(35,35,35,.22);backdrop-filter:none;box-shadow:0 24px 50px rgba(35,35,35,.055);}
body.light-mode .switch-panel.active{border-color:rgba(35,35,35,.28);}
body.light-mode .switch-gate{background:#F9F8F7;color:var(--dark);}
body.light-mode .gate-action{color:rgba(35,35,35,.48);}
body.light-mode .switch-heading{border-bottom-color:rgba(35,35,35,.18);}
body.light-mode .switch-title{color:var(--dark);}
body.light-mode .service-item{background:#FFFFFF;border-color:rgba(35,35,35,.18);box-shadow:none;}
body.light-mode .si-title{color:var(--dark);}
body.light-mode .si-body{color:rgba(35,35,35,.56);}
body.light-mode .si-price{color:var(--dark)}body.light-mode .si-old-price{color:rgba(35,35,35,.36)}
body.light-mode .si-status-orb{color:#171613;text-shadow:0 0 8px rgba(255,255,255,.95),0 0 22px rgba(124,116,84,.20);filter:none}
body.light-mode .si-status-orb.sale{border-color:rgba(35,35,35,.58);background:linear-gradient(135deg,rgba(35,35,35,.08),rgba(124,116,84,.08));color:#171613;text-shadow:none;box-shadow:inset 0 0 0 1px rgba(255,255,255,.45),0 12px 22px rgba(35,35,35,.10);filter:none}
body.light-mode .si-status-orb.soldout{color:#c71919;text-shadow:none}
body.light-mode .service-item:hover{background:#F9F8F7;border-color:rgba(35,35,35,.35);}
body.light-mode .service-item:hover .si-title{color:var(--dark);}
body.light-mode .service-item:hover .si-body{color:rgba(35,35,35,.58);}
body.light-mode .service-item:hover .si-num{color:rgba(35,35,35,.42);}
body.light-mode .footer-brand-logo,body.light-mode .nav-brand-logo{filter:none;}
body:not(.light-mode) .services-question{color:var(--beige);}
body:not(.light-mode) .service-item:hover{background:#181818;border-color:rgba(124,116,84,.42);}
body.lang-en .switch-gate{text-align:left;}
body.lang-en .gate-title{letter-spacing:1px;}
body.lang-en .hero-title{letter-spacing:-1.2px;}
body.lang-en .hero-sub,body.lang-en .about-body,body.lang-en .si-body,body.lang-en .footer-slogan{line-height:1.75;}
body.lang-en .nav-links a,body.lang-en .btn-primary,body.lang-en .btn-ghost,body.lang-en .nav-login{letter-spacing:2px;}
body.lang-en .card-tab{font-family:var(--font-en);font-size:9.5px;letter-spacing:1px;text-transform:uppercase;}
body.lang-en .services-question span{margin:0 10px;}
body.lang-ar .transform-sub{font-size:12px;letter-spacing:.8px;text-transform:none;}

/* FINAL TRANSFORMATION */
.final-reveal{height:76vh;min-height:600px;max-height:840px;background:#030303;position:relative;overflow:hidden;isolation:isolate;display:grid;place-items:center;}
.final-reveal::before{content:'';position:absolute;inset:0;background:radial-gradient(circle at 50% 50%,rgba(124,116,84,.055),transparent 52%);opacity:.35;transition:opacity 1s;}
.final-reveal::after{content:'';position:absolute;left:50%;top:50%;width:min(72vw,840px);aspect-ratio:1;border:1px solid rgba(124,116,84,.06);border-radius:50%;transform:translate(-50%,-50%) scale(.72);opacity:.3;transition:transform 1.1s cubic-bezier(.16,1,.3,1),opacity .8s;}
.final-stage{position:relative;width:min(88vw,1000px);height:500px;display:grid;place-items:center;z-index:2;}
.transform-mark{position:relative;width:270px;aspect-ratio:1094/1070;filter:drop-shadow(0 0 0 transparent);transition:filter 1s,transform 1s cubic-bezier(.16,1,.3,1);}
.mark-piece{position:absolute;inset:0;width:100%;height:100%;object-fit:contain;opacity:.2;transition:transform 1s cubic-bezier(.16,1,.3,1),opacity .8s,filter .8s;}
.mark-piece-1{transform:translateX(-90px) rotate(-20deg);}
.mark-piece-2{transform:translateY(-90px) rotate(-8deg);}
.mark-piece-3{transform:translateY(90px) rotate(8deg);}
.mark-piece-4{transform:translateX(90px) rotate(20deg);}
.transform-line{position:absolute;left:50%;top:50%;width:min(84vw,900px);height:1px;background:linear-gradient(90deg,transparent,rgba(124,116,84,.32),transparent);transform:translate(-50%,-50%) scaleX(.08);opacity:.25;transition:transform 1.2s cubic-bezier(.16,1,.3,1),opacity .8s;}
.transform-copy{position:absolute;left:0;right:0;bottom:-6px;text-align:center;opacity:.12;transform:translateY(24px);transition:opacity .8s .2s,transform .9s .2s;}
.transform-title{font-size:clamp(46px,6vw,88px);font-weight:600;color:var(--beige);line-height:1.15;letter-spacing:-1px;}
.transform-sub{font-size:9px;letter-spacing:5px;color:var(--gold);margin-top:18px;text-transform:uppercase;}
.transform-hint{position:absolute;top:50%;right:50%;transform:translate(50%,-50%);font-size:9px;letter-spacing:4px;color:rgba(224,220,205,.2);white-space:nowrap;transition:opacity .35s;z-index:4;}
.final-reveal:hover::before,.final-reveal.active::before{opacity:1;}
.final-reveal:hover::after,.final-reveal.active::after{transform:translate(-50%,-50%) scale(1);opacity:1;}
.final-reveal:hover .transform-mark,.final-reveal.active .transform-mark{filter:drop-shadow(0 0 28px rgba(124,116,84,.3));transform:translateY(-82px) scale(1.08);}
.final-reveal:hover .mark-piece,.final-reveal.active .mark-piece{opacity:1;filter:drop-shadow(0 0 14px rgba(124,116,84,.16));transform:none;}
.final-reveal:hover .transform-line,.final-reveal.active .transform-line{transform:translate(-50%,-50%) scaleX(1);opacity:1;}
.final-reveal:hover .transform-copy,.final-reveal.active .transform-copy{opacity:1;transform:none;}
.final-reveal:hover .transform-hint,.final-reveal.active .transform-hint{opacity:0;}

/* FOOTER */
footer{background:var(--black);padding:78px 48px 30px;border-top:1px solid rgba(124,116,84,0.12);}
.footer-inner{max-width:1200px;margin:0 auto;}
.footer-grid{display:grid;grid-template-columns:1.4fr .8fr 1fr 1.15fr;gap:54px;padding-bottom:58px;}
.footer-brand-logo{height:82px;max-width:150px;opacity:.75;margin-bottom:22px;}
.footer-slogan{font-size:14px;color:rgba(224,220,205,.55);line-height:1.9;max-width:250px;}
.footer-col-title{font-size:10px;letter-spacing:4px;color:var(--gold);margin-bottom:24px;}
.footer-list{display:flex;flex-direction:column;gap:14px;list-style:none;}
.footer-list a,.footer-list span{font-size:12px;color:rgba(224,220,205,.58);line-height:1.7;transition:color .2s;}
.footer-list a:hover{color:var(--beige);}
.footer-social{display:flex;gap:9px;flex-wrap:wrap;margin-top:24px;}
.footer-social a{min-width:38px;height:38px;padding:0 12px;border:1px solid rgba(124,116,84,.24);display:flex;align-items:center;justify-content:center;font-size:9px;letter-spacing:1px;color:rgba(224,220,205,.45);transition:all .25s;}
.footer-social a:hover{border-color:var(--gold);color:var(--gold);transform:translateY(-3px);}
.footer-legal{padding-top:24px;border-top:1px solid rgba(124,116,84,.14);display:flex;align-items:center;justify-content:space-between;gap:24px;flex-wrap:wrap;}
.footer-copy{font-size:10px;color:rgba(224,220,205,.46);letter-spacing:1px;}
.footer-legal-links{display:flex;gap:24px;flex-wrap:wrap;}
.footer-legal-links a{font-size:10px;color:rgba(224,220,205,.5);transition:color .2s;}
.footer-legal-links a:hover{color:var(--gold);}

/* MOBILE MENU */
.mobile-menu{display:none;position:fixed;top:64px;left:0;right:0;background:rgba(20,20,20,0.98);backdrop-filter:blur(12px);border-bottom:1px solid rgba(124,116,84,0.2);padding:24px 32px;z-index:99;flex-direction:column;gap:20px;}
.mobile-menu.open{display:flex;}
.mobile-menu a{font-size:13px;letter-spacing:3px;color:rgba(224,220,205,0.6);text-transform:uppercase;}
.mobile-menu a:hover{color:var(--gold);}
.mobile-bottom{display:flex;gap:12px;margin-top:8px;align-items:center;}
.mobile-lang{display:none;align-items:center;justify-content:center;min-height:34px;}

/* RESPONSIVE */
@media(max-width:900px){
  nav{padding:0 24px;}
  .nav-links{display:none;}
  .hamburger{display:flex;}
  .hero{padding:0 24px;min-height:100svh;}
  .hero-inner{grid-template-columns:1fr;gap:40px;padding-top:100px;padding-bottom:64px;}
  .hero-title{font-size:36px;}
  .hero-circle,.hero-circle2,.hero-line-v{display:none;}
  .hero-visual{justify-content:center;}
  .card-scene{width:280px;padding:20px;}
  .card-panel{padding:28px 24px 32px;min-height:360px;}
  .card-tabs{margin-bottom:30px;}
  .nfc-card-img{width:220px;height:135px;border-radius:12px;}
  .about{padding:80px 24px;}
  .about-grid{grid-template-columns:1fr;gap:32px;}
  .about-question{grid-column:auto;}
  .about-box-main{aspect-ratio:auto;padding:32px;min-height:200px;}
  .about-brand-logo{width:58%;max-height:190px;}
  .about-question,.services-question{font-size:42px;}
  .about-question span{font-size:58px;}
  .services-question span{font-size:42px;}
  .about-pillars{display:grid;grid-template-columns:1fr 1fr;height:auto;}
  .pillar,.pillar:hover,.pillar.active{min-height:130px;flex:auto;}
  .pillar-sub{min-width:0;}
  .about-accent,.about-accent2{display:none;}
  .services{padding:80px 24px;}
  .services-switcher,.services-switcher[data-active="products"]{display:flex;flex-direction:column;min-height:0;}
  .services-switcher[data-active="products"] .switch-panel[data-panel="products"],
  .services-switcher[data-active="products"] .switch-panel[data-panel="products"] .switch-content{min-height:0;}
  .switch-panel:not(.active){height:110px;min-height:110px;}
  .switch-panel.active{min-height:0;}
  .switch-gate{position:absolute;flex-direction:row;align-items:center;padding:28px;}
  .gate-title{font-size:24px;writing-mode:horizontal-tb;transform:none;}
  .switch-content{padding:34px 24px;}
  .switch-panel.active .switch-content{min-height:0;display:block;}
  .switch-title{font-size:28px;}
  .items-grid{grid-template-columns:1fr;}
  .switch-panel.active .items-grid{display:grid;grid-auto-rows:auto;}
  .service-item{min-height:auto;}
  .switch-panel.active .service-item{min-height:auto;}
  .order-form{grid-template-columns:1fr;}
  .order-preview{grid-template-columns:1fr;}
  .order-shipping{grid-template-columns:1fr;}
  .order-dialog{width:min(460px,100%);padding:10px;}
  .order-title{font-size:15px;padding:11px 8px 12px 44px;}
  .order-image{height:min(50vh,330px);min-height:250px;}
  .order-modal[data-order-kind="service"] .order-image img{max-height:140px;}
  .final-reveal{height:64vh;min-height:470px;}
  .final-stage{height:430px;}
  .transform-mark{transform:scale(.85);}
  .final-reveal:hover .transform-mark,.final-reveal.active .transform-mark{transform:translateY(-70px) scale(.92);}
  footer{padding:60px 24px 28px;}
  .footer-grid{grid-template-columns:1fr 1fr;gap:42px 28px;}
}
@media(max-width:480px){
  .hero-title{font-size:30px;}
  .nav-right > .nav-lang{display:none;}
  .mobile-menu .nav-lang{display:inline-flex;}
  .section-title{font-size:26px;}
  .transform-title{font-size:42px;}
  .transform-hint{letter-spacing:2px;}
  .footer-grid{grid-template-columns:1fr;}
  .hero-actions{flex-direction:column;width:100%;}
  .btn-primary,.btn-ghost{text-align:center;width:100%;padding:14px 24px;}
}
</style>
<link rel="icon" href="artee-logo.png">
<link rel="canonical" href="https://artee.com.sa/">
<meta name="description" content="نحوّل الخيال إلى واقع عبر خدمات ومنتجات إبداعية من ARTEE.">
<meta property="og:type" content="website">
<meta property="og:title" content="ARTEE">
<meta property="og:description" content="نحوّل الخيال إلى واقع عبر خدمات ومنتجات إبداعية من ARTEE.">
<meta property="og:image" content="https://artee.com.sa/artee-logo.png">
<meta property="og:url" content="https://artee.com.sa/">
<meta name="twitter:card" content="summary_large_image">
</head>
<body>
<div class="site-announcement" id="siteAnnouncement" hidden></div>

<!-- NAV -->
<nav id="main-nav">
  <div class="nav-inner">
    <div class="logo-mark">
      <img class="brand-logo nav-brand-logo" src="artee-logo.png" alt="ARTEE"/>
    </div>
    <ul class="nav-links">
      <li><a href="#about">من نحن</a></li>
      <li><a href="#services">خدماتنا</a></li>
      <li><a href="#products">منتجاتنا</a></li>
      <li><a href="contact.html">تواصل</a></li>
    </ul>
    <div class="nav-right">
      <span class="nav-lang" id="langToggle" data-lang-toggle>EN</span>
      <a class="nav-notify" id="navNotify" href="account.html#notifications" aria-label="الإشعارات">
        <svg viewBox="0 0 24 24"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9"/><path d="M10 21h4"/></svg>
        <span class="nav-notify-badge" id="navNotifyBadge"></span>
      </a>
      <button class="nav-cart" id="navCart" type="button" aria-label="السلة">
        <svg viewBox="0 0 24 24"><path d="M6 6h15l-2 9H8L6 6Z"/><path d="M6 6 5 3H2"/><circle cx="9" cy="20" r="1.5"/><circle cx="18" cy="20" r="1.5"/></svg>
        <span class="nav-cart-badge" id="navCartBadge" hidden>0</span>
      </button>
      <button class="nav-mode" id="modeToggle" aria-label="تبديل الوضع">
        <svg id="iconMoon" viewBox="0 0 24 24" style="display:none"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
        <svg id="iconSun" viewBox="0 0 24 24"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
      </button>
      <a href="login.html" class="nav-login">تسجيل دخول</a>
      <div class="hamburger" id="hamburger"><span></span><span></span><span></span></div>
    </div>
  </div>
</nav>

<div class="account-menu" id="accountMenu" aria-hidden="true">
  <a href="account.html#profile" data-account-option="profile">بيانات العميل</a>
  <a href="account.html#orders" data-account-option="orders">طلباتي</a>
  <a href="account.html#tickets" data-account-option="tickets">التذاكر والتواصل</a>
  <a href="#" data-account-logout>تسجيل الخروج</a>
</div>

<!-- Mobile Menu -->
<div class="mobile-menu" id="mobileMenu">
  <a href="#about">من نحن</a>
  <a href="#services">خدماتنا</a>
  <a href="#products">منتجاتنا</a>
  <a href="contact.html">تواصل</a>
  <div class="mobile-bottom">
    <a href="login.html" class="nav-login">تسجيل دخول</a>
    <button class="nav-lang mobile-lang" type="button" data-lang-toggle>EN</button>
  </div>
</div>

<!-- HERO -->
<section class="hero" id="hero">
  <div class="hero-pattern" id="heroPattern"></div>
  <div class="hero-line-v"></div>
  <div class="hero-line-h"></div>
  <div class="hero-circle" id="hCircle1"></div>
  <div class="hero-circle2" id="hCircle2"></div>
  <div class="hero-inner">
    <div>
      <h1 class="hero-title">نصنع<br/>هويات<br/><span>استثنائية</span></h1>
      <p class="hero-sub">منشأة إبداعية سعودية متخصصة في تصميم الجرافيك ثلاثي الأبعاد وبطاقات الأعمال الذكية — نحوّل أفكارك إلى تجارب بصرية لا تُنسى.</p>
      <div class="hero-actions">
        <a href="login.html?mode=register&next=project" class="btn-primary">ابدأ معنا</a>
        <a href="#services" class="btn-ghost">اكتشف خدماتنا ومنتجاتنا</a>
      </div>
    </div>
    <div class="hero-visual">
      <div class="card-scene" id="cardScene">
        <div class="card-glow"></div>
        <div class="card-wrapper" id="cardWrapper">
          <div class="card-panel">
            <div class="card-depth-layer"></div>
            <div class="card-tabs">
              <button class="card-tab active" type="button" data-card-tab="nfc">بطاقات أعمال ذكية</button>
              <button class="card-tab" type="button" data-card-tab="3d">تصميم ثلاثي الأبعاد</button>
            </div>
            <!-- NFC -->
            <div class="display-nfc active" id="dispNfc">
              <div class="nfc-card-img">
                <picture>
                  <source srcset="artee-business-card-optimized.webp" type="image/webp"/>
                  <img src="artee-business-card-optimized.png" width="640" height="407" alt="بطاقة أعمال ARTEE" decoding="async"/>
                </picture>
              </div>
              <div class="nfc-card-text">
                <div class="nfc-card-name">بطاقة أعمال ذكية</div>
                <div class="nfc-card-sub">بطاقة رقمية ذكية لمشاركة بياناتك وروابطك بلمسة واحدة.</div>
              </div>
            </div>
            <!-- 3D -->
            <div class="display-3d" id="disp3d">
              <div class="cube-scene">
                <div class="cube" aria-label="مكعب أحجية ثلاثي الأبعاد تفاعلي">
                  <div class="cubie" style="--tx:-35px;--ty:-35px;--tz:35px"><span class="c-side c-front"></span><span class="c-side c-back"></span><span class="c-side c-right"></span><span class="c-side c-left"></span><span class="c-side c-top"></span><span class="c-side c-bottom"></span></div>
                  <div class="cubie" style="--tx:35px;--ty:-35px;--tz:35px"><span class="c-side c-front"></span><span class="c-side c-back"></span><span class="c-side c-right"></span><span class="c-side c-left"></span><span class="c-side c-top"></span><span class="c-side c-bottom"></span></div>
                  <div class="cubie" style="--tx:-35px;--ty:35px;--tz:35px"><span class="c-side c-front"></span><span class="c-side c-back"></span><span class="c-side c-right"></span><span class="c-side c-left"></span><span class="c-side c-top"></span><span class="c-side c-bottom"></span></div>
                  <div class="cubie" style="--tx:35px;--ty:35px;--tz:35px"><span class="c-side c-front"></span><span class="c-side c-back"></span><span class="c-side c-right"></span><span class="c-side c-left"></span><span class="c-side c-top"></span><span class="c-side c-bottom"></span></div>
                  <div class="cubie" style="--tx:-35px;--ty:-35px;--tz:-35px"><span class="c-side c-front"></span><span class="c-side c-back"></span><span class="c-side c-right"></span><span class="c-side c-left"></span><span class="c-side c-top"></span><span class="c-side c-bottom"></span></div>
                  <div class="cubie" style="--tx:35px;--ty:-35px;--tz:-35px"><span class="c-side c-front"></span><span class="c-side c-back"></span><span class="c-side c-right"></span><span class="c-side c-left"></span><span class="c-side c-top"></span><span class="c-side c-bottom"></span></div>
                  <div class="cubie" style="--tx:-35px;--ty:35px;--tz:-35px"><span class="c-side c-front"></span><span class="c-side c-back"></span><span class="c-side c-right"></span><span class="c-side c-left"></span><span class="c-side c-top"></span><span class="c-side c-bottom"></span></div>
                  <div class="cubie" style="--tx:35px;--ty:35px;--tz:-35px"><span class="c-side c-front"></span><span class="c-side c-back"></span><span class="c-side c-right"></span><span class="c-side c-left"></span><span class="c-side c-top"></span><span class="c-side c-bottom"></span></div>
                </div>
              </div>
              <div class="nfc-card-text" style="margin-top:16px;">
                <div class="nfc-card-name">تصميم ثلاثي الأبعاد</div>
                <div class="nfc-card-sub">نماذج ومشاهد ثلاثية الأبعاد تعرض فكرتك بواقعية ووضوح.</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="hero-scroll">
    <div class="scroll-line"></div>
    <span>مرر للأسفل</span>
  </div>
</section>

<!-- ABOUT -->
<section class="about" id="about">
  <div class="about-grid">
    <h2 class="about-question">من نحن <span>؟</span></h2>
    <div class="about-visual">
      <div class="about-box-main">
        <p class="section-label">Smart KAF · ARTEE</p>
        <img class="brand-logo about-brand-logo" src="artee-logo.png" alt="شعار ARTEE"/>
        <p class="about-founded">تأسست · ٢٠٢٤</p>
      </div>
      <div class="about-accent"></div>
      <div class="about-accent2"></div>
    </div>
    <div class="about-content">
      <h2 class="section-title on-dark">إبداع سعودي<br/><span>بمعايير عالمية</span></h2>
      <div class="section-rule"></div>
      <p class="about-body">ARTEE منشأة إبداعية تقنية سعودية تابعة لـ Smart KAF، تجمع بين دقة التصميم وذكاء التقنية. نخدم رواد الأعمال والمنشآت والمؤسسات الباحثة عن هوية بصرية متميزة وأدوات تواصل احترافية.</p>
      <div class="about-pillars">
        <div class="pillar" tabindex="0"><p class="pillar-title">رؤيتنا</p><p class="pillar-sub">أن نكون المرجع الإبداعي الأول للتقنية والتصميم في المملكة.</p></div>
        <div class="pillar" tabindex="0"><p class="pillar-title">أسلوبنا</p><p class="pillar-sub">دقة معمارية، مساحة نظيفة، وهوية تعكس قيمة عميلنا الحقيقية.</p></div>
        <div class="pillar" tabindex="0"><p class="pillar-title">جودتنا</p><p class="pillar-sub">كل عنصر له هدف — لا مساحة لأي تفصيلة عشوائية.</p></div>
        <div class="pillar" tabindex="0"><p class="pillar-title">عملاؤنا</p><p class="pillar-sub">رواد أعمال، مؤسسات، وشركات تتطلع للتميز البصري.</p></div>
      </div>
    </div>
  </div>
</section>

<!-- SERVICES & PRODUCTS -->
<section class="services" id="services">
  <span class="section-anchor" id="products"></span>
  <div class="services-inner">
    <div class="services-header">
      <h2 class="services-question">خدماتنا <span>&</span> منتجاتنا</h2>
    </div>
    <div class="services-switcher" data-active="services">
      <section class="switch-panel active" data-panel="services">
        <button class="switch-gate" type="button" aria-label="عرض الخدمات">
          <span class="gate-num">01 · 04</span><strong class="gate-title">الخدمات</strong><span class="gate-action">استكشف ←</span>
        </button>
        <div class="switch-content">
          <div class="switch-heading"><h3 class="switch-title">الخدمات</h3><span class="switch-count">04 خدمات إبداعية</span></div>
          <div class="items-grid">
            <article class="service-item"><div class="si-icon"><svg viewBox="0 0 24 24"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/></svg></div><p class="si-num">01</p><h3 class="si-title">تصميم جرافيكي</h3><p class="si-body">تصاميم إبداعية تمنح علامتك حضورًا احترافيًا ومميزًا.</p></article>
            <article class="service-item"><div class="si-icon"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8"/><path d="M4 12h16M12 4v16"/></svg></div><p class="si-num">02</p><h3 class="si-title">تصميم ثلاثي الأبعاد</h3><p class="si-body">مشاهد وعناصر بصرية تحول أفكارك إلى تجربة ملموسة.</p></article>
            <article class="service-item"><div class="si-icon"><svg viewBox="0 0 24 24"><path d="M4 18L18 4M7 4h11v11"/></svg></div><p class="si-num">03</p><h3 class="si-title">الهوية البصرية</h3><p class="si-body">نظام بصري متكامل يعكس شخصية مشروعك وقيمته.</p></article>
            <article class="service-item"><div class="si-icon"><svg viewBox="0 0 24 24"><path d="M3 12h18M12 3v18"/><circle cx="12" cy="12" r="8"/></svg></div><p class="si-num">04</p><h3 class="si-title">موشن جرافيك</h3><p class="si-body">حركة مدروسة تجعل رسالتك أكثر وضوحًا وتأثيرًا.</p></article>
          </div>
        </div>
      </section>
      <section class="switch-panel" data-panel="products">
        <button class="switch-gate" type="button" aria-label="عرض المنتجات">
          <span class="gate-num">02 · 03</span><strong class="gate-title">المنتجات</strong><span class="gate-action">استكشف ←</span>
        </button>
        <div class="switch-content">
          <div class="switch-heading"><h3 class="switch-title">المنتجات</h3><span class="switch-count">03 منتجات ذكية</span></div>
          <div class="items-grid">
            <article class="service-item"><div class="si-icon"><svg viewBox="0 0 24 24"><rect x="2" y="5" width="20" height="14" rx="2"/><path d="M16 12a4 4 0 0 1-8 0"/></svg></div><p class="si-num">01</p><h3 class="si-title">بطاقات أعمال ذكية</h3><p class="si-body">بطاقات فاخرة تسهّل مشاركة معلوماتك بلمسة واحدة.</p></article>
            <article class="service-item"><div class="si-icon"><svg viewBox="0 0 24 24"><rect x="5" y="2" width="14" height="20" rx="2"/><path d="M9 18h6"/></svg></div><p class="si-num">02</p><h3 class="si-title">الملف الرقمي</h3><p class="si-body">صفحة تعريفية ذكية تجمع هويتك وروابطك في مكان واحد.</p></article>
            <article class="service-item"><div class="si-icon"><svg viewBox="0 0 24 24"><path d="M4 4h16v16H4zM8 8h3v3H8zM14 8h2M8 14h2M14 14h2v2"/></svg></div><p class="si-num">03</p><h3 class="si-title">حلول QR مخصصة</h3><p class="si-body">تجارب تواصل سريعة ومصممة لتناسب علامتك التجارية.</p></article>
          </div>
        </div>
      </section>
    </div>
  </div>
</section>

<div class="order-modal" id="orderModal" aria-hidden="true">
  <div class="order-dialog" role="dialog" aria-modal="true" aria-labelledby="orderTitle">
    <button class="order-close" type="button" id="orderClose" aria-label="إغلاق">×</button>
    <p class="order-kicker">Project Request</p>
    <h2 class="order-title" id="orderTitle">طلب خدمة</h2>
    <p class="order-desc" id="orderDesc">اكتب لنا فكرة مختصرة، وسنرتب لك الخطوة التالية.</p>
    <div class="order-preview">
      <div class="order-image" id="orderImage"><span>ARTEE</span><img id="orderImageSrc" alt=""/></div>
      <div class="order-info">
        <p class="order-desc" id="orderLongDesc">تفاصيل العنصر المختار تظهر هنا.</p>
        <div class="order-meta" id="orderMeta"></div>
        <div class="order-price" id="orderPrice"></div>
      </div>
    </div>
    <form class="order-form" id="orderForm">
      <input id="orderService" type="hidden"/>
      <input id="orderType" type="hidden"/>
      <label class="order-field-wide" id="orderOptionWrap">خيارات المنتج
        <select id="orderOption"></select>
        <div class="order-option-groups" id="orderOptionGroups"></div>
        <div class="order-options" id="orderOptions" hidden></div>
      </label>
      <label class="order-field-wide order-hidden" id="orderQuantityWrap">الكمية
        <input id="orderQuantity" type="number" min="1" max="99" step="1" value="1" inputmode="numeric"/>
      </label>
      <div class="product-config order-field-wide order-hidden" id="productConfigWrap">
        <p class="product-config-title">محتوى البطاقة الذكية</p>
        <p class="product-config-hint">اختر كيف تريد تجهيز المحتوى الداخلي للبطاقة.</p>
        <select id="productContentMode"></select>
        <div class="order-options" id="productContentModes"></div>
        <label class="order-field-wide" id="productContentBriefWrap">تفاصيل المحتوى
          <textarea id="productContentBrief" placeholder="اكتب الروابط، النصوص، الهوية، أو أي ملاحظات تساعدنا في تجهيز المحتوى..."></textarea>
        </label>
        <label class="order-field-wide order-hidden" id="productLinkWrap">رابط Linktree
          <input id="productLink" type="url" placeholder="https://linktr.ee/yourname"/>
        </label>
      </div>
      <label class="order-field-wide" id="orderMessageWrap">تفاصيل الطلب
        <textarea id="orderMessage" placeholder="اكتب وصفًا مختصرًا لما تريد تنفيذه..."></textarea>
      </label>
      <div class="order-shipping order-field-wide order-hidden" id="orderShippingWrap">
        <p class="order-shipping-title" id="orderShippingTitle">عنوان الشحن للمنتج</p>
        <p class="order-shipping-hint" id="orderShippingHint">راجع العنوان قبل الدفع، ويمكنك تعديله هنا.</p>
        <label>اسم المستلم
          <input id="shippingName" type="text" autocomplete="name" placeholder="مثال: محمد خالد"/>
        </label>
        <label>رقم الجوال
          <input id="shippingPhone" type="tel" autocomplete="tel" placeholder="05xxxxxxxx"/>
        </label>
        <label>المنطقة / الولاية
          <input id="shippingRegion" type="text" autocomplete="address-level1" placeholder="منطقة الرياض"/>
        </label>
        <label>المدينة
          <input id="shippingCity" type="text" autocomplete="address-level2" placeholder="الرياض"/>
        </label>
        <label>الحي / المنطقة
          <input id="shippingDistrict" type="text" autocomplete="address-level3" placeholder="العليا"/>
        </label>
        <label>الشارع
          <input id="shippingStreet" type="text" autocomplete="street-address" placeholder="طريق الملك فهد"/>
        </label>
        <label>رقم المبنى
          <input id="shippingBuilding" type="text" placeholder="3670"/>
        </label>
        <label>الرمز البريدي
          <input id="shippingPostal" type="text" autocomplete="postal-code" placeholder="12221"/>
        </label>
        <label>رمز العنوان المختصر
          <input id="shippingShortAddress" type="text" placeholder="RHOA3670"/>
        </label>
        <label class="full">تفاصيل إضافية
          <input id="shippingAddress" type="text" autocomplete="street-address" placeholder="أقرب معلم أو تعليمات وصول إضافية"/>
        </label>
        <label class="full">ملاحظات اختيارية
          <input id="shippingNotes" type="text" placeholder="وقت مناسب للتواصل أو تفاصيل إضافية"/>
        </label>
      </div>
      <label class="order-field-wide" id="orderAttachmentWrap">مرفقات داعمة
        <input id="orderAttachment" type="file" multiple accept=".jpg,.jpeg,.png,.webp,.pdf,.zip,image/jpeg,image/png,image/webp,application/pdf,application/zip,application/x-zip-compressed"/>
        <span class="order-help">مراجع تساعدنا نفهم الفكرة فقط: صور، PDF، أو ZIP/RAR. الحد الأقصى 4 ملفات، 25MB للملف، و75MB إجماليًا.</span>
      </label>
      <button class="order-submit" type="submit">إرسال الطلب</button>
      <p class="order-note" id="orderNote">هذا نموذج واجهة تجريبي. لاحقًا يمكن ربطه بقاعدة بيانات أو بريد رسمي.</p>
    </form>
  </div>
</div>

<div class="cart-modal" id="cartModal" aria-hidden="true">
  <div class="cart-dialog" role="dialog" aria-modal="true" aria-labelledby="cartTitle">
    <button class="cart-close" type="button" id="cartClose" aria-label="إغلاق">×</button>
    <h2 class="cart-title" id="cartTitle">السلة</h2>
    <p class="cart-sub" id="cartSub">راجع المنتجات قبل إتمام الدفع التجريبي.</p>
    <div class="cart-list" id="cartList"></div>
    <div class="cart-step" id="cartShippingStep" hidden>
      <div class="cart-step-grid">
        <label>اسم المستلم<input id="cartShippingName" type="text" autocomplete="name" placeholder="مثال: محمد خالد" required aria-describedby="cartShippingNote"/></label>
        <label>رقم الجوال<input id="cartShippingPhone" type="tel" autocomplete="tel" placeholder="05xxxxxxxx" required aria-describedby="cartShippingNote"/></label>
        <label>المنطقة / الولاية<input id="cartShippingRegion" type="text" autocomplete="address-level1" placeholder="منطقة الرياض" required aria-describedby="cartShippingNote"/></label>
        <label>المدينة<input id="cartShippingCity" type="text" autocomplete="address-level2" placeholder="الرياض" required aria-describedby="cartShippingNote"/></label>
        <label>الحي<input id="cartShippingDistrict" type="text" autocomplete="address-level3" placeholder="العليا" required aria-describedby="cartShippingNote"/></label>
        <label>الشارع<input id="cartShippingStreet" type="text" autocomplete="street-address" placeholder="طريق الملك فهد" required aria-describedby="cartShippingNote"/></label>
        <label>رقم المبنى<input id="cartShippingBuilding" type="text" placeholder="3670"/></label>
        <label>الرمز البريدي<input id="cartShippingPostal" type="text" autocomplete="postal-code" placeholder="12221"/></label>
        <label class="full">رمز العنوان المختصر<input id="cartShippingShortAddress" type="text" placeholder="RHOA3670"/></label>
        <label class="full">تفاصيل إضافية<input id="cartShippingAddress" type="text" placeholder="أقرب معلم أو تعليمات وصول إضافية"/></label>
        <label class="full">ملاحظات اختيارية<input id="cartShippingNotes" type="text" placeholder="وقت مناسب للتواصل أو تفاصيل إضافية"/></label>
      </div>
      <p class="cart-validation-note" id="cartShippingNote" role="alert" aria-live="polite"></p>
    </div>
    <div class="cart-step" id="cartPaymentStep" hidden>
      <div class="cart-payment-box" id="cartPaymentBox"></div>
    </div>
    <div class="cart-footer">
      <strong class="cart-total" id="cartTotal">0 SAR</strong>
      <button class="cart-checkout" type="button" id="cartCheckout">إتمام الدفع التجريبي</button>
    </div>
  </div>
</div>

<div class="cart-modal" id="notifyModal" aria-hidden="true">
  <div class="notify-dialog" role="dialog" aria-modal="true" aria-labelledby="notifyTitle">
    <button class="cart-close" type="button" id="notifyClose" aria-label="إغلاق">×</button>
    <h2 class="notify-title" id="notifyTitle">تنبيه التوفر</h2>
    <p class="notify-sub" id="notifySub">هل تريد أن نرسل لك تنبيهًا عند توفر هذا العنصر؟</p>
    <div class="notify-actions">
      <button class="primary" type="button" id="notifyConfirm">نعم، نبهني</button>
      <button type="button" id="notifyCancel">لا</button>
    </div>
  </div>
</div>

<!-- FINAL REVEAL -->
<section class="final-reveal" id="finalReveal">
  <div class="final-stage">
    <div class="transform-line"></div>
    <div class="transform-mark" aria-label="ARTEE">
      <img class="mark-piece mark-piece-1" src="artee-mark-piece-1.png" alt=""/>
      <img class="mark-piece mark-piece-2" src="artee-mark-piece-2.png" alt=""/>
      <img class="mark-piece mark-piece-3" src="artee-mark-piece-3.png" alt=""/>
      <img class="mark-piece mark-piece-4" src="artee-mark-piece-4.png" alt=""/>
    </div>
    <div class="transform-copy">
      <h2 class="transform-title">نحوّل الخيال إلى واقع</h2>
      <p class="transform-sub">من الخيال إلى واقع ملموس</p>
    </div>
    <p class="transform-hint">مرّر لتبدأ التحوّل</p>
  </div>
</section>

<!-- FOOTER -->
<footer>
  <div class="footer-inner">
    <div class="footer-grid">
      <div>
        <img class="brand-logo footer-brand-logo" src="artee-logo.png" alt="ARTEE"/>
        <p class="footer-slogan">شريكك الموثوق للحلول الابتكارية والخدمات المناسبة.</p>
        <div class="footer-social">
          <a href="https://www.instagram.com/artee.vrti/?hl=ar" target="_blank" rel="noopener">IG</a>
          <a href="https://x.com/ARTEEvrti?s=20" target="_blank" rel="noopener">X</a>
          <a href="https://www.linkedin.com/showcase/artee-vrti/?viewAsMember=true" target="_blank" rel="noopener">IN</a>
          <a href="https://wa.me/966557079096" target="_blank" rel="noopener">WA</a>
        </div>
      </div>
      <div>
        <h3 class="footer-col-title">روابط سريعة</h3>
        <ul class="footer-list">
          <li><a href="#hero">الرئيسية</a></li>
          <li><a href="#about">من نحن</a></li>
          <li><a href="#services">ماذا نقدم</a></li>
          <li><a href="contact.html">تواصل معنا</a></li>
        </ul>
      </div>
      <div>
        <h3 class="footer-col-title">ماذا نقدم</h3>
        <ul class="footer-list">
          <li><a href="#services">تصميم ثلاثي الأبعاد</a></li>
          <li><a href="#services">تصميم جرافيكي</a></li>
          <li><a href="#products">بطاقات أعمال ذكية</a></li>
          <li><a href="#products">حلول NFC ذكية</a></li>
        </ul>
      </div>
      <div>
        <h3 class="footer-col-title">معلومات التواصل</h3>
        <ul class="footer-list">
          <li><span>الرياض، المملكة العربية السعودية</span></li>
          <li><a href="tel:+966557079096">0557079096</a></li>
          <li><a href="mailto:info@artee.com.sa">info@artee.com.sa</a></li>
          <li><span>مؤسسة سمارت كاف</span></li>
          <li><span>الرقم الوطني الموحد: 7040340130</span></li>
          <li><span>الرقم المميز: 3122526599</span></li>
        </ul>
      </div>
    </div>
    <div class="footer-legal">
      <span class="footer-copy">© 2026 ARTEE · مؤسسة سمارت كاف · جميع الحقوق محفوظة</span>
      <div class="footer-legal-links">
        <a href="terms.html">الشروط والأحكام</a>
        <a href="privacy.html">سياسة الخصوصية</a>
      </div>
    </div>
  </div>
</footer>

<script>
const demoResetVersion='2026-06-24-empty-flow-2';
if(localStorage.getItem('arteeDemoResetVersion')!==demoResetVersion){
  ['arteeDemoRequests','arteeFreelancerOffers','arteeDemoOrders','arteeArchivedRequests','arteePendingOrder'].forEach(key=>localStorage.removeItem(key));
  localStorage.setItem('arteeDemoResetVersion',demoResetVersion);
}
/* Mode */
const modeBtn=document.getElementById('modeToggle'),iconMoon=document.getElementById('iconMoon'),iconSun=document.getElementById('iconSun');
let lightMode=localStorage.getItem('arteeTheme')==='light';
document.body.classList.toggle('light-mode',lightMode);
iconMoon.style.display=lightMode?'block':'none';
iconSun.style.display=lightMode?'none':'block';
modeBtn.addEventListener('click',()=>{
  lightMode=!lightMode;
  document.body.classList.toggle('light-mode',lightMode);
  iconMoon.style.display=lightMode?'block':'none';
  iconSun.style.display=lightMode?'none':'block';
  localStorage.setItem('arteeTheme',lightMode?'light':'dark');
  modeBtn.setAttribute('aria-label',lightMode?(isAr?'التبديل للوضع الداكن':'Switch to dark mode'):(isAr?'التبديل للوضع الفاتح':'Switch to light mode'));
});

/* Language */
const langButtons=document.querySelectorAll('[data-lang-toggle]');
let isAr=localStorage.getItem('arteeLang')!=='en';
const textMap={
  ar:{
    nav:['من نحن','خدماتنا','منتجاتنا','تواصل'],
    login:'تسجيل دخول',
    logout:'تسجيل الخروج',
    accountOptions:['بيانات العميل','طلباتي','التذاكر والتواصل'],
    heroTitle:'نصنع<br/>هويات<br/><span>استثنائية</span>',
    heroSub:'منشأة إبداعية سعودية متخصصة في تصميم الجرافيك ثلاثي الأبعاد وبطاقات الأعمال الذكية — نحوّل أفكارك إلى تجارب بصرية لا تُنسى.',
    start:'ابدأ معنا',
    discover:'اكتشف خدماتنا ومنتجاتنا',
    tabs:['بطاقات أعمال ذكية','تصميم ثلاثي الأبعاد'],
    cardName:'بطاقة أعمال ذكية',
    cardSub:'بطاقة رقمية ذكية لمشاركة بياناتك وروابطك بلمسة واحدة.',
    designName:'تصميم ثلاثي الأبعاد',
    designSub:'نماذج ومشاهد ثلاثية الأبعاد تعرض فكرتك بواقعية ووضوح.',
    scroll:'مرر للأسفل',
    aboutQuestion:'من نحن <span>؟</span>',
    founded:'تأسست · ٢٠٢٤',
    aboutTitle:'إبداع سعودي<br/><span>بمعايير عالمية</span>',
    aboutBody:'ARTEE منشأة إبداعية تقنية سعودية تابعة لـ Smart KAF، تجمع بين دقة التصميم وذكاء التقنية. نخدم رواد الأعمال والمنشآت والمؤسسات الباحثة عن هوية بصرية متميزة وأدوات تواصل احترافية.',
    pillars:[
      ['رؤيتنا','أن نكون المرجع الإبداعي الأول للتقنية والتصميم في المملكة.'],
      ['أسلوبنا','دقة معمارية، مساحة نظيفة، وهوية تعكس قيمة عميلنا الحقيقية.'],
      ['جودتنا','كل عنصر له هدف — لا مساحة لأي تفصيلة عشوائية.'],
      ['عملاؤنا','رواد أعمال، مؤسسات، وشركات تتطلع للتميز البصري.']
    ],
    servicesQuestion:'خدماتنا <span>&</span> منتجاتنا',
    gates:[
      {title:'الخدمات',action:'استكشف ←',count:'04 خدمات إبداعية',heading:'الخدمات'},
      {title:'المنتجات',action:'استكشف ←',count:'03 منتجات ذكية',heading:'المنتجات'}
    ],
    serviceItems:[
      ['تصميم جرافيكي','تصاميم إبداعية تمنح علامتك حضورًا احترافيًا ومميزًا.'],
      ['تصميم ثلاثي الأبعاد','مشاهد وعناصر بصرية تحول أفكارك إلى تجربة ملموسة.'],
      ['الهوية البصرية','نظام بصري متكامل يعكس شخصية مشروعك وقيمته.'],
      ['موشن جرافيك','حركة مدروسة تجعل رسالتك أكثر وضوحًا وتأثيرًا.'],
      ['بطاقات أعمال ذكية','بطاقات فاخرة تسهّل مشاركة معلوماتك بلمسة واحدة.'],
      ['الملف الرقمي','صفحة تعريفية ذكية تجمع هويتك وروابطك في مكان واحد.'],
      ['حلول QR مخصصة','تجارب تواصل سريعة ومصممة لتناسب علامتك التجارية.']
    ],
    finalTitle:'نحوّل الخيال إلى واقع',
    finalSub:'من الخيال إلى واقع ملموس',
    finalHint:'مرّر لتبدأ التحوّل',
    footerSlogan:'شريكك الموثوق للحلول الابتكارية والخدمات المناسبة.',
    footerCols:['روابط سريعة','ماذا نقدم','معلومات التواصل'],
    quick:['الرئيسية','من نحن','ماذا نقدم','تواصل معنا'],
    offers:['تصميم ثلاثي الأبعاد','تصميم جرافيكي','بطاقات أعمال ذكية','حلول NFC ذكية'],
    contact:['الرياض، المملكة العربية السعودية','مؤسسة سمارت كاف','الرقم الوطني الموحد: 7040340130','الرقم المميز: 3122526599'],
    copy:'© 2026 ARTEE · مؤسسة سمارت كاف · جميع الحقوق محفوظة',
    legal:['الشروط والأحكام','سياسة الخصوصية']
  },
  en:{
    nav:['About','Services','Products','Contact'],
    login:'Login',
    logout:'Log out',
    accountOptions:['Client Details','My Requests','Tickets & Messages'],
    heroTitle:'We Craft<br/>Exceptional<br/><span>Identities</span>',
    heroSub:'A Saudi creative-tech studio specialized in 3D graphic design and smart business cards — turning ideas into memorable visual experiences.',
    start:'Start With Us',
    discover:'Explore Services & Products',
    tabs:['Smart Business Cards','3D Design'],
    cardName:'Smart Business Card',
    cardSub:'A smart digital card for sharing your details and links in one tap.',
    designName:'3D Design',
    designSub:'3D scenes and assets that present your idea with clarity and depth.',
    scroll:'Scroll Down',
    aboutQuestion:'Who Are We <span>?</span>',
    founded:'Founded · 2024',
    aboutTitle:'Saudi Creativity<br/><span>Global Standards</span>',
    aboutBody:'ARTEE is a Saudi creative-tech studio under Smart KAF, combining design precision with intelligent technology. We serve entrepreneurs, organizations, and brands seeking distinctive visual identities and professional communication tools.',
    pillars:[
      ['Our Vision','To become the leading creative reference for technology and design in Saudi Arabia.'],
      ['Our Approach','Architectural precision, clean space, and an identity that reflects the true value of each client.'],
      ['Our Quality','Every element has a purpose — no room for random details.'],
      ['Our Clients','Entrepreneurs, organizations, and companies looking for visual distinction.']
    ],
    servicesQuestion:'Services <span>&</span> Products',
    gates:[
      {title:'Services',action:'Explore →',count:'04 Creative Services',heading:'Services'},
      {title:'Products',action:'Explore →',count:'03 Smart Products',heading:'Products'}
    ],
    serviceItems:[
      ['Graphic Design','Creative visuals that give your brand a professional and distinctive presence.'],
      ['3D Design','Scenes and visual assets that turn ideas into tangible experiences.'],
      ['Visual Identity','A complete visual system that reflects your project’s personality and value.'],
      ['Motion Graphics','Purposeful motion that makes your message clearer and more impactful.'],
      ['Smart Business Cards','Premium cards that make sharing your information effortless.'],
      ['Digital Profile','A smart profile page that gathers your identity and links in one place.'],
      ['Custom QR Solutions','Fast communication experiences designed to fit your brand.']
    ],
    finalTitle:'From Imagination to Impact',
    finalSub:'We turn ideas into visual reality',
    finalHint:'Hover to start the transformation',
    footerSlogan:'Your trusted partner for innovative solutions and fitting creative services.',
    footerCols:['Quick Links','What We Offer','Contact Info'],
    quick:['Home','About','What We Offer','Contact Us'],
    offers:['3D Design','Graphic Design','Smart Business Cards','Smart NFC Solutions'],
    contact:['Riyadh, Saudi Arabia','Smart KAF Establishment','Unified National Number: 7040340130','ZATCA Distinguished Number: 3122526599'],
    copy:'© 2026 ARTEE · Smart KAF Establishment · All rights reserved',
    legal:['Terms & Conditions','Privacy Policy']
  }
};
function setText(selector,value,{html=false,all=false}={}){
  const nodes=all?document.querySelectorAll(selector):[document.querySelector(selector)];
  nodes.forEach(node=>{if(node) html?node.innerHTML=value:node.textContent=value;});
}
let publicRoleRedirectStarted=false;
function dashboardTargetForRole(role){
  if(['owner','employee'].includes(role))return 'owner-dashboard.html';
  if(role==='freelancer')return 'freelancer-dashboard.html';
  return '';
}
function normalizePublicCustomer(customer){
  const target=dashboardTargetForRole(customer?.role);
  if(target){
    if(!publicRoleRedirectStarted){publicRoleRedirectStarted=true;location.replace(target)}
    return null;
  }
  return customer;
}
function getCustomer(){
  try{
    const stored=localStorage.getItem('arteeCustomer');
    if(stored) return normalizePublicCustomer(JSON.parse(stored));
    const legacy=localStorage.getItem('arteeDemoCustomer');
    if(legacy) return {name:'العميل محمد',email:legacy,phone:'',role:'customer'};
  }catch(e){}
  return null;
}
function readJsonStore(key,fallback=[]){
  try{
    const value=JSON.parse(localStorage.getItem(key)||'null');
    return Array.isArray(value)?value:fallback;
  }catch(e){return fallback}
}
function saveCustomerProfile(customer){
  if(!customer?.email||dashboardTargetForRole(customer.role))return;
  const normalized={...customer,role:'customer'};
  localStorage.setItem('arteeCustomer',JSON.stringify(normalized));
  try{
    const users=JSON.parse(localStorage.getItem('arteeUsers')||'{}');
    users[normalized.email]={...(users[normalized.email]||{}),...normalized};
    localStorage.setItem('arteeUsers',JSON.stringify(users));
  }catch(e){}
}
function readStockAlerts(){return readJsonStore('arteeStockAlerts',[])}
function readReadNotifications(){return readJsonStore('arteeReadNotifications',[])}
function requestNotificationMessage(item){
  const ar={client_price_sent:'عرض السعر ومدة التنفيذ جاهزان للمراجعة والدفع.',canceled:'تم إلغاء الطلب بعد رفض عرض السعر.',draft_uploaded:'المعاينة بعلامة مائية جاهزة للمراجعة.',revision_requested:'تم استلام طلب التعديل.',final_approved:'بانتظار دفع المتبقي لإكمال التسليم.',final_paid:'تم استلام الدفع المتبقي، الملف النهائي قيد التسليم.',final_uploaded:'رفع المستقل الملف النهائي وهو قيد مراجعة ARTEE.',delivered:'تم تسليم الملف النهائي.',payment_pending:'تم إنشاء طلب المنتج وهو بانتظار تأكيد التحويل البنكي.',product_received:'تم تأكيد دفع طلب المنتج واستلامه.',product_preparing:'طلب المنتج جاري التجهيز.',product_shipping:'طلب المنتج خرج للشحن.',product_delivered:'تم تسليم المنتج.'};
  const en={client_price_sent:'Price and timeline are ready for review and payment.',canceled:'Order canceled after rejecting the price offer.',draft_uploaded:'Watermarked preview is ready for review.',revision_requested:'Revision request received.',final_approved:'Remaining payment is pending to complete delivery.',final_paid:'Remaining payment received. Final file is being prepared.',final_uploaded:'The freelancer uploaded the final file; ARTEE is reviewing it.',delivered:'Final file has been delivered.',payment_pending:'The product order was created and awaits bank-transfer confirmation.',product_received:'The product payment was confirmed and the order was received.',product_preparing:'Product order is being prepared.',product_shipping:'Product order is shipping.',product_delivered:'Product delivered.'};
  return (isAr?ar:en)[item.status]||'';
}
async function saveAvailabilityAlert(item){
  const customer=getCustomer()||{};
  const email=customer.email||'guest';
  const id=[email,item?.type||'item',item?.name||'unknown'].join('::');
  const backendId=item?.backendId||item?.catalogItemId||null;
  const uuid=item?.catalogUuid||item?.uuid||'';
  if(location.protocol!=='file:'){
    if(!arteeAuthToken()||!(backendId||uuid))throw new Error(isAr?'سجّل الدخول لحفظ تنبيه التوفر.':'Sign in to save an availability alert.');
    return arteeApi('/catalog/availability-alert.php',{
      method:'POST',
      body:{backendId,uuid}
    });
  }
  const alerts=readStockAlerts();
  if(!alerts.some(alert=>alert.id===id)){
    alerts.unshift({
      id,
      email:customer.email||'',
      clientName:customer.name||'',
      itemName:item?.name||'',
      type:item?.type||'item',
      status:item?.status||'coming',
      read:false,
      createdAt:new Date().toISOString()
    });
    localStorage.setItem('arteeStockAlerts',JSON.stringify(alerts.slice(0,50)));
  }
  return {ok:true,subscribed:true};
}
async function availabilityAlertStatus(item){
  const backendId=item?.backendId||item?.catalogItemId||null,uuid=item?.catalogUuid||item?.uuid||'';
  if(location.protocol==='file:'){
    const customer=getCustomer()||{},email=customer.email||'guest',id=[email,item?.type||'item',item?.name||'unknown'].join('::');
    return {subscribed:readStockAlerts().some(alert=>alert.id===id)};
  }
  if(!arteeAuthToken()||!(backendId||uuid))return {subscribed:false};
  const params=new URLSearchParams();if(backendId)params.set('backendId',backendId);else params.set('uuid',uuid);
  return arteeApi('/catalog/availability-alert.php?'+params.toString());
}
async function cancelAvailabilityAlert(item){
  const backendId=item?.backendId||item?.catalogItemId||null,uuid=item?.catalogUuid||item?.uuid||'';
  if(location.protocol==='file:'){
    const customer=getCustomer()||{},email=customer.email||'guest',id=[email,item?.type||'item',item?.name||'unknown'].join('::');
    localStorage.setItem('arteeStockAlerts',JSON.stringify(readStockAlerts().filter(alert=>alert.id!==id)));
    return {ok:true,subscribed:false,cancelled:true};
  }
  return arteeApi('/catalog/availability-alert.php',{method:'DELETE',body:{backendId,uuid}});
}
function navNotificationCount(customer){
  if(location.protocol!=='file:')return 0;
  if(!customer)return 0;
  const email=customer.email||'';
  const read=new Set(readReadNotifications());
  const requestNotifications=(location.protocol==='file:'?readJsonStore('arteeDemoRequests',[]):[])
    .filter(request=>(request.email===email||request.customerEmail===email)&&request.status!=='archived'&&requestNotificationMessage(request))
    .map(request=>`${request.id}-${request.status}`);
  const alertNotifications=readStockAlerts()
    .filter(alert=>alert.email===email)
    .map(alert=>`stock-${alert.id}`);
  const unread=[...requestNotifications,...alertNotifications].filter(id=>!read.has(id));
  return Math.min(99,unread.length);
}
function updateNavNotifications(customer){
  const notify=document.getElementById('navNotify');
  const badge=document.getElementById('navNotifyBadge');
  if(!notify)return;
  if(location.protocol!=='file:'){
    notify.classList.toggle('visible',!!customer);
    notify.setAttribute('aria-label',isAr?'الإشعارات':'Notifications');
    if(badge){badge.hidden=true;badge.textContent=''}
    return;
  }
  const count=navNotificationCount(customer);
  notify.classList.toggle('visible',!!customer);
  notify.setAttribute('aria-label',isAr?`الإشعارات (${count})`:`Notifications (${count})`);
  if(badge)badge.hidden=!count;
}
function readCart(){
  try{return JSON.parse(localStorage.getItem('arteeCart')||'[]')}catch(e){return []}
}
function cartOwnerMatch(item,customer){
  return !customer?.email||!item.email||item.email===customer.email;
}
function updateCartBadge(customer){
  const cart=document.getElementById('navCart');
  const badge=document.getElementById('navCartBadge');
  if(!cart)return;
  const count=readCart().filter(item=>cartOwnerMatch(item,customer)).length;
  cart.classList.toggle('visible',!!customer);
  cart.setAttribute('aria-label',isAr?`السلة (${count})`:`Cart (${count})`);
  if(badge){
    badge.hidden=!count;
    badge.textContent=count>9?'9+':String(count);
  }
}
function saveCart(items){
  localStorage.setItem('arteeCart',JSON.stringify(items.slice(0,30)));
  updateCartBadge(getCustomer());
}
function cartTotalValue(items){
  return roundMoney(items.reduce((sum,item)=>sum+cartItemGrossValue(item),0));
}
function includedVatParts(total,taxEnabled=true){
  const amount=roundMoney(total);
  if(!taxEnabled)return {net:amount,tax:0,total:amount};
  const tax=roundMoney(amount-(amount/1.15));
  return {net:roundMoney(amount-tax),tax,total:amount};
}
function cartItemCatalog(item){
  try{
    const live=Array.isArray(window.__arteeVisibleProducts)?window.__arteeVisibleProducts:[];
    const backendId=String(item.backendId||item.catalogItemId||'');
    const uuid=String(item.catalogUuid||item.uuid||'');
    const matched=live.find(product=>(backendId&&String(product.backendId||product.catalogItemId||'')===backendId)||(uuid&&String(product.id||product.uuid||'')===uuid));
    if(matched)return matched;
    if(backendId||uuid)return null;
    return productCatalog[item.serviceAr]||productCatalog[item.serviceEn]||productCatalog[item.service]||null;
  }catch(error){return null}
}
function cartLiveOption(options=[],selected){
  if(!selected)return null;
  const backendId=String(selected.backendId||'');
  const key=String(selected.key||selected.id||'');
  return options.find(option=>(backendId&&String(option.backendId||option.id||'')===backendId)||(key&&String(option.key||option.modeKey||option.id||'')===key))||null;
}
function cartItemGrossValue(item){
  const catalogItem=cartItemCatalog(item);
  if(catalogItem){
    const groups=productOptionGroups(catalogItem),saved=Array.isArray(item.selections)?item.selections:(item.selection?[item.selection]:[]);
    const selectedOptions=saved.map(selection=>{const group=groups.find((candidate,index)=>(selection.groupKey&&optionGroupKey(candidate,index)===selection.groupKey)||(selection.groupId&&String(candidate.backendId||candidate.id||'')===String(selection.groupId)))||(groups.length===1?groups[0]:null);return group?cartLiveOption(group.options||[],selection):null}).filter(Boolean);
    const design=cartLiveOption(catalogItem.designOptions||[],item.contentSelection);
    const unit=roundMoney((catalogItem.price||0)+selectedOptions.reduce((sum,option)=>sum+optionExtra(option),0)+optionExtra(design));
    return roundMoney(unit*Math.max(1,Math.min(99,Number(item.quantity)||1)));
  }
  return catalogNumber(item.clientPrice||item.total||item.subtotal);
}
function cartItemAvailable(item){const product=cartItemCatalog(item);if(!product||product.active===false||['coming','soldout'].includes(product.status||'none'))return false;const groups=productOptionGroups(product),saved=Array.isArray(item.selections)?item.selections:(item.selection?[item.selection]:[]);const matched=new Set();for(const selection of saved){const group=groups.find((candidate,index)=>(selection.groupKey&&optionGroupKey(candidate,index)===selection.groupKey)||(selection.groupId&&String(candidate.backendId||candidate.id||'')===String(selection.groupId)))||(groups.length===1?groups[0]:null);if(!group||matched.has(optionGroupKey(group,groups.indexOf(group)))||!cartLiveOption(group.options||[],selection))return false;matched.add(optionGroupKey(group,groups.indexOf(group)))}if(groups.some((group,index)=>group.required&&!matched.has(optionGroupKey(group,index))))return false;if(item.contentSelection&&!cartLiveOption(product.designOptions||[],item.contentSelection))return false;return true}
function cartItemRequiresShipping(item){
  const product=cartItemCatalog(item);
  const mode=String(product?.shippingMode||item.shippingMode||'manual');
  return mode!=='none'&&(product?.requiresShipping!==false&&item.requiresShipping!==false);
}
async function checkoutIdempotencyKey(customer,items,shipping){
  const payload={
    customer:String(customer?.id||customer?.email||'customer'),
    items:items.map(item=>({
      cartId:String(item.cartId||item.id||''),catalogItemId:item.catalogItemId||item.backendId||item.catalogId||null,
      quantity:Number(item.quantity)||1,selections:(Array.isArray(item.selections)?item.selections:(item.selection?[item.selection]:[])).map(option=>({groupKey:option.groupKey||null,key:option.key||option.id||null})).sort((a,b)=>String(a.groupKey).localeCompare(String(b.groupKey))),
      contentSelection:item.contentSelection?.key||item.contentSelection?.id||null,
      contentMode:item.contentMode||null,contentLink:item.contentLink||null,contentBrief:item.contentBrief||null
    })).sort((a,b)=>a.cartId.localeCompare(b.cartId)),
    shipping:shipping||null
  };
  const source=JSON.stringify(payload);
  if(globalThis.crypto?.subtle){
    const digest=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(source));
    return `cart-${[...new Uint8Array(digest)].map(byte=>byte.toString(16).padStart(2,'0')).join('').slice(0,64)}`;
  }
  let first=2166136261,second=5381;
  for(let index=0;index<source.length;index+=1){first=Math.imul(first^source.charCodeAt(index),16777619);second=Math.imul(second,33)^source.charCodeAt(index)}
  return `cart-${(first>>>0).toString(16).padStart(8,'0')}${(second>>>0).toString(16).padStart(8,'0')}`;
}
let cartStep='items';
let cartSubmitting=false;
function cartShippingInputs(){
  return {
    recipientName:document.getElementById('cartShippingName'),
    phone:document.getElementById('cartShippingPhone'),
    region:document.getElementById('cartShippingRegion'),
    city:document.getElementById('cartShippingCity'),
    district:document.getElementById('cartShippingDistrict'),
    street:document.getElementById('cartShippingStreet'),
    buildingNumber:document.getElementById('cartShippingBuilding'),
    postalCode:document.getElementById('cartShippingPostal'),
    shortAddress:document.getElementById('cartShippingShortAddress'),
    address:document.getElementById('cartShippingAddress'),
    notes:document.getElementById('cartShippingNotes')
  };
}
function fillCartShipping(customer){
  const fields=cartShippingInputs();
  if(!fields.recipientName)return;
  fields.recipientName.value=customer.name||'';
  fields.phone.value=customer.phone||'';
  fields.region.value=customer.shippingRegion||customer.region||'منطقة الرياض';
  fields.city.value=customer.city||'الرياض';
  fields.district.value=customer.shippingDistrict||customer.district||'';
  fields.street.value=customer.shippingStreet||'';
  fields.buildingNumber.value=customer.shippingBuilding||'';
  fields.postalCode.value=customer.shippingPostal||'';
  fields.shortAddress.value=customer.shippingShortAddress||'';
  fields.address.value=customer.shippingAddress||'';
  fields.notes.value=customer.shippingNotes||'';
  Object.values(fields).forEach(input=>{input?.closest('label')?.classList.remove('order-error');input?.removeAttribute('aria-invalid')});
  const note=document.getElementById('cartShippingNote');
  if(note)note.textContent='';
}
function readCartShipping(){
  const fields=cartShippingInputs();
  return {addressId:getCustomer()?.addressId||null,...Object.fromEntries(Object.entries(fields).map(([key,input])=>[key,(input?.value||'').trim()]))};
}
function validateCartShipping(){
  const fields=cartShippingInputs();
  const data=readCartShipping();
  const note=document.getElementById('cartShippingNote');
  Object.values(fields).forEach(input=>{input?.closest('label')?.classList.remove('order-error');input?.removeAttribute('aria-invalid')});
  const required=['recipientName','phone','region','city','district','street'];
  const missing=required.filter(key=>!data[key]);
  missing.forEach(key=>{fields[key]?.closest('label')?.classList.add('order-error');fields[key]?.setAttribute('aria-invalid','true')});
  if(missing.length){
    if(note)note.textContent=isAr?'أكمل الحقول المظللة للمتابعة: اسم المستلم، الجوال، المنطقة، المدينة، الحي والشارع.':'Complete the highlighted fields to continue: recipient name, phone, region, city, district, and street.';
    fields[missing[0]]?.focus();
    return null;
  }
  if(note)note.textContent='';
  return data;
}
function closeCart(){
  const modal=document.getElementById('cartModal');
  if(!modal)return;
  modal.classList.remove('open');
  modal.setAttribute('aria-hidden','true');
}
function renderCart(){
  const customer=getCustomer();
  const list=document.getElementById('cartList');
  const total=document.getElementById('cartTotal');
  const checkout=document.getElementById('cartCheckout');
  const title=document.getElementById('cartTitle');
  const sub=document.getElementById('cartSub');
  const shippingStep=document.getElementById('cartShippingStep');
  const paymentStep=document.getElementById('cartPaymentStep');
  const paymentBox=document.getElementById('cartPaymentBox');
  if(!list)return;
  const items=readCart().filter(item=>cartOwnerMatch(item,customer));
  const unavailableCount=items.filter(item=>!cartItemAvailable(item)).length;
  const requiresShipping=items.some(cartItemRequiresShipping);
  if(!requiresShipping&&cartStep==='shipping')cartStep='payment';
  if(!items.length&&cartStep!=='items')cartStep='items';
  list.hidden=cartStep!=='items';
  if(shippingStep)shippingStep.hidden=cartStep!=='shipping';
  if(paymentStep)paymentStep.hidden=cartStep!=='payment';
  const totalValue=cartTotalValue(items);
  const taxableCount=items.filter(item=>item.taxEnabled!==false).length;
  const taxSummary=taxableCount===items.length?(isAr?'الإجمالي شامل الضريبة':'Total including VAT'):taxableCount===0?(isAr?'الإجمالي بدون ضريبة':'Total with no VAT'):(isAr?'الإجمالي (الضريبة على المنتجات الخاضعة فقط)':'Total (VAT on taxable products only)');
  title.textContent=cartStep==='shipping'?(isAr?'عنوان الشحن':'Shipping Address'):(cartStep==='payment'?(isAr?'الدفع':'Payment'):(isAr?'السلة':'Cart'));
  sub.textContent=cartStep==='shipping'
    ?(isAr?'أدخل عنوان الشحن مرة واحدة لكل منتجات السلة.':'Enter one shipping address for all cart products.')
    :(cartStep==='payment'
      ?(isAr?'راجع المبلغ وأنشئ الطلب. سيبقى بانتظار تأكيد التحويل البنكي.':'Review the amount and place the order. It will remain pending until the bank transfer is confirmed.')
      :(unavailableCount?(isAr?'بعض المنتجات تغيّرت أو لم تعد متاحة. احذفها من السلة للمتابعة.':'Some products changed or are no longer available. Remove them to continue.'):(requiresShipping?(isAr?'راجع المنتجات قبل المتابعة إلى الشحن.':'Review products before continuing to shipping.'):(isAr?'راجع المنتجات قبل المتابعة إلى الدفع.':'Review products before continuing to payment.'))));
  checkout.textContent=cartStep==='shipping'?(isAr?'متابعة للدفع':'Continue to Payment'):(cartStep==='payment'?(isAr?'إنشاء الطلب':'Place Order'):(requiresShipping?(isAr?'متابعة إلى الشحن':'Continue to Shipping'):(isAr?'متابعة إلى الدفع':'Continue to Payment')));
  total.textContent=money(cartTotalValue(items));
  checkout.disabled=cartSubmitting||!items.length||unavailableCount>0;
  if(paymentBox)paymentBox.innerHTML=isAr
    ?`سيتم إنشاء طلب واحد يحتوي على <strong>${items.length} منتج</strong><span>${taxSummary}: ${money(totalValue)}</span><span>لن يُسجل الطلب كمدفوع إلا بعد تأكيد التحويل البنكي من ARTEE.</span>`
    :`One order will be created with <strong>${items.length} product${items.length===1?'':'s'}</strong><span>${taxSummary}: ${money(totalValue)}</span><span>The order will not be marked paid until ARTEE confirms the bank transfer.</span>`;
  list.innerHTML=items.length?items.map(item=>`
    <article class="cart-item" data-cart-id="${safeAttr(item.cartId||item.id)}">
      <img src="${safeAttr(item.image||'artee-logo.png')}" alt=""/>
      <div>
        <strong>${safeAttr(isAr?(item.serviceAr||item.service):(item.serviceEn||item.service))}</strong>
        <small>${money(cartItemGrossValue(item))}${item.quantity>1?' · ×'+item.quantity:''}${(item.selections||[item.selection]).filter(Boolean).map(option=>isAr?(option.labelAr||option.label):(option.labelEn||option.labelAr||option.label)).filter(Boolean).map(label=>' · '+safeAttr(label)).join('')}${!cartItemAvailable(item)?' · '+(isAr?'غير متاح':'Unavailable'):''}</small>
      </div>
      <button class="cart-remove" type="button" data-remove-cart="${safeAttr(item.cartId||item.id)}">${isAr?'حذف':'Remove'}</button>
    </article>`).join(''):`<div class="cart-empty">${isAr?'السلة فارغة حاليًا.':'Your cart is empty.'}</div>`;
}
async function openCart(){
  if(location.protocol!=='file:'&&!(await loadBackendCustomerProfile())){
    window.ArteeUI?.notice(isAr?'تعذر تحميل بيانات الحساب والعنوان. أعد المحاولة.':'Could not load your profile and address. Please try again.','error');
    return;
  }
  const customer=getCustomer();
  if(!customer){location.href='login.html?mode=login&next=order';return;}
  const modal=document.getElementById('cartModal');
  if(!modal)return;
  cartStep='items';
  fillCartShipping(customer);
  renderCart();
  modal.classList.add('open');
  modal.setAttribute('aria-hidden','false');
}
async function checkoutCart(){
  if(cartSubmitting)return;
  const customer=getCustomer();
  const items=readCart();
  const mine=items.filter(item=>cartOwnerMatch(item,customer));
  if(!customer||!mine.length)return;
  if(mine.some(item=>!cartItemAvailable(item))){cartStep='items';renderCart();return}
  const requiresShipping=mine.some(cartItemRequiresShipping);
  if(cartStep==='items'){
    cartStep=requiresShipping?'shipping':'payment';
    renderCart();
    return;
  }
  if(cartStep==='shipping'){
    if(!validateCartShipping())return;
    cartStep='payment';
    renderCart();
    return;
  }
  const shippingData=requiresShipping?validateCartShipping():null;
  if(requiresShipping&&!shippingData){
    cartStep='shipping';
    renderCart();
    return;
  }
  cartSubmitting=true;
  const checkoutButton=document.getElementById('cartCheckout');
  if(checkoutButton){
    checkoutButton.disabled=true;
    checkoutButton.textContent=isAr?'جارٍ إنشاء الطلب…':'Creating order…';
  }
  const now=new Date();
  const requests=location.protocol==='file:'?JSON.parse(localStorage.getItem('arteeDemoRequests')||'[]'):[];
  const total=cartTotalValue(mine);
  const idempotencyKey=await checkoutIdempotencyKey(customer,mine,shippingData);
  const taxAmount=mine.reduce((sum,item)=>sum+includedVatParts(cartItemGrossValue(item),item.taxEnabled!==false).tax,0);
  const subtotal=total-taxAmount;
  const first=mine[0]||{};
  const itemSummary=mine.map((item,index)=>{
    const name=isAr?(item.serviceAr||item.service):(item.serviceEn||item.serviceAr||item.service);
    const labels=(item.selections||[item.selection]).filter(Boolean).map(option=>isAr?(option.labelAr||option.label):(option.labelEn||option.labelAr||option.label)).filter(Boolean);
    const selection=labels.length?` - ${labels.join(' / ')}`:'';
    const price=money(cartItemGrossValue(item));
    return `${index+1}. ${name||'Product'}${selection}${price?' ('+price+')':''}`;
  }).join(' / ');
  const stamped={
    ...first,
    id:'REQ-'+String(Date.now()).slice(-6),
    idempotencyKey,
    service:mine.length>1?'طلب منتجات متعددة':(first.service||first.serviceAr||first.serviceEn),
    serviceAr:mine.length>1?'طلب منتجات متعددة':(first.serviceAr||first.service||first.serviceEn),
    serviceEn:mine.length>1?'Multiple Products Order':(first.serviceEn||first.serviceAr||first.service),
    descriptionAr:mine.length>1?'طلب واحد يحتوي على عدة منتجات من السلة.':(first.descriptionAr||first.description||''),
    descriptionEn:mine.length>1?'One checkout order containing multiple cart products.':(first.descriptionEn||first.descriptionAr||''),
    message:itemSummary,
    items:mine.map(item=>{const gross=cartItemGrossValue(item);const vat=includedVatParts(gross,item.taxEnabled!==false);return {...item,cartId:undefined,subtotal:money(vat.net),taxAmount:money(vat.tax),clientPrice:money(gross),total:money(gross)}}),
    type:'product',
    status:'payment_pending',
    productPayment:'manual-pending',
    paymentPlan:'full',
    subtotal:money(subtotal),
    taxEnabled:mine.some(item=>item.taxEnabled!==false),
    taxRate:15,
    taxAmount:money(taxAmount),
    clientPrice:money(total),
    initialPayment:'بانتظار تأكيد التحويل البنكي',
    initialPaymentAt:'',
    clientName:customer.name||shippingData?.recipientName||first.clientName||'العميل محمد',
    phone:shippingData?.phone||customer.phone||first.phone||'',
    country:customer.country||first.country||'المملكة العربية السعودية',
    shippingRecipient:shippingData?.recipientName||'',
    shippingPhone:shippingData?.phone||'',
    shippingRegion:shippingData?.region||'',
    city:shippingData?.city||'',
    shippingDistrict:shippingData?.district||'',
    shippingStreet:shippingData?.street||'',
    shippingBuilding:shippingData?.buildingNumber||'',
    shippingPostal:shippingData?.postalCode||'',
    shippingShortAddress:shippingData?.shortAddress||'',
    shippingAddress:shippingData?.address||'',
    shippingNotes:shippingData?.notes||'',
    invoiceId:'',
    paidAt:'',
    createdAt:now.toISOString()
  };
  if(shippingData&&location.protocol==='file:')saveCustomerProfile({
    ...customer,
    name:customer.name||shippingData.recipientName,
    phone:customer.phone||shippingData.phone,
    shippingRegion:shippingData.region,
    city:shippingData.city,
    shippingDistrict:shippingData.district,
    shippingStreet:shippingData.street,
    shippingBuilding:shippingData.buildingNumber,
    shippingPostal:shippingData.postalCode,
    shippingShortAddress:shippingData.shortAddress,
    shippingAddress:shippingData.address,
    shippingNotes:shippingData.notes
  });
  let backendOrder=null;
  try{
    const stagedItems=await stageCartAttachments(mine,idempotencyKey);
    backendOrder=await syncOrderToBackend(stamped,stagedItems,shippingData,true);
  }catch(error){
    await discardStagedCheckout(idempotencyKey);
    cartSubmitting=false;
    renderCart();
    const paymentBox=document.getElementById('cartPaymentBox');
    if(paymentBox){
      paymentBox.textContent=error.message||(isAr?'تعذر إنشاء الطلب. لم يتم خصم السلة، ويمكنك المحاولة مرة أخرى.':'Could not create the order. Your cart was kept so you can try again.');
    }
    return;
  }
  if(!backendOrder){
    await discardStagedCheckout(idempotencyKey);
    cartSubmitting=false;
    renderCart();
    const paymentBox=document.getElementById('cartPaymentBox');
    if(paymentBox)paymentBox.textContent=isAr?'تعذر إنشاء طلب حقيقي. لم يتم حذف أي منتج من السلة.':'A real order could not be created. No cart items were removed.';
    return;
  }
  applyBackendOrderMeta(stamped,backendOrder);
  if(location.protocol!=='file:')await loadBackendCustomerProfile();
  if(location.protocol==='file:')localStorage.setItem('arteeDemoRequests',JSON.stringify([stamped,...requests].slice(0,30)));
  const committedAttachmentIds=collectStoredAttachmentIds(mine);
  saveCart(items.filter(item=>!cartOwnerMatch(item,customer)));
  await deleteStoredAttachmentIds(committedAttachmentIds,{ownerKey:attachmentOwnerKey(customer),allowLegacy:true,activeIds:activeStoredAttachmentIds()});
  updateNavNotifications(customer);
  closeCart();
  location.href='account.html#orders';
}
function updateAccountUi(t){
  const customer=getCustomer();
  document.querySelectorAll('.nav-login').forEach(link=>{
    if(customer){
      const displayName=customer.name||'العميل محمد';
      link.href='account.html';
      link.classList.add('logged-in');
      link.setAttribute('aria-haspopup','menu');
      link.setAttribute('aria-expanded','false');
      link.innerHTML=`<span class="account-avatar">${safeAttr(displayName.trim().charAt(0))}</span><span>${safeAttr(displayName)}</span>`;
    }else{
      link.href='login.html';
      link.classList.remove('logged-in');
      link.removeAttribute('aria-haspopup');
      link.removeAttribute('aria-expanded');
      link.textContent=t.login;
    }
  });
  updateAccountMenuText(t);
  updateNavNotifications(customer);
  updateCartBadge(customer);
}
const accountMenu=document.getElementById('accountMenu');
function logoutCustomer(){
  const customer=getCustomer(),items=readCart(),mine=items.filter(item=>cartOwnerMatch(item,customer));
  saveCart(items.filter(item=>!cartOwnerMatch(item,customer)));
  void deleteStoredAttachmentIds(collectStoredAttachmentIds(mine),{ownerKey:attachmentOwnerKey(customer),allowLegacy:true,activeIds:activeStoredAttachmentIds()}).catch(()=>{});
  ['arteeCustomer','arteeAuthToken','arteeAuthExpiresAt','arteeAuthUser','arteeDemoCustomer','arteeBackendOrders','arteeFreelancerBackendOrders','arteeDemoRequests'].forEach(key=>localStorage.removeItem(key));
  closeAccountMenu();
  updateAccountUi(textMap[isAr?'ar':'en']);
  if(location.hash!=='#hero')location.href='artee_latest.html#hero';
}
accountMenu?.addEventListener('click',event=>{
  const logoutLink=event.target.closest?.('[data-account-logout]');
  if(!logoutLink)return;
  event.preventDefault();
  event.stopPropagation();
  logoutCustomer();
});
function updateAccountMenuText(t){
  if(!accountMenu)return;
  accountMenu.querySelectorAll('[data-account-option]').forEach((link,index)=>{
    const label=t.accountOptions?.[index];
    if(label)link.textContent=label;
  });
  const logoutLink=accountMenu.querySelector('[data-account-logout]');
  if(logoutLink)logoutLink.textContent=t.logout||'تسجيل الخروج';
}
function closeAccountMenu(){
  if(!accountMenu)return;
  accountMenu.classList.remove('open');
  accountMenu.setAttribute('aria-hidden','true');
  document.querySelectorAll('.nav-login.logged-in').forEach(link=>link.setAttribute('aria-expanded','false'));
}
function openAccountMenu(trigger){
  if(!accountMenu)return;
  const rect=trigger.getBoundingClientRect();
  const width=230;
  const top=rect.bottom+10;
  const preferredLeft=document.documentElement.dir==='rtl'?rect.right-width:rect.left;
  const left=Math.max(12,Math.min(preferredLeft,window.innerWidth-width-12));
  accountMenu.style.top=top+'px';
  accountMenu.style.left=left+'px';
  accountMenu.classList.add('open');
  accountMenu.setAttribute('aria-hidden','false');
  document.querySelectorAll('.nav-login.logged-in').forEach(link=>link.setAttribute('aria-expanded',link===trigger?'true':'false'));
}
document.addEventListener('click',event=>{
  const trigger=event.target.closest?.('.nav-login.logged-in');
  if(trigger){
    event.preventDefault();
    event.stopPropagation();
    if(accountMenu?.classList.contains('open'))closeAccountMenu();
    else openAccountMenu(trigger);
    return;
  }
  const logoutLink=event.target.closest?.('[data-account-logout]');
  if(logoutLink){
    event.preventDefault();
    logoutCustomer();
    return;
  }
  if(accountMenu&&!event.target.closest?.('#accountMenu'))closeAccountMenu();
});
window.addEventListener('resize',closeAccountMenu);
window.addEventListener('scroll',closeAccountMenu,{passive:true});
function applyLanguage(){
  const lang=isAr?'ar':'en',t=textMap[lang];
  document.documentElement.lang=lang;
  document.documentElement.dir=isAr?'rtl':'ltr';
  document.title=(isAr?'ARTEE | نحول الخيال إلى واقع':'ARTEE | From Imagination to Reality');
  document.body.classList.toggle('lang-en',!isAr);
  document.body.classList.toggle('lang-ar',isAr);
  langButtons.forEach(btn=>btn.textContent=isAr?'EN':'AR');
  const cardImage=document.querySelector('img[src*="artee-business-card"]');if(cardImage)cardImage.alt=isAr?'بطاقة أعمال ARTEE':'ARTEE business card';
  const aboutLogo=document.querySelector('.about-brand-logo');if(aboutLogo)aboutLogo.alt=isAr?'شعار ARTEE':'ARTEE logo';
  document.querySelectorAll('.nav-links a').forEach((a,i)=>a.textContent=t.nav[i]);
  document.querySelectorAll('.mobile-menu > a').forEach((a,i)=>a.textContent=t.nav[i]);
  updateAccountUi(t);
  setText('.hero-title',t.heroTitle,{html:true});
  setText('.hero-sub',t.heroSub);
  setText('.hero-actions .btn-primary',t.start);
  setText('.hero-actions .btn-ghost',t.discover);
  document.querySelectorAll('.card-tab').forEach((tab,i)=>tab.textContent=t.tabs[i]);
  setText('#dispNfc .nfc-card-name',t.cardName);
  setText('#dispNfc .nfc-card-sub',t.cardSub);
  setText('#disp3d .nfc-card-name',t.designName);
  setText('#disp3d .nfc-card-sub',t.designSub);
  setText('.hero-scroll span',t.scroll);
  setText('.about-question',t.aboutQuestion,{html:true});
  setText('.about-founded',t.founded);
  setText('.about-content .section-title',t.aboutTitle,{html:true});
  setText('.about-body',t.aboutBody);
  document.querySelectorAll('.pillar').forEach((pillar,i)=>{
    pillar.querySelector('.pillar-title').textContent=t.pillars[i][0];
    pillar.querySelector('.pillar-sub').textContent=t.pillars[i][1];
  });
  setText('.services-question',t.servicesQuestion,{html:true});
  document.querySelectorAll('.switch-panel').forEach((panel,i)=>{
    panel.querySelector('.gate-title').textContent=t.gates[i].title;
    panel.querySelector('.gate-action').textContent=t.gates[i].action;
    panel.querySelector('.switch-title').textContent=t.gates[i].heading;
    panel.querySelector('.switch-count').textContent=t.gates[i].count;
  });
  if(window.__arteeCatalogReady){
    renderClientCatalog();
    bindCatalogCards();
  }
  setText('.transform-title',t.finalTitle);
  setText('.transform-sub',t.finalSub);
  setText('.transform-hint',t.finalHint);
  setText('.footer-slogan',t.footerSlogan);
  document.querySelectorAll('.footer-col-title').forEach((title,i)=>title.textContent=t.footerCols[i]);
  document.querySelectorAll('.footer-grid > div:nth-child(2) .footer-list a').forEach((a,i)=>a.textContent=t.quick[i]);
  document.querySelectorAll('.footer-grid > div:nth-child(3) .footer-list a').forEach((a,i)=>a.textContent=t.offers[i]);
  const contactItems=document.querySelectorAll('.footer-grid > div:nth-child(4) .footer-list li');
  if(contactItems[0]) contactItems[0].querySelector('span').textContent=t.contact[0];
  if(contactItems[3]) contactItems[3].querySelector('span').textContent=t.contact[1];
  if(contactItems[4]) contactItems[4].querySelector('span').textContent=t.contact[2];
  if(contactItems[5]) contactItems[5].querySelector('span').textContent=t.contact[3];
  setText('.footer-copy',t.copy);
  document.querySelectorAll('.footer-legal-links a').forEach((a,i)=>a.textContent=t.legal[i]);
  document.querySelector('.nav-mode').setAttribute('aria-label',lightMode?(isAr?'التبديل للوضع الداكن':'Switch to dark mode'):(isAr?'التبديل للوضع الفاتح':'Switch to light mode'));
  document.querySelector('[data-panel="services"] .switch-gate').setAttribute('aria-label',isAr?'عرض الخدمات':'Show services');
  document.querySelector('[data-panel="products"] .switch-gate').setAttribute('aria-label',isAr?'عرض المنتجات':'Show products');
  document.querySelector('.cube')?.setAttribute('aria-label',isAr?'مكعب أحجية ثلاثي الأبعاد تفاعلي':'Interactive 3D puzzle cube');
  const ui=isAr?{
    option:'خيارات المنتج',quantity:'الكمية',contentTitle:'محتوى البطاقة الذكية',contentHint:'اختر كيف تريد تجهيز المحتوى الداخلي للبطاقة.',contentDetails:'تفاصيل المحتوى',link:'رابط Linktree',details:'تفاصيل الطلب',detailsPlaceholder:'اكتب وصفًا مختصرًا لما تريد تنفيذه...',shippingTitle:'عنوان الشحن للمنتج',shippingHint:'راجع العنوان قبل الدفع، ويمكنك تعديله هنا.',attachment:'مرفقات داعمة',attachmentHelp:'مراجع تساعدنا على فهم الفكرة: صور أو PDF أو ZIP/RAR. الحد الأقصى 4 ملفات، 25MB للملف، و75MB إجمالًا.',submit:'إرسال الطلب',cart:'السلة',cartSub:'راجع المنتجات قبل المتابعة إلى الدفع.',checkout:'متابعة الدفع',close:'إغلاق',shippingLabels:['اسم المستلم','رقم الجوال','المنطقة / الولاية','المدينة','الحي / المنطقة','الشارع','رقم المبنى','الرمز البريدي','رمز العنوان المختصر','تفاصيل إضافية','ملاحظات اختيارية'],placeholders:['مثال: محمد خالد','05xxxxxxxx','منطقة الرياض','الرياض','العليا','طريق الملك فهد','3670','12221','RHOA3670','أقرب معلم أو تعليمات وصول إضافية','وقت مناسب للتواصل أو تفاصيل إضافية']
  }:{
    option:'Product options',quantity:'Quantity',contentTitle:'Smart card content',contentHint:'Choose how you want the card content to be prepared.',contentDetails:'Content details',link:'Linktree URL',details:'Request details',detailsPlaceholder:'Briefly describe what you would like us to create...',shippingTitle:'Product shipping address',shippingHint:'Review the address before payment. You can edit it here.',attachment:'Supporting attachments',attachmentHelp:'Helpful references: images, PDF, or ZIP/RAR. Up to 4 files, 25MB each, and 75MB total.',submit:'Send request',cart:'Cart',cartSub:'Review the products before continuing to payment.',checkout:'Continue to payment',close:'Close',shippingLabels:['Recipient name','Phone number','Region / State','City','District / Area','Street','Building number','Postal code','Short address code','Additional details','Optional notes'],placeholders:['Example: Mohammed Khaled','05xxxxxxxx','Riyadh Region','Riyadh','Al Olaya','King Fahd Road','3670','12221','RHOA3670','Nearest landmark or additional directions','Preferred contact time or other details']
  };
  const setLabel=(selector,value)=>{const el=document.querySelector(selector);if(!el)return;const node=[...el.childNodes].find(item=>item.nodeType===Node.TEXT_NODE&&item.textContent.trim());if(node)node.textContent=value+'\n'};
  setLabel('#orderOptionWrap',ui.option);setLabel('#orderQuantityWrap',ui.quantity);setText('.product-config-title',ui.contentTitle);setText('.product-config-hint',ui.contentHint);setLabel('#productContentBriefWrap',ui.contentDetails);setLabel('#productLinkWrap',ui.link);setLabel('#orderMessageWrap',ui.details);setLabel('#orderAttachmentWrap',ui.attachment);
  document.getElementById('orderMessage').placeholder=ui.detailsPlaceholder;document.getElementById('productContentBrief').placeholder=isAr?'اكتب الروابط والنصوص والهوية أو أي ملاحظات مساعدة...':'Add links, text, brand assets, or any helpful notes...';
  document.getElementById('orderShippingTitle').textContent=ui.shippingTitle;document.getElementById('orderShippingHint').textContent=ui.shippingHint;document.querySelector('#orderAttachmentWrap .order-help').textContent=ui.attachmentHelp;
  document.querySelectorAll('#orderShippingWrap > label').forEach((label,index)=>{const node=[...label.childNodes].find(item=>item.nodeType===Node.TEXT_NODE&&item.textContent.trim());if(node)node.textContent=(ui.shippingLabels[index]||'')+'\n';const input=label.querySelector('input');if(input&&ui.placeholders[index])input.placeholder=ui.placeholders[index]});
  document.querySelectorAll('#cartShippingStep label').forEach((label,index)=>{const node=[...label.childNodes].find(item=>item.nodeType===Node.TEXT_NODE&&item.textContent.trim());if(node)node.textContent=(ui.shippingLabels[index]||'')+'\n';const input=label.querySelector('input');if(input&&ui.placeholders[index])input.placeholder=ui.placeholders[index]});
  document.querySelectorAll('.order-close,.cart-close').forEach(button=>button.setAttribute('aria-label',ui.close));document.getElementById('cartTitle').textContent=ui.cart;document.getElementById('cartSub').textContent=ui.cartSub;document.getElementById('cartCheckout').textContent=ui.checkout;
  const modalEl=document.getElementById('orderModal'),submitEl=document.querySelector('#orderForm .order-submit');if(modalEl&&submitEl&&!modalEl.classList.contains('open'))submitEl.textContent=ui.submit;
}
langButtons.forEach(btn=>{
  btn.addEventListener('click',()=>{
    isAr=!isAr;
    localStorage.setItem('arteeLang',isAr?'ar':'en');
    applyLanguage();
    if(window.__arteeSiteSettings)applyPublicSiteSettings(window.__arteeSiteSettings);
  });
});
applyLanguage();

/* Hamburger */
document.getElementById('hamburger').addEventListener('click',()=>{
  document.getElementById('mobileMenu').classList.toggle('open');
});
function closeMobile(){document.getElementById('mobileMenu').classList.remove('open');}
document.querySelectorAll('#mobileMenu > a').forEach(link=>link.addEventListener('click',closeMobile));

/* Tabs */
function switchTab(type,el){
  document.querySelectorAll('.card-tab').forEach(t=>t.classList.remove('active'));
  el.classList.add('active');
  const nfc=document.getElementById('dispNfc'),d3=document.getElementById('disp3d');
  const show3d=type==='3d';
  nfc.classList.toggle('active',!show3d);
  d3.classList.toggle('active',show3d);
  nfc.style.display=show3d?'none':'flex';
  d3.style.display=show3d?'flex':'none';
}
document.querySelectorAll('[data-card-tab]').forEach(tab=>{
  tab.addEventListener('click',()=>switchTab(tab.dataset.cardTab,tab));
});
document.getElementById('dispNfc').style.display='flex';
document.getElementById('disp3d').style.display='none';

/* Services and products expanding switcher */
const servicesSwitcher=document.querySelector('.services-switcher');
const switchPanels=document.querySelectorAll('.switch-panel');
function activatePanel(name){
  servicesSwitcher.dataset.active=name;
  switchPanels.forEach(panel=>{
    const active=panel.dataset.panel===name;
    panel.classList.toggle('active',active);
    if(active){
      panel.querySelectorAll('.service-item').forEach((item,index)=>{
        item.classList.remove('revealed');
        setTimeout(()=>item.classList.add('revealed'),180+(index*110));
      });
    }
  });
}
switchPanels.forEach(panel=>{
  panel.querySelector('.switch-gate').addEventListener('click',()=>activatePanel(panel.dataset.panel));
});
function syncPanelFromHash(){
  if(location.hash==='#products') activatePanel('products');
  if(location.hash==='#services') activatePanel('services');
}
document.querySelectorAll('a[href="#products"],a[href="#services"]').forEach(link=>{
  link.addEventListener('click',()=>activatePanel(link.getAttribute('href')==='#products'?'products':'services'));
});
window.addEventListener('hashchange',syncPanelFromHash);
syncPanelFromHash();

/* Service/product request flow */
const orderModal=document.getElementById('orderModal');
const orderDialog=orderModal.querySelector('.order-dialog');
const orderClose=document.getElementById('orderClose');
const orderForm=document.getElementById('orderForm');
const orderService=document.getElementById('orderService');
const orderType=document.getElementById('orderType');
const orderTitle=document.getElementById('orderTitle');
const orderDesc=document.getElementById('orderDesc');
const orderLongDesc=document.getElementById('orderLongDesc');
const orderImage=document.getElementById('orderImage');
const orderImageSrc=document.getElementById('orderImageSrc');
const orderMeta=document.getElementById('orderMeta');
const orderPrice=document.getElementById('orderPrice');
const orderOptionWrap=document.getElementById('orderOptionWrap');
const orderOption=document.getElementById('orderOption');
const orderOptions=document.getElementById('orderOptions');
const orderOptionGroups=document.getElementById('orderOptionGroups');
const orderQuantityWrap=document.getElementById('orderQuantityWrap');
const orderQuantity=document.getElementById('orderQuantity');
const productConfigWrap=document.getElementById('productConfigWrap');
const productContentMode=document.getElementById('productContentMode');
const productContentModes=document.getElementById('productContentModes');
const productContentBriefWrap=document.getElementById('productContentBriefWrap');
const productContentBrief=document.getElementById('productContentBrief');
const productLinkWrap=document.getElementById('productLinkWrap');
const productLink=document.getElementById('productLink');
const orderMessageWrap=document.getElementById('orderMessageWrap');
const orderMessage=document.getElementById('orderMessage');
const orderAttachmentWrap=document.getElementById('orderAttachmentWrap');
const orderAttachment=document.getElementById('orderAttachment');
const orderShippingWrap=document.getElementById('orderShippingWrap');
const shippingName=document.getElementById('shippingName');
const shippingPhone=document.getElementById('shippingPhone');
const shippingRegion=document.getElementById('shippingRegion');
const shippingCity=document.getElementById('shippingCity');
const shippingDistrict=document.getElementById('shippingDistrict');
const shippingStreet=document.getElementById('shippingStreet');
const shippingBuilding=document.getElementById('shippingBuilding');
const shippingPostal=document.getElementById('shippingPostal');
const shippingShortAddress=document.getElementById('shippingShortAddress');
const shippingAddress=document.getElementById('shippingAddress');
const shippingNotes=document.getElementById('shippingNotes');
const orderShippingTitle=document.getElementById('orderShippingTitle');
const orderShippingHint=document.getElementById('orderShippingHint');
const orderNote=document.getElementById('orderNote');
const orderSubmit=orderForm.querySelector('.order-submit');
const notifyModal=document.getElementById('notifyModal');
const notifyTitle=document.getElementById('notifyTitle');
const notifySub=document.getElementById('notifySub');
const notifyConfirm=document.getElementById('notifyConfirm');
const notifyCancel=document.getElementById('notifyCancel');
const notifyClose=document.getElementById('notifyClose');
let orderSubmitting=false;
let activeNotifyItem=null,activeNotifySubscribed=false;
const MAX_ORDER_ATTACHMENTS=4;
const MAX_ATTACHMENT_SIZE=25*1024*1024;
const MAX_TOTAL_ATTACHMENT_SIZE=75*1024*1024;
const ALLOWED_ATTACHMENT_EXTENSIONS=['jpg','jpeg','png','webp','pdf','zip'];
const ATTACHMENT_DB='arteeDemoAttachments';
const ATTACHMENT_STORE='files';
const ATTACHMENT_MAX_AGE_MS=7*24*60*60*1000;
const productCatalog={
  'بطاقات أعمال ذكية':{price:299,image:'artee-business-card-optimized.png',productMode:'smart-card',hasChoices:true,hasDesign:true,options:[{id:'standard',labelAr:'بطاقة قياسية',labelEn:'Standard card',price:0},{id:'premium',labelAr:'NFC فاخرة',labelEn:'Premium NFC',price:100},{id:'metal',labelAr:'خامة معدنية',labelEn:'Metal material',price:250}]},
  'الملف الرقمي':{price:199,image:'artee-logo.png',productMode:'direct',options:[]},
  'حلول QR مخصصة':{price:149,image:'artee-logo.png',productMode:'direct',options:[]},
  'Smart Business Cards':{price:299,image:'artee-business-card-optimized.png',productMode:'smart-card',hasChoices:true,hasDesign:true,options:[{id:'standard',labelAr:'بطاقة قياسية',labelEn:'Standard card',price:0},{id:'premium',labelAr:'NFC فاخرة',labelEn:'Premium NFC',price:100},{id:'metal',labelAr:'خامة معدنية',labelEn:'Metal material',price:250}]},
  'Digital Profile':{price:199,image:'artee-logo.png',productMode:'direct',options:[]},
  'Custom QR Solutions':{price:149,image:'artee-logo.png',productMode:'direct',options:[]}
};
const serviceVisuals={
  'تصميم جرافيكي':'artee-logo.png',
  'تصميم ثلاثي الأبعاد':'artee-logo.png',
  'الهوية البصرية':'artee-logo.png',
  'موشن جرافيك':'artee-logo.png',
  'Graphic Design':'artee-logo.png',
  '3D Design':'artee-logo.png',
  'Visual Identity':'artee-logo.png',
  'Motion Graphics':'artee-logo.png'
};
let activeOrderData=null;

function roundMoney(value){const amount=Number(value);return Number.isFinite(amount)?Math.round((amount+Number.EPSILON)*100)/100:0}
function money(value){const amount=Number(value);return Number.isFinite(amount)?`${roundMoney(amount).toFixed(2)} SAR`:''}
function fileExtension(file){return (file.name.split('.').pop()||'').toLowerCase()}
let activeProductOptionSelections=[];
function productOptionGroups(item=activeOrderData){
  if(Array.isArray(item?.optionGroups)&&item.optionGroups.length)return item.optionGroups;
  if(Array.isArray(item?.options)&&item.options.length)return [{id:null,backendId:null,key:'legacy-product-options',groupKey:'legacy-product-options',nameAr:'خيارات المنتج',nameEn:'Product options',required:true,options:item.options}];
  return [];
}
function optionGroupKey(group,index=0){return String(group?.groupKey||group?.key||group?.backendId||group?.id||`group-${index+1}`)}
function selectedProductOptions(){return activeProductOptionSelections.map(entry=>entry.option)}
function syncProductOptionPills(){
  orderOptionGroups.querySelectorAll('.order-option-pill').forEach(pill=>{
    const groupKey=pill.dataset.groupKey||pill.dataset.clearGroup;
    const selected=activeProductOptionSelections.find(entry=>entry.groupKey===groupKey);
    const active=pill.dataset.clearGroup?!selected:(selected&&optionId(selected.option)===pill.dataset.value);
    pill.classList.toggle('active',active);
    pill.setAttribute('aria-checked',active?'true':'false');
  });
}
function updateProductPrice(){
  if(!activeOrderData||activeOrderData.type!=='product')return;
  const design=activeOrderData.designOptions?.find((option,index)=>optionId(option,index)===productContentMode.value);
  const quantity=Math.max(1,Math.min(99,Number(orderQuantity?.value)||1));
  const optionDelta=selectedProductOptions().reduce((sum,option)=>sum+optionExtra(option),0);
  const unitPrice=roundMoney((activeOrderData.price||0)+optionDelta+optionExtra(design));
  const price=roundMoney(unitPrice*quantity);
  orderPrice.textContent=money(price);
  syncProductOptionPills();
  syncProductContentPills();
}
function renderProductOptions(groups){
  activeProductOptionSelections=[];
  orderOptionGroups.innerHTML=(groups||[]).map((group,groupIndex)=>{
    const groupKey=optionGroupKey(group,groupIndex),options=Array.isArray(group.options)?group.options:[];
    if(group.required&&options[0])activeProductOptionSelections.push({groupKey,group,option:options[0]});
    const title=isAr?(group.nameAr||group.name||group.nameEn):(group.nameEn||group.name||group.nameAr);
    const optional=group.required?'':`<button class="order-option-pill" type="button" data-clear-group="${safeAttr(groupKey)}">${isAr?'بدون اختيار':'No selection'}</button>`;
    return `<section class="order-option-group" data-option-group="${safeAttr(groupKey)}"><div class="order-option-group-head"><strong>${safeAttr(title||'')}</strong><small>${group.required?(isAr?'مطلوب':'Required'):(isAr?'اختياري':'Optional')}</small></div><div class="order-options">${optional}${options.map((option,index)=>`<button class="order-option-pill" type="button" role="radio" aria-checked="false" data-group-key="${safeAttr(groupKey)}" data-value="${safeAttr(optionId(option,index))}"><span>${safeAttr(optionLabel(option,index))}</span><span class="order-option-price">${safeAttr(optionPriceText(option))}</span></button>`).join('')}</div></section>`;
  }).join('');
  orderOption.value=activeProductOptionSelections[0]?optionId(activeProductOptionSelections[0].option):'';
  updateProductPrice();
}
function defaultCatalogIcon(item,type){const key=String(item?.id||item?.name||'').toLowerCase();if(key.includes('3d')||key.includes('ثلاث'))return 'cube';if(key.includes('motion')||key.includes('موشن'))return 'motion';if(key.includes('identity')||key.includes('هوية'))return 'identity';if(key.includes('card')||key.includes('بطاق'))return 'card';if(key.includes('profile')||key.includes('ملف'))return 'link';if(key.includes('qr'))return 'qr';return type==='products'?'box':'pen'}
function defaultProductMode(item){const key=String(item?.id||item?.name||item?.nameAr||'').toLowerCase();if(item?.hasDesign||key.includes('card')||key.includes('بطاق'))return 'smart-card';if(item?.hasChoices||item?.options?.length)return 'materials';return 'direct'}
function optionId(option,index=0){return Array.isArray(option)?option[0]:(option?.key||option?.modeKey||option?.id||`option-${index+1}`)}
function optionLabel(option,index=0){if(Array.isArray(option))return option[1]||`Option ${index+1}`;return isAr?(option?.labelAr||option?.label||option?.labelEn||`خيار ${index+1}`):(option?.labelEn||option?.label||option?.labelAr||`Option ${index+1}`)}
function optionExtra(option){const value=Array.isArray(option)?option[2]:(option?.price??option?.priceExtra??option?.priceDelta);const n=parseFloat(String(value||'').replace(/[^\d.]/g,''));return Number.isFinite(n)?roundMoney(n):0}
function optionPriceText(option){const extra=optionExtra(option);return extra?`+ ${money(extra)}`:(isAr?'بدون زيادة':'No extra')}
function itemName(item){return isAr?(item.nameAr||item.name):(item.nameEn||item.nameAr||item.name)}
function itemDescription(item){return isAr?(item.descriptionAr||item.description):(item.descriptionEn||item.descriptionAr||item.description)}
function safeAttr(value){return String(value??'').replace(/[&<>"']/g,char=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[char]))}
function defaultDesignOptions(item={}){return item.designOptions?.length?item.designOptions:[{id:'own-design',labelAr:'تصميم جاهز من العميل',labelEn:'Client ready design',price:0},{id:'linktree',labelAr:'رابط Linktree',labelEn:'Linktree link',price:0},{id:'artee-design',labelAr:'تصميم من ARTEE',labelEn:'Designed by ARTEE',price:0}]}
function catalogIconSvg(icon='pen'){
  const paths={
    pen:'<path d="M4 20h4l11-11-4-4L4 16v4z"/><path d="M13 6l4 4"/>',
    cube:'<path d="M12 3l8 4.5v9L12 21l-8-4.5v-9L12 3z"/><path d="M12 12l8-4.5"/><path d="M12 12v9"/><path d="M12 12L4 7.5"/>',
    motion:'<path d="M5 7h9"/><path d="M5 12h14"/><path d="M5 17h7"/><path d="M16 8l3 4-3 4"/>',
    identity:'<path d="M4 7h16"/><path d="M7 4v16"/><path d="M4 17h16"/><path d="M17 4v16"/>',
    card:'<path d="M4 7h16v10H4z"/><path d="M7 11h5"/><path d="M7 14h3"/><path d="M15 11h2"/>',
    link:'<path d="M9 12a4 4 0 016-3l1 1"/><path d="M15 12a4 4 0 01-6 3l-1-1"/><path d="M8 12h8"/>',
    qr:'<path d="M4 4h6v6H4z"/><path d="M14 4h6v6h-6z"/><path d="M4 14h6v6H4z"/><path d="M14 14h2"/><path d="M18 14h2v2"/><path d="M14 18h6"/>',
    box:'<path d="M5 8l7-4 7 4-7 4-7-4z"/><path d="M5 8v8l7 4 7-4V8"/><path d="M12 12v8"/>'
  };
  return `<svg viewBox="0 0 24 24">${paths[icon]||paths.pen}</svg>`;
}
function smartCardContentOptions(){
  return activeOrderData?.designOptions?.length?activeOrderData.designOptions:defaultDesignOptions(activeOrderData);
}
function syncProductContentPills(){
  productContentModes.querySelectorAll('.order-option-pill').forEach(pill=>{
    const active=pill.dataset.value===productContentMode.value;
    pill.classList.toggle('active',active);
    pill.setAttribute('aria-checked',active?'true':'false');
  });
}
function updateProductContentFields(){
  const smart=activeOrderData?.type==='product'&&activeOrderData?.productMode==='smart-card';
  productConfigWrap.classList.toggle('order-hidden',!smart);
  if(!smart)return;
  const value=productContentMode.value||'artee-design';
  const linkMode=value==='linktree';
  productLinkWrap.classList.toggle('order-hidden',!linkMode);
  productContentBriefWrap.classList.toggle('order-hidden',linkMode);
  orderAttachmentWrap.classList.toggle('order-hidden',linkMode);
  productContentBrief.placeholder=value==='own-design'
    ?(isAr?'اكتب أي ملاحظات على التصميم الجاهز، وارفق الملف إذا كان متوفرًا.':'Add notes about your ready design, and attach the file if available.')
    :(isAr?'اكتب الروابط، النصوص، الهوية، والألوان التي تريد أن نبني عليها التصميم.':'Write the links, text, brand notes, and colors you want us to design around.');
  syncProductContentPills();
  updateProductPrice();
}
function renderProductContentModes(){
  const options=smartCardContentOptions();
  productContentMode.innerHTML=options.map((option,index)=>`<option value="${safeAttr(optionId(option,index))}">${safeAttr(optionLabel(option,index))} · ${safeAttr(optionPriceText(option))}</option>`).join('');
  productContentModes.innerHTML=options.map((option,index)=>`<button class="order-option-pill" type="button" role="radio" aria-checked="false" data-value="${safeAttr(optionId(option,index))}"><span>${safeAttr(optionLabel(option,index))}</span><span class="order-option-price">${safeAttr(optionPriceText(option))}</span></button>`).join('');
  productContentMode.value=options.some((option,index)=>optionId(option,index)==='artee-design')?'artee-design':optionId(options[0],0);
  updateProductContentFields();
}
function displayMoney(value){return money(catalogNumber(value))}
function catalogNumber(value){const n=parseFloat(String(value||'').replace(/[^\d.]/g,''));return Number.isFinite(n)?n:0}
function catalogStatusLabel(status){const ar={none:'',available:'',coming:'قريبًا',sale:'خصم',soldout:'نفدت الكمية'};const en={none:'',available:'',coming:'Soon',sale:'Sale',soldout:'Sold out'};const labels=isAr?ar:en;return Object.prototype.hasOwnProperty.call(labels,status)?labels[status]:''}
function effectiveCatalogPrice(item){
  // list.php has already selected sale_price/base_price and rounded it to the
  // database currency precision. Discount fields are display metadata only.
  return roundMoney(item?.effectivePrice??item?.price??item?.salePrice??0);
}
function readClientCatalog(){try{return JSON.parse(localStorage.getItem('arteeCatalog')||'{}')}catch(e){return {}}}
const ARTEE_API_BASE=(location.protocol==='file:'?'https://artee.com.sa':location.origin).replace(/\/$/,'')+'/backend/api';
function arteeAuthToken(){return localStorage.getItem('arteeAuthToken')||sessionStorage.getItem('arteeAuthToken')||'';}
async function arteeApi(path,options={}){
  const headers={'Content-Type':'application/json',...(options.headers||{})};
  const token=arteeAuthToken();
  if(token)headers.Authorization=`Bearer ${token}`;
  const response=await fetch(`${ARTEE_API_BASE}${path}`,{
    method:options.method||'GET',
    credentials:'same-origin',
    cache:'no-store',
    headers,
    body:options.body?JSON.stringify(options.body):undefined
  });
  const raw=await response.text();
  let data={};
  try{data=raw?JSON.parse(raw):{};}catch(error){data={ok:false,message:raw||'Invalid API response'};}
  if(!response.ok||data.ok===false)throw new Error(data.message||`API ${response.status}`);
  return data;
}
async function loadBackendCustomerProfile(){
  if(location.protocol==='file:')return true;
  if(!arteeAuthToken())return false;
  try{
    const data=await arteeApi('/account/profile.php');
    const current=getCustomer()||{},address=data.defaultAddress||{};
    saveCustomerProfile({...current,
      id:data.user?.id??current.id,uuid:data.user?.uuid||current.uuid,role:data.user?.role||'customer',
      name:data.user?.fullName||data.user?.full_name||current.name,email:data.user?.email||current.email,
      phoneCountryCode:data.user?.phoneCountryCode||data.user?.phone_country_code||current.phoneCountryCode||'+966',
      phone:data.user?.phone||current.phone,addressId:address.id||null,country:address.country||current.country||'Saudi Arabia',
      shippingRegion:address.region||'',city:address.city||current.city||'',shippingDistrict:address.district||'',
      shippingStreet:address.street||'',shippingBuilding:address.buildingNumber||'',shippingPostal:address.postalCode||'',
      shippingShortAddress:address.shortAddress||'',shippingAddress:address.address||'',
      shippingRecipient:address.recipientName||'',shippingPhone:address.phone||''
    });
    return true;
  }catch(error){console.warn('Customer profile API load failed',error);return false}
}
function applyPublicSiteSettings(settings={}){
  window.__arteeSiteSettings=settings;
  const preset=settings.themePreset||'default';
  const primary=settings.primaryColor||'#7C7454';
  const accent=settings.accentColor||'#E0DCCD';
  const background=settings.backgroundColor||'#232323';
  document.documentElement.style.setProperty('--gold',primary);
  document.documentElement.style.setProperty('--beige',accent);
  document.body.style.setProperty('--bg-hero',background);
  document.body.style.setProperty('--bg-about',background);
  document.body.style.setProperty('--bg-services',background);
  document.body.style.setProperty('--nav-bg',background+'F5');
  document.body.dataset.siteTheme=preset;
  const title=(isAr?settings.siteTitleAr:settings.siteTitleEn)||'ARTEE';
  document.title=title+' | '+(isAr?'نحوّل الخيال إلى واقع':'From Imagination to Reality');
  const logo=settings.siteLogo||'artee-logo.png';
  document.querySelectorAll('img.brand-logo,img.logo,img[alt="ARTEE"]').forEach(image=>{image.src=logo});
  const favicon=settings.favicon||logo;
  let icon=document.querySelector('link[rel~="icon"]');if(!icon){icon=document.createElement('link');icon.rel='icon';document.head.appendChild(icon)}icon.href=favicon;
  const description=(isAr?settings.metaDescriptionAr:settings.metaDescriptionEn)||'';
  const setMeta=(selector,attribute,value)=>{let meta=document.head.querySelector(selector);if(!meta){meta=document.createElement('meta');const pair=selector.match(/^meta\[(name|property)="([^"]+)"\]$/);if(pair)meta.setAttribute(pair[1],pair[2]);document.head.appendChild(meta)}meta.setAttribute(attribute,value)};
  setMeta('meta[name="description"]','content',description);
  setMeta('meta[property="og:title"]','content',document.title);
  setMeta('meta[property="og:description"]','content',description);
  setMeta('meta[property="og:image"]','content',new URL(settings.socialImage||logo,location.origin+'/').href);
  setMeta('meta[property="og:type"]','content','website');
  setMeta('meta[property="og:url"]','content',location.origin+'/');
  setMeta('meta[name="twitter:card"]','content','summary_large_image');
  const announcement=document.getElementById('siteAnnouncement');
  const announcementText=isAr?settings.announcementAr:settings.announcementEn;
  const show=Boolean(settings.announcementEnabled&&String(announcementText||'').trim());
  if(announcement){announcement.textContent=announcementText||'';announcement.hidden=!show;announcement.dir=isAr?'rtl':'ltr'}
  document.body.classList.toggle('site-announcement-active',show);
}
async function loadPublicSiteSettings(){
  try{
    const response=await fetch(`${ARTEE_API_BASE}/settings/site.php`,{credentials:'same-origin',cache:'no-store',headers:{Accept:'application/json'}});
    const data=await response.json();
    if(response.ok&&data.ok)applyPublicSiteSettings(data.settings||{});
  }catch(error){console.warn('Site settings fallback',error)}
}
async function loadBackendCatalog(){
  try{
    const data=await arteeApi('/catalog/list.php');
    if(data.ok){
      const snapshot={services:data.services||[],products:data.products||[]};
      window.__arteeBackendCatalog=snapshot;
      // Local file demonstrations may retain a snapshot. Hosted checkout uses
      // only this request's live API response and therefore fails closed when
      // an authoritative refresh is unavailable.
      if(location.protocol==='file:')localStorage.setItem('arteeCatalog',JSON.stringify(snapshot));
      return true;
    }
  }catch(error){console.warn('Catalog API fallback',error);}
  return false;
}
function backendOptionPayload(option){
  if(!option)return null;
  return {
    id:optionId(option),
    backendId:Array.isArray(option)?null:(option.id||null),
    key:Array.isArray(option)?option[0]:(option.key||option.modeKey||null),
    label:optionLabel(option),
    labelAr:Array.isArray(option)?option[1]:(option.labelAr||option.label||''),
    labelEn:Array.isArray(option)?option[1]:(option.labelEn||option.label||''),
    priceDelta:optionExtra(option),
    priceExtra:optionExtra(option)
  };
}
function backendOrderItemPayload(item){
  const selectedOptions=[];
  (Array.isArray(item.selections)?item.selections:(item.selection?[item.selection]:[])).forEach(option=>selectedOptions.push({group:'product_option',...option}));
  if(item.contentSelection)selectedOptions.push({group:'nfc_design',...item.contentSelection});
  return {
    ...item,
    backendId:item.backendId||item.catalogItemId||item.catalogId||null,
    catalogItemId:item.catalogItemId||item.backendId||item.catalogId||null,
    uuid:item.catalogUuid||item.uuid||null,
    itemType:item.type||item.itemType||'service',
    name:item.service||item.name,
    nameAr:item.serviceAr||item.nameAr||item.service||item.name,
    nameEn:item.serviceEn||item.nameEn||item.serviceAr||item.service||item.name,
    description:item.descriptionAr||item.description||item.message||'',
    unitPrice:catalogNumber(item.clientPrice||item.total||item.price),
    lineTotal:catalogNumber(item.total||item.clientPrice||item.price),
    selectedOptions,
    serviceDescription:(item.type||item.itemType)==='product'
      ?(item.contentBrief||item.serviceDescription||'')
      :(item.message||item.serviceDescription||item.description||''),
    nfcDesignMode:item.contentMode||item.nfcDesignMode||'none',
    linktreeUrl:item.contentLink||item.linktreeUrl||''
  };
}
async function syncOrderToBackend(order,items=[],shipping=null,required=false){
  try{
    if(!arteeAuthToken()){
      if(required)throw new Error(isAr?'انتهت جلسة الدخول. سجل الدخول ثم أعد المحاولة.':'Your session has expired. Sign in and try again.');
      return null;
    }
    const backendItems=(items.length?items:[order]).map(backendOrderItemPayload);
    const backendOrder={...order,items:backendItems};
    const data=await arteeApi('/orders/create.php',{method:'POST',body:{order:backendOrder,items:backendItems,shipping,idempotencyKey:order.idempotencyKey||''}});
    if(data.ok&&data.order){
      applyBackendOrderMeta(order,data.order);
      order.backendOrderSynced=true;
      return data.order;
    }
  }catch(error){
    console.warn('Order API fallback',error);
    if(required)throw error;
  }
  return null;
}
async function uploadOrderAttachments(orderId,files,orderItemId=null){
  const token=arteeAuthToken();
  if(!token||!orderId||!files.length)return [];
  const uploaded=[];
  for(const file of files){
    const form=new FormData();
    form.append('orderId',String(orderId));
    if(orderItemId)form.append('orderItemId',String(orderItemId));
    form.append('file',file,file.name);
    const response=await fetch(`${ARTEE_API_BASE}/orders/upload-attachment.php`,{method:'POST',credentials:'same-origin',cache:'no-store',headers:{Accept:'application/json',Authorization:`Bearer ${token}`},body:form});
    const raw=await response.text();
    let data={};
    try{data=raw?JSON.parse(raw):{}}catch(error){data={ok:false,message:raw||'Invalid API response'}}
    if(!response.ok||data.ok===false)throw new Error(data.message||`Attachment upload failed (${response.status})`);
    if(data.attachment)uploaded.push(data.attachment);
  }
  return uploaded;
}
async function attachmentUploadKey(checkoutKey,lineKey,attachment,file){
  const source=[checkoutKey,lineKey,attachment?.id||'',file.name,file.size,file.lastModified||0].join('|');
  if(!globalThis.crypto?.subtle)throw new Error(isAr?'المتصفح لا يدعم رفع المرفقات الآمن.':'This browser does not support secure attachment upload.');
  const digest=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(source));
  return [...new Uint8Array(digest)].map(byte=>byte.toString(16).padStart(2,'0')).join('');
}
async function stageCartAttachments(items,checkoutKey){
  const token=arteeAuthToken();
  if(!token)throw new Error(isAr?'انتهت جلسة الدخول. سجل الدخول ثم أعد المحاولة.':'Your session has expired. Sign in and try again.');
  const staged=[];
  for(let itemIndex=0;itemIndex<items.length;itemIndex+=1){
    const item=items[itemIndex]||{},attachmentTokens=[];
    const catalogItemId=item.catalogItemId||item.backendId||item.catalogId;
    for(const attachment of item.attachments||[]){
      const file=await storedAttachmentFile(attachment);
      if(!file)throw new Error(isAr?`تعذر قراءة المرفق ${attachment.name||''}. أعد اختياره.`:`Could not read attachment ${attachment.name||''}. Select it again.`);
      const lineKey=`line-${itemIndex+1}`,form=new FormData();
      form.append('catalogItemId',String(catalogItemId||''));form.append('checkoutKey',checkoutKey);form.append('lineKey',lineKey);
      form.append('uploadKey',await attachmentUploadKey(checkoutKey,lineKey,attachment,file));form.append('file',file,file.name);
      const response=await fetch(`${ARTEE_API_BASE}/orders/stage-attachment.php`,{method:'POST',credentials:'same-origin',cache:'no-store',headers:{Accept:'application/json',Authorization:`Bearer ${token}`},body:form});
      const raw=await response.text();let data={};try{data=raw?JSON.parse(raw):{}}catch(error){data={ok:false,message:raw||'Invalid API response'}}
      if(!response.ok||data.ok===false||!data.attachment?.token)throw new Error(data.message||`Attachment upload failed (${response.status})`);
      attachmentTokens.push(data.attachment.token);
    }
    staged.push({...item,attachmentTokens});
  }
  return staged;
}
async function discardStagedCheckout(checkoutKey){
  if(!arteeAuthToken()||!checkoutKey)return false;
  try{
    await arteeApi('/orders/discard-staged-attachments.php',{method:'POST',body:{checkoutKey}});
    return true;
  }catch(error){
    console.warn('Staged checkout cleanup deferred to expiry',error);
    return false;
  }
}
function applyBackendOrderMeta(order,backendOrder){
  if(!order||!backendOrder)return order;
  const orderNumber=backendOrder.orderNumber||backendOrder.order_number;
  const status=backendOrder.status==='review'?'offer_pending_owner':backendOrder.status;
  order.backendId=backendOrder.id;
  order.backendUuid=backendOrder.uuid||order.backendUuid;
  order.backendOrderNumber=orderNumber;
  if(orderNumber)order.id=orderNumber;
  order.status=status||order.status;
  order.type=(backendOrder.kind||backendOrder.order_kind||order.type)==='product'?'product':order.type;
  order.paymentPlan=backendOrder.paymentPlan||backendOrder.payment_plan||order.paymentPlan;
  order.paymentStatus=backendOrder.paymentStatus||order.paymentStatus||'';
  order.invoiceId=backendOrder.invoiceNumber||backendOrder.invoice?.number||order.invoiceId||'';
  order.invoiceIssuedAt=backendOrder.invoice?.issuedAt||order.invoiceIssuedAt||'';
  if(backendOrder.shipping!==undefined)order.shippingAmount=money(backendOrder.shipping);
  if(backendOrder.paid!==undefined)order.paidAmount=Number(backendOrder.paid)||0;
  if(backendOrder.due!==undefined)order.dueAmount=Number(backendOrder.due)||0;
  if(backendOrder.subtotal!==undefined&&(order.type==='product'||Number(backendOrder.subtotal)>0))order.subtotal=money(backendOrder.subtotal);
  if(backendOrder.taxIncluded!==undefined&&(order.type==='product'||Number(backendOrder.taxIncluded)>0))order.taxAmount=money(backendOrder.taxIncluded);
  if(backendOrder.total!==undefined&&(order.type==='product'||Number(backendOrder.total)>0))order.clientPrice=money(backendOrder.total);
  if(backendOrder.total!==undefined&&(order.type==='product'||Number(backendOrder.total)>0))order.total=money(backendOrder.total);
  return order;
}
function fallbackCatalog(type){
  const panel=document.querySelector(`.switch-panel[data-panel="${type}"]`);
  return [...(panel?.querySelectorAll('.service-item')||[])].map((card,index)=>{
    const name=card.querySelector('.si-title')?.textContent.trim()||`Item ${index+1}`;
    const product=productCatalog[name]||{};
    return {id:`${type}-${index+1}`,name,nameAr:name,nameEn:name,description:card.querySelector('.si-body')?.textContent.trim()||'',descriptionAr:card.querySelector('.si-body')?.textContent.trim()||'',descriptionEn:card.querySelector('.si-body')?.textContent.trim()||'',image:product.image||serviceVisuals[name]||'artee-logo.png',price:product.price||'',optionGroups:product.optionGroups||[],options:product.options||[],designOptions:product.designOptions||[],hasChoices:!!product.options?.length,hasDesign:product.productMode==='smart-card',productMode:product.productMode||defaultProductMode({name,options:product.options}),icon:defaultCatalogIcon({id:`${type}-${index+1}`,name},type),active:true,status:'none',shippingMode:'manual'};
  });
}
function clientCatalogItems(type){const source=location.protocol==='file:'?readClientCatalog():window.__arteeBackendCatalog;const stored=source?.[type];const fallback=location.protocol==='file:'?fallbackCatalog(type):[];return (Array.isArray(stored)?stored:fallback).filter(item=>item.active!==false)}
function catalogCardHtml(item,index,type){
  const rawStatus=item.statusEnabled===false?'none':(item.status||'none');
  const status=rawStatus;
  const isProduct=type==='products';
  const productMode=item.hasDesign===false?(item.hasChoices===false?'direct':'materials'):(item.productMode||defaultProductMode(item));
  const icon=item.icon||defaultCatalogIcon(item,type);
  const name=itemName(item);
  const description=itemDescription(item);
  const nameAr=item.nameAr||item.name||name;
  const nameEn=item.nameEn||nameAr;
  const descriptionAr=item.descriptionAr||item.description||description;
  const descriptionEn=item.descriptionEn||descriptionAr;
  const oldPrice=status==='sale'&&item.oldPrice?`<span class="si-old-price">${safeAttr(displayMoney(item.oldPrice))}</span>`:'';
  const finalPrice=effectiveCatalogPrice(item);
  const hidePrice=status==='coming';
  const price=!hidePrice&&finalPrice?`<div class="si-price">${oldPrice}<strong>${safeAttr(displayMoney(finalPrice))}</strong></div>`:'';
  const statusLabel=catalogStatusLabel(status);
  const statusTag=statusLabel?`<span class="si-status-orb ${status}">${statusLabel}</span>`:'';
  const image=safeAttr(item.image||'artee-logo.png');
  return `<article class="service-item ${status==='soldout'?'is-soldout':''} ${status==='coming'?'is-coming':''}" data-catalog-type="${safeAttr(type)}" data-catalog-id="${safeAttr(item.id||'')}" data-catalog-uuid="${safeAttr(item.id||'')}" data-backend-id="${safeAttr(item.backendId||'')}" data-name-ar="${safeAttr(nameAr)}" data-name-en="${safeAttr(nameEn)}" data-description-ar="${safeAttr(descriptionAr)}" data-description-en="${safeAttr(descriptionEn)}" data-status="${safeAttr(status)}" data-image="${image}" data-price="${safeAttr(finalPrice)}" data-old-price="${safeAttr(catalogNumber(item.oldPrice))}" data-tax-enabled="${item.taxEnabled===false?'false':'true'}" data-shipping-mode="${safeAttr(item.shippingMode||'manual')}" data-product-mode="${safeAttr(productMode)}" data-icon="${safeAttr(icon)}">${statusTag}<div class="si-head"><div class="si-icon">${catalogIconSvg(icon)}</div><img class="si-thumb" src="${image}" alt="" loading="lazy"/></div><p class="si-num">${String(index+1).padStart(2,'0')}</p><h3 class="si-title">${safeAttr(name)}</h3><p class="si-body">${safeAttr(description||'')}</p>${price}</article>`;
}
function renderClientCatalog(){
  const services=clientCatalogItems('services'),products=clientCatalogItems('products');
  const servicesGrid=document.querySelector('.switch-panel[data-panel="services"] .items-grid');
  const productsGrid=document.querySelector('.switch-panel[data-panel="products"] .items-grid');
  if(servicesGrid)servicesGrid.innerHTML=services.map((item,index)=>catalogCardHtml(item,index,'services')).join('');
  if(productsGrid)productsGrid.innerHTML=products.map((item,index)=>catalogCardHtml(item,index,'products')).join('');
  const serviceCount=document.querySelector('.switch-panel[data-panel="services"] .switch-count');
  const productCount=document.querySelector('.switch-panel[data-panel="products"] .switch-count');
  if(serviceCount)serviceCount.textContent=isAr?`${services.length} خدمات إبداعية`:`${services.length} creative services`;
  if(productCount)productCount.textContent=isAr?`${products.length} منتجات ذكية`:`${products.length} smart products`;
  const visibleProducts=[];
  products.forEach(item=>{const hasDesign=item.hasDesign===false?false:(item.hasDesign||defaultProductMode(item)==='smart-card');const groups=Array.isArray(item.optionGroups)?item.optionGroups:[];const hasChoices=item.hasChoices!==false&&(groups.length>0||!!(item.options||[]).length);const shippingMode=item.shippingMode||'manual';const entry={id:item.id||'',uuid:item.id||'',backendId:item.backendId||null,catalogItemId:item.backendId||null,active:item.active!==false,nameAr:item.nameAr||item.name,nameEn:item.nameEn||item.nameAr||item.name,descriptionAr:item.descriptionAr||item.description,descriptionEn:item.descriptionEn||item.descriptionAr||item.description,price:effectiveCatalogPrice(item),effectivePrice:effectiveCatalogPrice(item),image:item.image||'artee-logo.png',optionGroups:hasChoices?groups:[],options:hasChoices?(item.options||[]):[],designOptions:hasDesign?(item.designOptions||[]):[],hasChoices,hasDesign,productMode:hasDesign?'smart-card':(hasChoices?'materials':'direct'),status:item.statusEnabled===false?'none':(item.status||'none'),statusEnabled:item.statusEnabled!==false,shippingMode,requiresShipping:item.requiresShipping!==false&&shippingMode!=='none',taxEnabled:item.taxEnabled!==false,icon:item.icon||defaultCatalogIcon(item,'products')};visibleProducts.push(entry);[item.name,item.nameAr,item.nameEn].filter(Boolean).forEach(name=>{productCatalog[name]=entry})});
  window.__arteeVisibleProducts=visibleProducts;
  services.forEach(item=>{[item.name,item.nameAr,item.nameEn].filter(Boolean).forEach(name=>{serviceVisuals[name]=item.image||'artee-logo.png'})});
  revealActiveCatalogCards();
}
function revealActiveCatalogCards(){
  requestAnimationFrame(()=>{
    document.querySelectorAll('.switch-panel.active .service-item').forEach(item=>item.classList.add('revealed'));
  });
}
function bindCatalogCards(){
  document.querySelectorAll('.service-item').forEach(item=>{
    if(item.dataset.bound==='true')return;
    item.dataset.bound='true';
    item.addEventListener('click',()=>handleCatalogClick(item));
  });
}
function handleCatalogClick(item){
  const status=item.dataset.status||'none';
  if(['coming','soldout'].includes(status)){
    handleUnavailableCatalogItem(item,status);
    return;
  }
  openOrder(item);
}
function handleUnavailableCatalogItem(item,status){
  const customer=getCustomer();
  const serviceName=item.querySelector('.si-title')?.textContent.trim()||'ARTEE';
  if(!customer){
    localStorage.setItem('arteePendingOrder',serviceName);
    location.href='login.html?mode=login&next=order';
    return;
  }
  activeNotifyItem={
    type:item.dataset.catalogType||'item',
    backendId:item.dataset.backendId||null,
    catalogItemId:item.dataset.backendId||null,
    catalogUuid:item.dataset.catalogUuid||item.dataset.catalogId||'',
    name:serviceName,
    nameAr:item.dataset.nameAr||serviceName,
    nameEn:item.dataset.nameEn||serviceName,
    status
  };
  openNotifyModal(activeNotifyItem);
}
async function openNotifyModal(item){
  if(!notifyModal)return;
  const name=isAr?(item.nameAr||item.name):(item.nameEn||item.nameAr||item.name);
  notifyTitle.textContent=isAr?'تنبيه التوفر':'Availability Alert';
  notifySub.textContent=isAr?'جارٍ التحقق من حالة التنبيه...':'Checking alert status...';
  notifyConfirm.textContent=isAr?'جارٍ التحميل...':'Loading...';
  notifyConfirm.disabled=true;
  notifyCancel.textContent=isAr?'إغلاق':'Close';
  notifyModal.classList.add('open');
  notifyModal.setAttribute('aria-hidden','false');
  try{
    const state=await availabilityAlertStatus(item);
    if(activeNotifyItem!==item)return;
    activeNotifySubscribed=state.subscribed===true;
    notifySub.textContent=activeNotifySubscribed?(isAr?`لديك تنبيه نشط لـ ${name}. يمكنك إلغاؤه الآن.`:`You have an active alert for ${name}. You can cancel it now.`):(isAr?`هل تريد أن نرسل لك تنبيهًا عند توفر ${name}؟`:`Would you like us to notify you when ${name} is available?`);
    notifyConfirm.textContent=activeNotifySubscribed?(isAr?'إلغاء التنبيه':'Unsubscribe'):(isAr?'نعم، نبهني':'Yes, notify me');
  }catch(error){notifySub.textContent=error.message||(isAr?'تعذر تحميل حالة التنبيه.':'Could not load alert status.')}finally{notifyConfirm.disabled=false}
}
function closeNotifyModal(){
  notifyModal?.classList.remove('open');
  notifyModal?.setAttribute('aria-hidden','true');
  activeNotifyItem=null;
  activeNotifySubscribed=false;
}
async function confirmNotifyAlert(){
  if(!activeNotifyItem)return;
  notifyConfirm.disabled=true;
  try{
    if(activeNotifySubscribed){
      await cancelAvailabilityAlert(activeNotifyItem);
      activeNotifySubscribed=false;
      notifySub.textContent=isAr?'تم إلغاء تنبيه التوفر.':'Availability alert cancelled.';
    }else{
      await saveAvailabilityAlert(activeNotifyItem);
      activeNotifySubscribed=true;
      notifySub.textContent=isAr?'تم حفظ التنبيه. سنشعرك عند توفر هذا العنصر.':'Alert saved. We will notify you when this item becomes available.';
    }
    updateNavNotifications(getCustomer());
    setTimeout(()=>{
      notifyConfirm.disabled=false;
      closeNotifyModal();
    },700);
  }catch(error){
    notifySub.textContent=error.message||(isAr?'تعذر حفظ التنبيه. حاول مرة أخرى.':'Could not save the alert. Please try again.');
    notifyConfirm.disabled=false;
  }
}
function openAttachmentDb(){
  return new Promise((resolve,reject)=>{
    const request=indexedDB.open(ATTACHMENT_DB,1);
    request.onupgradeneeded=()=>{if(!request.result.objectStoreNames.contains(ATTACHMENT_STORE))request.result.createObjectStore(ATTACHMENT_STORE,{keyPath:'id'});};
    request.onsuccess=()=>resolve(request.result);
    request.onerror=()=>reject(request.error);
  });
}
function attachmentOwnerKey(customer=getCustomer()){
  return String(customer?.id||customer?.uuid||customer?.email||'').trim().toLowerCase();
}
function collectStoredAttachmentIds(value,result=new Set()){
  if(Array.isArray(value)){value.forEach(item=>collectStoredAttachmentIds(item,result));return result;}
  if(!value||typeof value!=='object')return result;
  const id=String(value.id||'');
  if(id&&(value.stored===true||/^(?:ATT-|artee-file-)/.test(id)))result.add(id);
  ['attachments','previewFile','approvedPreviewFile','finalFile','items'].forEach(key=>collectStoredAttachmentIds(value[key],result));
  return result;
}
function attachmentRecordCreatedAt(record){
  const explicit=Date.parse(record?.createdAt||'');
  if(Number.isFinite(explicit))return explicit;
  const match=String(record?.id||'').match(/^(?:ATT-|artee-file-)([a-z0-9]+)-/i);
  if(!match)return 0;
  const parsed=parseInt(match[1],36);
  return Number.isFinite(parsed)&&parsed>946684800000&&parsed<Date.now()+86400000?parsed:0;
}
function activeStoredAttachmentIds(){
  const active=collectStoredAttachmentIds(readCart());
  try{collectStoredAttachmentIds(JSON.parse(localStorage.getItem('arteeDemoRequests')||'[]'),active);}catch(error){}
  try{collectStoredAttachmentIds(JSON.parse(localStorage.getItem('arteeFreelancerOffers')||'[]'),active);}catch(error){}
  return active;
}
async function deleteStoredAttachmentIds(ids,{ownerKey=attachmentOwnerKey(),allowLegacy=false,activeIds=new Set()}={}){
  const targets=new Set([...ids].map(String).filter(Boolean));
  if(!targets.size)return 0;
  const db=await openAttachmentDb();
  return new Promise((resolve,reject)=>{
    let deleted=0;
    const tx=db.transaction(ATTACHMENT_STORE,'readwrite'),store=tx.objectStore(ATTACHMENT_STORE);
    targets.forEach(id=>{
      if(activeIds.has(id))return;
      const request=store.get(id);
      request.onsuccess=()=>{
        const record=request.result;
        if(!record)return;
        const recordOwner=String(record.ownerKey||'').toLowerCase();
        if((recordOwner&&recordOwner!==ownerKey)||(!recordOwner&&!allowLegacy))return;
        store.delete(id);deleted+=1;
      };
    });
    tx.oncomplete=()=>resolve(deleted);
    tx.onerror=()=>reject(tx.error);
    tx.onabort=()=>reject(tx.error);
  });
}
async function pruneStoredAttachments({ownerKey=attachmentOwnerKey(),now=Date.now()}={}){
  const activeIds=activeStoredAttachmentIds(),db=await openAttachmentDb();
  return new Promise((resolve,reject)=>{
    let deleted=0;
    const tx=db.transaction(ATTACHMENT_STORE,'readwrite'),store=tx.objectStore(ATTACHMENT_STORE),cursor=store.openCursor();
    cursor.onsuccess=()=>{
      const item=cursor.result;
      if(!item)return;
      const record=item.value||{},id=String(record.id||''),recordOwner=String(record.ownerKey||'').toLowerCase();
      const createdAt=attachmentRecordCreatedAt(record),expired=createdAt>0&&now-createdAt>ATTACHMENT_MAX_AGE_MS;
      if(!activeIds.has(id)&&expired&&(!recordOwner||recordOwner===ownerKey)){item.delete();deleted+=1;}
      item.continue();
    };
    tx.oncomplete=()=>resolve(deleted);
    tx.onerror=()=>reject(tx.error);
    tx.onabort=()=>reject(tx.error);
  });
}
async function fileToAttachment(file){
  const id='ATT-'+Date.now().toString(36)+'-'+Math.random().toString(36).slice(2,8);
  const db=await openAttachmentDb();
  return new Promise((resolve,reject)=>{
    const tx=db.transaction(ATTACHMENT_STORE,'readwrite');
    tx.objectStore(ATTACHMENT_STORE).put({id,name:file.name,size:file.size,type:file.type,blob:file,ownerKey:attachmentOwnerKey(),purpose:'checkout',createdAt:new Date().toISOString()});
    tx.oncomplete=()=>resolve({id,name:file.name,size:file.size,type:file.type,stored:true});
    tx.onerror=()=>reject(tx.error);
  });
}
async function storedAttachmentFile(attachment){
  if(!attachment?.id)return null;
  const db=await openAttachmentDb();
  return new Promise((resolve,reject)=>{
    const tx=db.transaction(ATTACHMENT_STORE,'readonly');
    const request=tx.objectStore(ATTACHMENT_STORE).get(attachment.id);
    request.onsuccess=()=>{
      const record=request.result;
      const recordOwner=String(record?.ownerKey||'').toLowerCase();
      if(!record?.blob||(recordOwner&&recordOwner!==attachmentOwnerKey())){resolve(null);return;}
      resolve(new File([record.blob],record.name||attachment.name||'attachment',{type:record.type||record.blob.type||'application/octet-stream'}));
    };
    request.onerror=()=>reject(request.error);
  });
}
async function uploadCartAttachments(orderId,items=[],backendItems=[]){
  const uploaded=[];
  for(let itemIndex=0;itemIndex<items.length;itemIndex+=1){
    const item=items[itemIndex]||{};
    const files=[];
    for(const attachment of item.attachments||[]){
      const file=await storedAttachmentFile(attachment);
      if(file){
        const prefix=`product-${itemIndex+1}-`;
        files.push(new File([file],prefix+file.name,{type:file.type||'application/octet-stream'}));
      }
    }
    if(files.length)uploaded.push(...await uploadOrderAttachments(orderId,files,backendItems[itemIndex]?.id||null));
  }
  return uploaded;
}
// Keep active cart/demo references, but age out unreferenced records from this
// account (and safely identifiable legacy records) on ordinary page visits.
void pruneStoredAttachments().catch(error=>console.warn('Attachment cache cleanup deferred',error));

function showOrderModal(sourceItem){
  const sourceElement=sourceItem instanceof Element?sourceItem:null;
  const reduceMotion=window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  if(!sourceElement||reduceMotion||!sourceElement.getBoundingClientRect){
    orderModal.classList.add('open');
    orderModal.setAttribute('aria-hidden','false');
    return;
  }

  const sourceRect=sourceElement.getBoundingClientRect();
  const sourceCenterX=sourceRect.left+(sourceRect.width/2);
  const sourceCenterY=sourceRect.top+(sourceRect.height/2);
  const startX=(sourceCenterX-(window.innerWidth/2))*.10;
  const startY=(sourceCenterY-(window.innerHeight/2))*.08;
  const originX=Math.max(12,Math.min(88,(sourceCenterX/window.innerWidth)*100));
  const originY=Math.max(12,Math.min(88,(sourceCenterY/window.innerHeight)*100));

  orderDialog.style.setProperty('--order-start-x',startX.toFixed(1)+'px');
  orderDialog.style.setProperty('--order-start-y',startY.toFixed(1)+'px');
  orderDialog.style.setProperty('--order-origin-x',originX.toFixed(1)+'%');
  orderDialog.style.setProperty('--order-origin-y',originY.toFixed(1)+'%');
  sourceElement.classList.add('is-soft-source');

  window.setTimeout(()=>{
    orderModal.classList.add('open','soft-opening');
    orderModal.setAttribute('aria-hidden','false');
    window.setTimeout(()=>sourceElement.classList.remove('is-soft-source'),380);
    window.setTimeout(()=>orderModal.classList.remove('soft-opening'),680);
  },90);
}

function openOrder(item){
  const customer=getCustomer();
  const serviceName=typeof item==='string'?item:item.querySelector('.si-title')?.textContent.trim()||'الخدمة';
  const description=typeof item==='string'?'':item.querySelector('.si-body')?.textContent.trim()||'';
  const panel=typeof item==='string'?null:item.closest('.switch-panel');
  const sourceStatus=typeof item==='string'?'none':(item.dataset.status||'none');
  const sourceImage=typeof item==='string'?'':item.dataset.image;
  const kind=(productCatalog[serviceName]||panel?.dataset.panel==='products')?'product':'service';
  if(!customer){
    localStorage.setItem('arteePendingOrder',serviceName);
    location.href='login.html?mode=login&next=order';
    return;
  }
  const product=productCatalog[serviceName]||null;
  const sourceNameAr=typeof item==='string'?(product?.nameAr||serviceName):(item.dataset.nameAr||serviceName);
  const sourceNameEn=typeof item==='string'?(product?.nameEn||sourceNameAr):(item.dataset.nameEn||sourceNameAr);
  const sourceDescriptionAr=typeof item==='string'?(product?.descriptionAr||description):(item.dataset.descriptionAr||description);
  const sourceDescriptionEn=typeof item==='string'?(product?.descriptionEn||sourceDescriptionAr):(item.dataset.descriptionEn||sourceDescriptionAr);
  activeOrderData={
    type:kind,
    catalogUuid:typeof item==='string'?(product?.uuid||product?.id||''):(item.dataset.catalogUuid||item.dataset.catalogId||product?.uuid||product?.id||''),
    backendId:typeof item==='string'?(product?.backendId||product?.catalogItemId||null):(item.dataset.backendId||product?.backendId||product?.catalogItemId||null),
    catalogItemId:typeof item==='string'?(product?.catalogItemId||product?.backendId||null):(item.dataset.backendId||product?.catalogItemId||product?.backendId||null),
    name:serviceName,
    nameAr:sourceNameAr,
    nameEn:sourceNameEn,
    description,
    descriptionAr:sourceDescriptionAr,
    descriptionEn:sourceDescriptionEn,
    image:sourceImage||product?.image||serviceVisuals[serviceName]||'artee-logo.png',
    price:product?.price||0,
    optionGroups:product?.optionGroups||[],
    options:product?.options||[],
    designOptions:product?.designOptions||[],
    hasChoices:product?.hasChoices!==false,
    hasDesign:product?.hasDesign||product?.productMode==='smart-card',
    productMode:product?.productMode||(typeof item==='string'?'direct':item.dataset.productMode)||defaultProductMode({name:serviceName,options:product?.options||[]}),
    status:sourceStatus,
    taxEnabled:typeof item==='string'?product?.taxEnabled!==false:item.dataset.taxEnabled!=='false',
    shippingMode:typeof item==='string'?(product?.shippingMode||'manual'):(item.dataset.shippingMode||product?.shippingMode||'manual'),
    requiresShipping:typeof item==='string'?(product?.requiresShipping!==false):(item.dataset.shippingMode!=='none'&&product?.requiresShipping!==false)
  };
  orderService.value=serviceName;
  orderType.value=kind;
  orderModal.dataset.orderKind=kind;
  orderTitle.textContent=kind==='product'?(isAr?'إضافة '+serviceName:'Add '+serviceName):(isAr?'طلب '+serviceName:'Request '+serviceName);
  orderDesc.textContent=kind==='product'?(isAr?'راجع تفاصيل المنتج واختر المواصفات المناسبة قبل الإضافة.':'Review the product details and choose the suitable option.'):(isAr?'اكتب تفاصيل الخدمة المطلوبة وأرفق أي ملفات تساعدنا نفهم المطلوب.':'Describe the service and attach any helpful files.');
  orderLongDesc.textContent=description||orderDesc.textContent;
  orderMeta.innerHTML='';
  orderImage.classList.toggle('has-image',!!activeOrderData.image);
  orderImageSrc.src=activeOrderData.image;
  orderImageSrc.alt=serviceName;
  orderMessageWrap.classList.toggle('order-hidden',kind==='product');
  orderAttachmentWrap.classList.toggle('order-hidden',kind==='product');
  productConfigWrap.classList.add('order-hidden');
  orderShippingWrap.classList.add('order-hidden');
  orderSubmit.dataset.requireShipping=activeOrderData.requiresShipping?'true':'false';
  orderMessageWrap.classList.remove('order-error');
  orderAttachmentWrap.classList.remove('order-error');
  productContentBriefWrap.classList.remove('order-error');
  productLinkWrap.classList.remove('order-error');
  orderShippingWrap.querySelectorAll('label').forEach(label=>label.classList.remove('order-error'));
  orderNote.classList.remove('order-note-error');
  orderMessage.value='';
  orderAttachment.value='';
  productContentBrief.value='';
  productLink.value='';
  const hasSavedShipping=!!customer.shippingAddress;
  orderShippingTitle.textContent=kind==='product'&&hasSavedShipping?(isAr?'مراجعة عنوان الشحن':'Review Shipping Address'):(isAr?'عنوان الشحن للمنتج':'Product Shipping Address');
  orderShippingHint.textContent=kind==='product'&&hasSavedShipping
    ?(isAr?'سنستخدم عنوانك المحفوظ. يمكنك تعديله هنا أو كتابة عنوان جديد قبل الدفع.':'We will use your saved address. You can edit it here or enter a new one before payment.')
    :(isAr?'أكمل بيانات الشحن المطلوبة قبل إتمام الدفع وطلب المنتج.':'Complete the required shipping details before payment.');
  shippingName.value=customer.name||'';
  shippingPhone.value=customer.phone||'';
  shippingRegion.value=customer.shippingRegion||customer.region||'منطقة الرياض';
  shippingCity.value=customer.city||'الرياض';
  shippingDistrict.value=customer.shippingDistrict||customer.district||'';
  shippingStreet.value=customer.shippingStreet||'';
  shippingBuilding.value=customer.shippingBuilding||'';
  shippingPostal.value=customer.shippingPostal||'';
  shippingShortAddress.value=customer.shippingShortAddress||'';
  shippingAddress.value=customer.shippingAddress||'';
  shippingNotes.value=customer.shippingNotes||'';
  orderOption.innerHTML='';
  orderOptions.innerHTML='';
  orderQuantity.value='1';
  orderQuantityWrap.classList.toggle('order-hidden',kind!=='product');
  const activeGroups=kind==='product'?productOptionGroups(activeOrderData):[];
  if(kind==='product'&&activeOrderData.hasChoices!==false&&activeGroups.length){
    orderOptionWrap.classList.remove('order-hidden');
    renderProductOptions(activeGroups);
  }else{
    orderOptionWrap.classList.add('order-hidden');
    activeProductOptionSelections=[];
    orderOptionGroups.innerHTML='';
  }
  if(kind==='product'&&(activeOrderData.hasDesign||activeOrderData.productMode==='smart-card')){
    renderProductContentModes();
  }
  if(kind==='product')updateProductPrice();else orderPrice.textContent='';
  orderSubmitting=false;
  const notifyOnly=['coming','soldout'].includes(sourceStatus);
  orderSubmit.disabled=false;
  orderSubmit.textContent=sourceStatus==='coming'?(isAr?'نبهني عند التوفر':'Notify Me'):sourceStatus==='soldout'?(isAr?'نبهني عند توفر الكمية':'Notify Me'):(kind==='product'?(isAr?'إضافة للسلة':'Add to Cart'):(isAr?'إرسال الطلب':'Send Request'));
  orderNote.textContent=notifyOnly?(sourceStatus==='soldout'?(isAr?'الكمية غير متوفرة حاليًا. اضغط الزر لنرسل لك تنبيهًا عند توفرها.':'This item is out of stock. Use the button to get notified when it returns.'):(isAr?'هذا العنصر قريبًا. اضغط الزر لنرسل لك تنبيهًا عند توفره.':'This item is coming soon. Use the button to get notified when it becomes available.')):(kind==='product'?(isAr?'أضف المنتج للسلة، وبعد مراجعة السلة يتم الدفع وإنشاء الطلب.':'Add the product to cart, then checkout creates the order.'):(isAr?'بيانات حسابك ستضاف تلقائيًا للطلب، ولا تحتاج لإدخال الاسم أو البريد أو رقم الجوال.':'Your account details are attached automatically; no need to enter name, email, or phone.'));
  showOrderModal(item);
}
function closeOrder(){
  orderModal.classList.remove('open');
  orderModal.classList.remove('soft-opening');
  orderModal.setAttribute('aria-hidden','true');
  orderSubmitting=false;
  orderSubmit.disabled=false;
  document.querySelectorAll('.service-item.is-soft-source').forEach(card=>card.classList.remove('is-soft-source'));
}
window.__arteeCatalogReady=true;
loadPublicSiteSettings();
renderClientCatalog();
bindCatalogCards();
loadBackendCustomerProfile().then(updated=>{if(updated)updateAccountUi(textMap[isAr?'ar':'en'])});
loadBackendCatalog().then(updated=>{if(updated){renderClientCatalog();bindCatalogCards();}});
orderClose.addEventListener('click',closeOrder);
orderModal.addEventListener('click',event=>{if(event.target===orderModal) closeOrder();});
document.getElementById('navCart')?.addEventListener('click',openCart);
document.getElementById('cartClose')?.addEventListener('click',closeCart);
document.getElementById('cartModal')?.addEventListener('click',event=>{if(event.target.id==='cartModal') closeCart();});
notifyConfirm?.addEventListener('click',confirmNotifyAlert);
notifyCancel?.addEventListener('click',closeNotifyModal);
notifyClose?.addEventListener('click',closeNotifyModal);
notifyModal?.addEventListener('click',event=>{if(event.target===notifyModal)closeNotifyModal()});
document.getElementById('cartList')?.addEventListener('click',event=>{
  const removeId=event.target.closest?.('[data-remove-cart]')?.dataset.removeCart;
  if(!removeId)return;
  const cart=readCart(),removed=cart.find(item=>(item.cartId||item.id)===removeId),remaining=cart.filter(item=>(item.cartId||item.id)!==removeId);
  saveCart(remaining);
  if(removed)void deleteStoredAttachmentIds(collectStoredAttachmentIds(removed),{ownerKey:attachmentOwnerKey(),allowLegacy:true,activeIds:activeStoredAttachmentIds()}).catch(()=>{});
  renderCart();
});
document.getElementById('cartCheckout')?.addEventListener('click',checkoutCart);
document.querySelectorAll('#cartShippingStep input').forEach(input=>{
  input.addEventListener('input',()=>{
    if(input.value.trim()){
      input.closest('label')?.classList.remove('order-error');
      input.removeAttribute('aria-invalid');
    }
    if(!document.querySelector('#cartShippingStep label.order-error')){
      const note=document.getElementById('cartShippingNote');
      if(note)note.textContent='';
    }
  });
});
orderOption.addEventListener('change',updateProductPrice);
orderOptionGroups.addEventListener('click',event=>{
  const clear=event.target.closest('[data-clear-group]');
  if(clear){
    activeProductOptionSelections=activeProductOptionSelections.filter(entry=>entry.groupKey!==clear.dataset.clearGroup);
    clear.closest('[data-option-group]')?.classList.remove('order-error');
    updateProductPrice();return;
  }
  const pill=event.target.closest('.order-option-pill');
  if(!pill)return;
  const groupKey=pill.dataset.groupKey;
  const groups=productOptionGroups(activeOrderData);
  const group=groups.find((candidate,index)=>optionGroupKey(candidate,index)===groupKey);
  const option=group?.options?.find((candidate,index)=>optionId(candidate,index)===pill.dataset.value);
  if(!group||!option)return;
  activeProductOptionSelections=activeProductOptionSelections.filter(entry=>entry.groupKey!==groupKey);
  activeProductOptionSelections.push({groupKey,group,option});
  orderOption.value=optionId(option);
  pill.closest('[data-option-group]')?.classList.remove('order-error');
  updateProductPrice();
});
productContentModes.addEventListener('click',event=>{
  const pill=event.target.closest('.order-option-pill');
  if(!pill)return;
  productContentMode.value=pill.dataset.value;
  updateProductContentFields();
});
productContentMode.addEventListener('change',updateProductContentFields);
orderQuantity.addEventListener('input',()=>{const value=Math.max(1,Math.min(99,Math.trunc(Number(orderQuantity.value)||1)));orderQuantity.value=String(value);updateProductPrice()});
productContentBrief.addEventListener('input',()=>{
  if(productContentBrief.value.trim()) productContentBriefWrap.classList.remove('order-error');
});
productLink.addEventListener('input',()=>{
  if(productLink.value.trim()) productLinkWrap.classList.remove('order-error');
});
orderMessage.addEventListener('input',()=>{
  if(orderMessage.value.trim()){
    orderMessageWrap.classList.remove('order-error');
    orderNote.classList.remove('order-note-error');
  }
});
orderAttachment.addEventListener('change',()=>{
  orderAttachmentWrap.classList.remove('order-error');
  orderNote.classList.remove('order-note-error');
});
orderShippingWrap.querySelectorAll('input').forEach(input=>{
  input.addEventListener('input',()=>{
    input.closest('label')?.classList.remove('order-error');
    orderNote.classList.remove('order-note-error');
  });
});
orderForm.addEventListener('submit',async event=>{
  event.preventDefault();
  if(orderSubmitting)return;
  const isServiceOrder=orderType.value!=='product';
  const messageValue=orderMessage.value.trim();
  const isSmartProduct=orderType.value==='product'&&(activeOrderData?.hasDesign||activeOrderData?.productMode==='smart-card');
  const productContentModeValue=isSmartProduct?(productContentMode.value||'artee-design'):'';
  const productBriefValue=isSmartProduct?productContentBrief.value.trim():'';
  const productLinkValue=isSmartProduct?productLink.value.trim():'';
  const shouldValidateAttachments=isServiceOrder||(isSmartProduct&&productContentModeValue!=='linktree');
  const selectedFiles=[...orderAttachment.files];
  if(['coming','soldout'].includes(activeOrderData?.status)){
    try{
      await saveAvailabilityAlert(activeOrderData);
      updateNavNotifications(getCustomer());
      orderNote.classList.remove('order-note-error');
      orderNote.textContent=isAr?'تم حفظ التنبيه. سنشعرك عند توفر هذا العنصر.':'Alert saved. We will notify you when this item becomes available.';
      orderSubmit.disabled=true;
      orderSubmit.textContent=isAr?'تم حفظ التنبيه':'Alert Saved';
      window.setTimeout(closeOrder,650);
    }catch(error){
      orderNote.classList.add('order-note-error');
      orderNote.textContent=error.message||(isAr?'تعذر حفظ التنبيه. حاول مرة أخرى.':'Could not save the alert. Please try again.');
    }
    return;
  }
  if(isServiceOrder&&!messageValue){
    orderMessageWrap.classList.add('order-error');
    orderNote.classList.add('order-note-error');
    orderNote.textContent=isAr?'يجب عليك كتابة وصف مختصر للخدمة المطلوبة قبل الإرسال.':'Please write a short description for the requested service before sending.';
    orderMessage.focus();
    return;
  }
  if(!isServiceOrder){
    const missingGroup=productOptionGroups(activeOrderData).find((group,index)=>group.required&&!activeProductOptionSelections.some(entry=>entry.groupKey===optionGroupKey(group,index)));
    if(missingGroup){
      const missingKey=optionGroupKey(missingGroup,productOptionGroups(activeOrderData).indexOf(missingGroup));
      orderOptionGroups.querySelector(`[data-option-group="${CSS.escape(missingKey)}"]`)?.classList.add('order-error');
      orderNote.classList.add('order-note-error');
      orderNote.textContent=isAr?'اختر قيمة لكل مجموعة خيارات مطلوبة.':'Select a value for every required option group.';
      orderOptionGroups.querySelector(`[data-option-group="${CSS.escape(missingKey)}"]`)?.scrollIntoView({block:'nearest'});
      return;
    }
  }
  if(isSmartProduct&&productContentModeValue==='linktree'&&!productLinkValue){
    productLinkWrap.classList.add('order-error');
    orderNote.classList.add('order-note-error');
    orderNote.textContent=isAr?'أضف رابط Linktree قبل إتمام طلب البطاقة.':'Add the Linktree link before placing the card order.';
    productLink.focus();
    return;
  }
  if(shouldValidateAttachments&&selectedFiles.length>MAX_ORDER_ATTACHMENTS){
    orderAttachmentWrap.classList.add('order-error');
    orderNote.classList.add('order-note-error');
    orderNote.textContent=isAr?'الحد الأقصى للمرفقات هو 4 ملفات فقط.':'You can attach up to 4 files only.';
    orderAttachment.focus();
    return;
  }
  const unsupportedFile=selectedFiles.find(file=>!ALLOWED_ATTACHMENT_EXTENSIONS.includes(fileExtension(file)));
  if(shouldValidateAttachments&&unsupportedFile){
    orderAttachmentWrap.classList.add('order-error');
    orderNote.classList.add('order-note-error');
    orderNote.textContent=isAr?`نوع الملف "${unsupportedFile.name}" غير مدعوم. استخدم صورًا أو PDF أو ZIP/RAR.`:`"${unsupportedFile.name}" is not supported. Use images, PDF, or ZIP/RAR.`;
    orderAttachment.focus();
    return;
  }
  const oversizedFile=selectedFiles.find(file=>file.size>MAX_ATTACHMENT_SIZE);
  if(shouldValidateAttachments&&oversizedFile){
    orderAttachmentWrap.classList.add('order-error');
    orderNote.classList.add('order-note-error');
    orderNote.textContent=isAr?`حجم الملف "${oversizedFile.name}" أكبر من 25MB.`:`"${oversizedFile.name}" is larger than 25MB.`;
    orderAttachment.focus();
    return;
  }
  const totalAttachmentSize=selectedFiles.reduce((sum,file)=>sum+file.size,0);
  if(shouldValidateAttachments&&totalAttachmentSize>MAX_TOTAL_ATTACHMENT_SIZE){
    orderAttachmentWrap.classList.add('order-error');
    orderNote.classList.add('order-note-error');
    orderNote.textContent=isAr?'إجمالي حجم المرفقات أكبر من 75MB. قلل عدد الملفات أو اضغطها في ملف أصغر.':'Total attachments size is larger than 75MB. Reduce files or compress them.';
    orderAttachment.focus();
    return;
  }
  orderSubmitting=true;
  orderSubmit.disabled=true;
  const submitLabel=orderSubmit.textContent;
  orderSubmit.textContent=isAr?'جاري الإرسال...':'Sending...';
  const customer=getCustomer()||{};
  const serviceName=orderService.value||'طلب جديد';
  const selectedOptions=activeProductOptionSelections.map(entry=>({
    ...backendOptionPayload(entry.option),
    groupId:entry.group.backendId||((typeof entry.group.id==='number')?entry.group.id:null),
    groupKey:entry.groupKey,
    groupNameAr:entry.group.nameAr||entry.group.name||'',
    groupNameEn:entry.group.nameEn||entry.group.name||''
  }));
  const selectedOption=selectedOptions[0]||null;
  const selectedDesignOption=activeOrderData?.designOptions?.find((option,index)=>optionId(option,index)===productContentModeValue);
  const quantity=Math.max(1,Math.min(99,Math.trunc(Number(orderQuantity.value)||1)));
  const unitPrice=roundMoney((activeOrderData?.price||0)+selectedOptions.reduce((sum,option)=>sum+optionExtra(option),0)+optionExtra(selectedDesignOption));
  const finalPrice=roundMoney(unitPrice*quantity);
  const productTaxEnabled=orderType.value==='product'&&activeOrderData?.taxEnabled!==false;
  const productVat=includedVatParts(finalPrice,productTaxEnabled);
  const productTaxAmount=productVat.tax;
  const productSubtotal=productVat.net;
  const productTotal=productVat.total;
  const shippingData={
    recipientName:shippingName.value.trim(),
    phone:shippingPhone.value.trim(),
    region:shippingRegion.value.trim(),
    city:shippingCity.value.trim(),
    district:shippingDistrict.value.trim(),
    street:shippingStreet.value.trim(),
    buildingNumber:shippingBuilding.value.trim(),
    postalCode:shippingPostal.value.trim(),
    shortAddress:shippingShortAddress.value.trim(),
    address:shippingAddress.value.trim(),
    notes:shippingNotes.value.trim()
  };
  // Shipping belongs to the cart checkout step.  A physical item must be
  // addable before the customer is asked for the single shared cart address.
  let attachments=[];
  try{
    attachments=shouldValidateAttachments?await Promise.all(selectedFiles.map(fileToAttachment)):[];
  }catch(error){
    orderSubmitting=false;
    orderSubmit.disabled=false;
    orderSubmit.textContent=submitLabel;
    orderAttachmentWrap.classList.add('order-error');
    orderNote.classList.add('order-note-error');
    orderNote.textContent=isAr?'تعذر حفظ المرفقات داخل المتصفح. جرّب ملفات أقل حجمًا أو أعد المحاولة.':'Could not save the attachments in the browser. Try smaller files or try again.';
    return;
  }
  const request={
    id:(orderType.value==='product'?'CART-':'REQ-')+Date.now().toString().slice(-6),
    type:orderType.value||'service',
    service:serviceName,
    serviceAr:activeOrderData?.nameAr||serviceName,
    serviceEn:activeOrderData?.nameEn||activeOrderData?.nameAr||serviceName,
    orderedLang:isAr?'ar':'en',
    clientName:orderType.value==='product'?(customer.name||shippingData.recipientName||'العميل محمد'):(customer.name||'العميل محمد'),
    email:customer.email||'customer@example.com',
    phone:orderType.value==='product'?shippingData.phone:(customer.phone||''),
    country:customer.country||'المملكة العربية السعودية',
    shippingRegion:orderType.value==='product'?shippingData.region:(customer.shippingRegion||customer.region||''),
    city:orderType.value==='product'?shippingData.city:(customer.city||'الرياض'),
    shippingRecipient:orderType.value==='product'?shippingData.recipientName:'',
    shippingPhone:orderType.value==='product'?shippingData.phone:'',
    shippingDistrict:orderType.value==='product'?shippingData.district:'',
    shippingStreet:orderType.value==='product'?shippingData.street:'',
    shippingBuilding:orderType.value==='product'?shippingData.buildingNumber:'',
    shippingPostal:orderType.value==='product'?shippingData.postalCode:'',
    shippingShortAddress:orderType.value==='product'?shippingData.shortAddress:'',
    shippingAddress:orderType.value==='product'?shippingData.address:(customer.shippingAddress||''),
    shippingNotes:orderType.value==='product'?shippingData.notes:'',
    message:isSmartProduct?(productLinkValue||productBriefValue):messageValue,
    image:activeOrderData?.image||'artee-logo.png',
    description:isServiceOrder?messageValue:(activeOrderData?.description||''),
    descriptionAr:isServiceOrder?messageValue:(activeOrderData?.descriptionAr||activeOrderData?.description||''),
    descriptionEn:isServiceOrder?messageValue:(activeOrderData?.descriptionEn||activeOrderData?.descriptionAr||activeOrderData?.description||''),
    backendId:activeOrderData?.backendId||null,
    catalogItemId:activeOrderData?.catalogItemId||activeOrderData?.backendId||null,
    catalogUuid:activeOrderData?.catalogUuid||'',
    selection:selectedOption,
    selections:selectedOptions,
    quantity,
    unitPrice:orderType.value==='product'?money(unitPrice):'',
    productMode:activeOrderData?.productMode||'',
    contentMode:productContentModeValue,
    contentSelection:selectedDesignOption?backendOptionPayload(selectedDesignOption):null,
    contentLink:productLinkValue,
    contentBrief:productBriefValue,
    subtotal:orderType.value==='product'?money(productSubtotal):'',
    taxEnabled:orderType.value==='product'?productTaxEnabled:false,
    taxRate:productTaxEnabled?15:0,
    taxAmount:orderType.value==='product'?money(productTaxAmount):'',
    clientPrice:orderType.value==='product'?money(productTotal):'',
    invoiceId:'',
    attachments,
    status:orderType.value==='product'?'cart_pending':'offer_pending_owner',
    paymentPlan:orderType.value==='product'?'full':'split',
    productPayment:'',
    initialPayment:'',
    initialPaymentAt:'',
    finalPayment:'',
    paidAt:'',
    productAvailability:activeOrderData?.status||'none',
    catalogPrice:isServiceOrder?money(finalPrice):'',
    price:isServiceOrder&&finalPrice?money(finalPrice):'',
    shippingMode:activeOrderData?.shippingMode||'manual',
    requiresShipping:activeOrderData?.requiresShipping!==false,
    createdAt:new Date().toISOString()
  };
  if(request.type==='product'){
    request.cartId=request.id;
    request.status='cart_pending';
    request.productPayment='';
    request.initialPayment='';
    request.initialPaymentAt='';
    request.paidAt='';
    const cart=readCart();
    cart.unshift(request);
    saveCart(cart);
    orderNote.classList.remove('order-note-error');
    orderNote.innerHTML=isAr
      ?`تمت إضافة <strong>${safeAttr(request.service)}</strong> إلى السلة.`
      :`<strong>${safeAttr(request.service)}</strong> has been added to cart.`;
    window.setTimeout(()=>{
      closeOrder();
      orderSubmit.textContent=submitLabel;
      openCart();
    },420);
    return;
  }
  const requests=location.protocol==='file:'?JSON.parse(localStorage.getItem('arteeDemoRequests')||'[]'):[];
  let attachmentUploadFailed=false;
  const backendOrder=await syncOrderToBackend(request,[request],request.type==='product'?shippingData:null);
  if(backendOrder){
    applyBackendOrderMeta(request,backendOrder);
    if(selectedFiles.length){
      try{
        const uploaded=await uploadOrderAttachments(backendOrder.id,selectedFiles);
        if(uploaded.length){
          const localAttachmentIds=collectStoredAttachmentIds(request.attachments);
          request.attachments=uploaded;
          await deleteStoredAttachmentIds(localAttachmentIds,{ownerKey:attachmentOwnerKey(customer),allowLegacy:true,activeIds:activeStoredAttachmentIds()});
        }
      }catch(error){
        attachmentUploadFailed=true;
        console.warn('Attachment API fallback',error);
      }
    }
  }
  requests.unshift(request);
  if(location.protocol==='file:')localStorage.setItem('arteeDemoRequests',JSON.stringify(requests.slice(0,20)));
  updateNavNotifications(getCustomer());
  orderNote.classList.toggle('order-note-error',attachmentUploadFailed);
  orderNote.innerHTML=attachmentUploadFailed
    ?(isAr?'تم إنشاء الطلب، لكن تعذر رفع أحد المرفقات إلى الخادم. يمكنك متابعة الطلب والتواصل مع ARTEE لإرسال الملف.':'The order was created, but an attachment could not be uploaded. You can continue and contact ARTEE to send the file.')
    :(isAr
      ?`تم ${request.type==='product'?'طلب المنتج':'إرسال الطلب'} برقم <strong>${safeAttr(request.id)}</strong>. سيظهر الآن في حساب العميل ولوحة المالك.`
      :`${request.type==='product'?'Product ordered':'Request sent'} as <strong>${safeAttr(request.id)}</strong>. It will now appear in the client account and owner dashboard.`);
  window.setTimeout(()=>{
    closeOrder();
    orderSubmit.textContent=submitLabel;
  },420);
});
const pendingOrder=localStorage.getItem('arteePendingOrder');
if(pendingOrder && getCustomer()){
  localStorage.removeItem('arteePendingOrder');
  activatePanel(['بطاقات أعمال ذكية','الملف الرقمي','حلول QR مخصصة','Smart Business Cards','Digital Profile','Custom QR Solutions'].includes(pendingOrder)?'products':'services');
  setTimeout(()=>openOrder(pendingOrder),450);
}
const servicesObserver=new IntersectionObserver(entries=>{
  entries.forEach(entry=>{
    if(entry.isIntersecting){
      document.querySelectorAll('.switch-panel.active .service-item').forEach((item,index)=>{
        setTimeout(()=>item.classList.add('revealed'),index*110);
      });
      servicesObserver.disconnect();
    }
  });
},{threshold:.2});
servicesObserver.observe(servicesSwitcher);

/* Hover stays transient on desktop; tap is available only on touch devices. */
const touchInteraction=window.matchMedia('(hover: none), (pointer: coarse)');
document.querySelectorAll('.pillar').forEach(pillar=>{
  pillar.addEventListener('click',event=>{
    if(!touchInteraction.matches){
      pillar.classList.remove('active');
      return;
    }
    event.stopPropagation();
    const opening=!pillar.classList.contains('active');
    document.querySelectorAll('.pillar').forEach(item=>item.classList.remove('active'));
    if(opening) pillar.classList.add('active');
  });
});
document.addEventListener('click',event=>{
  if(touchInteraction.matches&&!event.target.closest('.pillar'))document.querySelectorAll('.pillar.active').forEach(item=>item.classList.remove('active'));
});

/* Interactive floating product, while the glass frame stays fixed */
const scene=document.getElementById('cardScene'),wrapper=document.getElementById('cardWrapper');
const floatCard=document.querySelector('.nfc-card-img');
const cubeScene=document.querySelector('.cube-scene');
const cube=document.querySelector('.cube');
const isMobile=()=>window.innerWidth<900;
const baseCubeTransform='rotateX(-27deg) rotateY(-38deg) rotateZ(-5deg)';

function applyProductMotion(x,y,proximity){
  const lift=18+(proximity*105);
  const scale=.78+(proximity*.34);
  const moveX=x*14*proximity;
  const moveY=y*10*proximity;
  const rotateY=x*20*proximity;
  const rotateX=-y*16*proximity;
  floatCard.style.transform=`translate3d(${moveX}px,${moveY}px,${lift}px) scale(${scale}) rotateY(${rotateY}deg) rotateX(${rotateX}deg)`;
  floatCard.style.boxShadow=`0 ${8+proximity*24}px ${16+proximity*30}px rgba(0,0,0,${.22+proximity*.28})`;
}
function resetProductMotion(){
  floatCard.style.transform='translate3d(0,0,18px) scale(.78) rotateY(0deg) rotateX(0deg)';
  floatCard.style.boxShadow='0 8px 16px rgba(0,0,0,.22)';
}
function applyCubeMotion(x,y,proximity){
  if(!cube) return;
  const lift=18+(proximity*105);
  const scale=.78+(proximity*.34);
  const moveX=x*14*proximity;
  const moveY=y*10*proximity;
  const rotateX=-27-(y*18*proximity);
  const rotateY=-38+(x*30*proximity);
  const rotateZ=-5+(x*y*10*proximity);
  cubeScene.style.transform=`translate3d(${moveX}px,${moveY}px,${lift}px) scale(${scale})`;
  cubeScene.style.filter=`drop-shadow(0 ${8+proximity*24}px ${16+proximity*30}px rgba(0,0,0,${.22+proximity*.28}))`;
  cube.style.setProperty('--shift-x',`${x*2.2*proximity}px`);
  cube.style.setProperty('--shift-y',`${y*2.2*proximity}px`);
  cube.style.transform=`rotateX(${rotateX}deg) rotateY(${rotateY}deg) rotateZ(${rotateZ}deg)`;
}
function resetCubeMotion(){
  if(cubeScene){
    cubeScene.style.transform='translate3d(0,0,18px) scale(.78)';
    cubeScene.style.filter='drop-shadow(0 8px 16px rgba(0,0,0,.22))';
  }
  if(cube){
    cube.style.setProperty('--shift-x','0px');
    cube.style.setProperty('--shift-y','0px');
    cube.style.transform=baseCubeTransform;
  }
}

scene.addEventListener('mousemove',e=>{
  if(isMobile()) return;
  const r=scene.getBoundingClientRect();
  const x=((e.clientX-r.left)/r.width-.5)*2;
  const y=((e.clientY-r.top)/r.height-.5)*2;
  const distance=Math.min(1,Math.hypot(x,y));
  const proximity=1-distance*.42;
  if(document.getElementById('disp3d').classList.contains('active')){
    applyCubeMotion(x,y,proximity);
  }else{
    applyProductMotion(x,y,proximity);
  }
});
scene.addEventListener('mouseleave',()=>{
  resetProductMotion();
  resetCubeMotion();
});

/* Gentle motion on mobile */
if(isMobile()){
  let t=0;
  setInterval(()=>{
    t+=0.02;
    if(!document.getElementById('disp3d').classList.contains('active')){
      applyProductMotion(Math.sin(t)*.35,Math.cos(t*.7)*.25,.72);
    }
  },30);
}

/* Final transformation */
const finalReveal=document.getElementById('finalReveal');
finalReveal.addEventListener('click',event=>{
  if(!touchInteraction.matches){
    finalReveal.classList.remove('active');
    return;
  }
  event.stopPropagation();
  finalReveal.classList.toggle('active');
});
document.addEventListener('click',event=>{
  if(touchInteraction.matches&&!event.target.closest('#finalReveal'))finalReveal.classList.remove('active');
});
</script>
</body>
</html>
