/* ============================================================
   bezikaron — אזור אישי. נפתח לאחר התשלום (אופציונלי).
   מציג את תהליך ביצוע ההזמנה לפי הנתונים שהוזנו.
   ============================================================ */

function Cabinet({ order, onHome }) {
  const D = window.DATA;
  const isSub = order.mode === 'subscribe';
  const pkg = D.packages.find((p) => p.id === order.pkg);
  const subPrice = isSub ? window.PRICE.sub(order.monument, order.subTier, order.plan) : null;
  const orderPrice = !isSub && pkg ? window.PRICE.pkg(pkg.id, order.monument) : 0;
  const manager = order.manager || { name: 'אנה לוריא', role: 'מנהל טיפול אישי' };

  // שלבי הביצוע
  const stages = isSub
    ? [
        { title: 'המנוי פעיל', desc: 'התשלום בוצע, הכול אושר.' },
        { title: 'הביקור הראשון מתוכנן', desc: 'בעל המקצוע יגיע ברבעון זה.' },
        { title: 'הטיפול מתבצע', desc: 'בעל המקצוע במקום, מסדר את הכול.' },
        { title: 'דוח התמונות מוכן', desc: 'התמונות של הרבעון הזה זמינות.' },
      ]
    : [
        { title: 'ההזמנה התקבלה', desc: 'התשלום בוצע, ההזמנה נרשמה.' },
        { title: 'שובץ בעל מקצוע', desc: 'היציאה מתוכננת ל-5–7 ימים.' },
        { title: 'הטיפול מתבצע', desc: 'בעל המקצוע במקום, מסדר את הכול.' },
        { title: 'דוח התמונות מוכן', desc: 'התמונות "לפני ואחרי" זמינות.' },
      ];

  // השלב הנוכחי (אפשר לקדם בדמו)
  const [stage, setStage] = React.useState(1);
  const reportReady = stage >= 3;

  const placeLine = (() => {
    if (order.placeMethod === 'search') return [order.cemetery, order.deceased].filter(Boolean).join(' · ') || '—';
    if (order.placeMethod === 'photo') return 'לפי התמונה שלכם';
    return 'נעזור לאתר — המנהל יבדוק';
  })();

  return (
    <div style={{ background: 'var(--bg)', minHeight: '100%' }}>
      {/* כותרת האזור האישי */}
      <div style={{
        paddingTop: 56, paddingInline: 22, paddingBottom: 18,
        background: 'var(--ink)', color: 'var(--on-accent)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontFamily: 'var(--font-head)', fontWeight: 600, fontSize: 18 }}>אזור אישי</span>
          <button onClick={onHome} aria-label="לדף הבית" style={{
            width: 38, height: 38, borderRadius: 999, cursor: 'pointer',
            border: '1px solid rgba(251,250,246,0.2)', background: 'rgba(251,250,246,0.06)',
            color: 'var(--on-accent)', display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Icon name="arrowL" size={18} /></button>
        </div>
        <h1 className="t-h2" style={{ color: 'var(--on-accent)', marginTop: 14, fontSize: 26 }}>
          שלום{order.name ? `, ${order.name.split(' ')[0]}` : ''}
        </h1>
        <p style={{ color: 'rgba(251,250,246,0.65)', fontSize: 15, marginTop: 4 }}>
          הזמנה מס'{order.id} · {order.createdAt}
        </p>
      </div>

      {/* הזמנה פעילה */}
      <div style={{ padding: '20px 22px 0' }}>
        <div className="card" style={{ padding: 20, marginTop: -38, position: 'relative' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, marginBottom: 14 }}>
            <div>
              <div className="faint" style={{ fontSize: 13, fontWeight: 700, marginBottom: 3 }}>{isSub ? 'מנוי' : 'טיפול חד-פעמי'}</div>
              <h2 className="t-h3" style={{ fontSize: 20 }}>{isSub ? D.subscription.title : pkg.name}</h2>
            </div>
            <span style={{
              fontSize: 12, fontWeight: 700, padding: '6px 12px', borderRadius: 999, whiteSpace: 'nowrap',
              background: reportReady ? 'var(--accent-tint)' : 'var(--bronze-tint)',
              color: reportReady ? 'var(--accent-deep)' : 'var(--bronze-deep)',
            }}>{reportReady ? 'הושלם' : 'בטיפול'}</span>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '14px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
            <CabRow icon="pin" label="מיקום" value={placeLine} />
            {isSub && <CabRow icon="heart" label="רמת הטיפול" value={subPrice.tierName} />}
            <CabRow icon="leaf" label="סוג המצבה" value={window.MONUMENT_LABEL(order.monument)} />
            <CabRow icon={isSub ? 'calendar' : 'doc'} label={isSub ? 'תשלום' : 'מחיר'} value={isSub ? `${window.fmt(subPrice.perMonth)} ₪/חודש` : `${window.fmt(orderPrice)} ₪`} />
          </div>

          {/* ציר הזמן של הביצוע */}
          <div style={{ marginTop: 18 }}>
            <div className="t-eyebrow" style={{ marginBottom: 14 }}>תהליך הביצוע</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              {stages.map((s, i) => {
                const done = i < stage;
                const active = i === stage;
                return (
                  <div key={i} style={{ display: 'flex', gap: 14 }}>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                      <div style={{
                        width: 28, height: 28, borderRadius: 999, flexShrink: 0,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        background: done ? 'var(--accent)' : active ? 'var(--surface)' : 'var(--surface)',
                        border: done ? 'none' : active ? '2px solid var(--accent)' : '2px solid var(--line)',
                        color: done ? 'var(--on-accent)' : 'var(--accent)',
                        position: 'relative',
                      }}>
                        {done ? <Icon name="check" size={15} stroke={2.4} />
                          : active ? <span className="pulse" style={{ width: 9, height: 9, borderRadius: 999, background: 'var(--accent)' }} />
                          : <span style={{ width: 7, height: 7, borderRadius: 999, background: 'var(--line)' }} />}
                      </div>
                      {i < stages.length - 1 && <div style={{ width: 2, flex: 1, minHeight: 26, background: i < stage ? 'var(--accent)' : 'var(--line)' }} />}
                    </div>
                    <div style={{ paddingBottom: i < stages.length - 1 ? 16 : 0, paddingTop: 2 }}>
                      <div style={{ fontWeight: 700, fontSize: 16, color: active || done ? 'var(--ink)' : 'var(--ink-faint)' }}>{s.title}</div>
                      <p className="t-small" style={{ marginTop: 2, color: active || done ? 'var(--ink-soft)' : 'var(--ink-faint)' }}>{s.desc}</p>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>

      {/* דוח תמונות */}
      <div style={{ padding: '16px 22px 0' }}>
        <div className="card" style={{ padding: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: reportReady ? 14 : 0 }}>
            <IconDisc name="camera" size={40} />
            <div style={{ flex: 1 }}>
              <h3 className="t-h3" style={{ fontSize: 17 }}>דוח תמונות</h3>
              <p className="t-small">{reportReady ? 'התמונות "לפני ואחרי" מוכנות.' : 'יופיע לאחר ביצוע הטיפול.'}</p>
            </div>
            {!reportReady && <Icon name="lock" size={20} style={{ color: 'var(--ink-faint)' }} />}
          </div>
          {reportReady && (() => {
            const dbl = order.monument === 'double';
            const shots = [
              ['לפני', dbl ? 'uploads/Double_Before_2.jpg' : 'uploads/Single_Before_2.jpg'],
              ['אחרי', dbl ? 'uploads/Double_After_2.jpg' : 'uploads/Single_After_2.jpg'],
            ];
            return (
              <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                {shots.map(([lbl, src]) => (
                  <div key={lbl} style={{ position: 'relative', height: 150, borderRadius: 'var(--r)', overflow: 'hidden', border: '1px solid var(--line)' }}>
                    <img src={src} alt={lbl} style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center 38%' }} />
                    <span style={{
                      position: 'absolute', top: 8, insetInlineStart: 8,
                      fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase',
                      color: '#FBFAF6', background: 'rgba(20,20,18,0.5)', backdropFilter: 'blur(3px)',
                      padding: '4px 9px', borderRadius: 999,
                    }}>{lbl}</span>
                  </div>
                ))}
              </div>
            );
          })()}
        </div>
      </div>

      {/* מנוי: החיוב/הביקור הבא */}
      {isSub && (
        <div style={{ padding: '16px 22px 0' }}>
          <div className="card" style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 12 }}>
            <h3 className="t-h3" style={{ fontSize: 17 }}>המנוי שלכם</h3>
            <CabRow icon="pin" label="הביקור הבא" value="ברבעון זה" />
            <CabRow icon="calendar" label="החיוב הבא" value={subPrice.bill.replace('חיוב של ', '').replace(/ (פעם בשנה|מדי חודש)/, '')} />
            <button className="btn btn-quiet btn-sm" style={{ width: '100%', marginTop: 2 }}>ניהול המנוי</button>
          </div>
        </div>
      )}

      {/* מנהל טיפול אישי */}
      <div style={{ padding: '16px 22px 0' }}>
        <div className="card" style={{ padding: 18, display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 48, height: 48, borderRadius: 999, background: 'var(--bronze-tint)', color: 'var(--bronze-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-head)', fontWeight: 600, fontSize: 20, flexShrink: 0 }}>{manager.name[0]}</div>
          <div style={{ flex: 1 }}>
            <div className="faint" style={{ fontSize: 13, fontWeight: 700 }}>{manager.role}</div>
            <div style={{ fontWeight: 700, fontSize: 16 }}>{manager.name}</div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            {['chat', 'phone'].map((ic) => (
              <button key={ic} aria-label={ic} style={{
                width: 44, height: 44, borderRadius: 999, cursor: 'pointer',
                border: '1px solid var(--line)', background: 'var(--surface-2)',
                color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}><Icon name={ic} size={20} /></button>
            ))}
          </div>
        </div>
      </div>

      {/* בקרת התקדמות לדמו */}
      <div style={{ padding: '20px 22px 40px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {stage < stages.length - 1 ? (
          <button className="btn btn-ghost btn-sm" style={{ width: '100%' }} onClick={() => setStage((s) => Math.min(stages.length - 1, s + 1))}>
            <Icon name="arrow" size={16} /> דמו: השלב הבא
          </button>
        ) : (
          <button className="btn btn-quiet btn-sm" style={{ width: '100%' }} onClick={() => setStage(1)}>
            איפוס הדמו
          </button>
        )}
        <button className="btn btn-quiet" onClick={onHome}>
          <Icon name="arrowL" size={18} /> לדף הבית
        </button>
      </div>
    </div>
  );
}

function CabRow({ icon, label, value }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
      <Icon name={icon} size={18} style={{ color: 'var(--accent-deep)', flexShrink: 0 }} />
      <span className="t-small" style={{ flexShrink: 0 }}>{label}</span>
      <span className="t-body" style={{ fontWeight: 700, marginInlineStart: 'auto', textAlign: 'end' }}>{value}</span>
    </div>
  );
}

// ---------- אזור אישי ריק (עדיין אין הזמנות) ----------
function CabinetEmpty({ onGoCare }) {
  return (
    <div style={{ minHeight: '100%', background: 'var(--bg)' }}>
      <window.TabHeader title="אזור אישי" lead="כאן יופיעו ההזמנות ודוחות התמונות שלכם." />
      <div style={{ padding: '40px 22px', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center' }}>
        <div style={{
          width: 76, height: 76, borderRadius: 999, marginBottom: 20,
          background: 'var(--accent-tint)', color: 'var(--accent-deep)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="leaf" size={36} />
        </div>
        <h2 className="t-h3" style={{ marginBottom: 8 }}>אין הזמנות עדיין</h2>
        <p className="t-small" style={{ maxWidth: 280, marginBottom: 24 }}>
          לאחר שתזמינו טיפול, כאן תוכלו לעקוב אחר הביצוע ולראות את דוח התמונות.
        </p>
        <button className="btn btn-primary" style={{ maxWidth: 260 }} onClick={onGoCare}>
          לבחור טיפול
          <Icon name="arrow" size={20} stroke={2} />
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { Cabinet, CabinetEmpty });
