
// Right-side lead detail drawer with 8-step pipeline and dynamic activity
const { useState: useStDr, useEffect: useEffDr } = React;

function LeadDrawer({ lead, agents, stages, onClose, onUpdate }) {
  const [agentOpen, setAgentOpen] = useStDr(false);
  const [callingState, setCallingState] = useStDr('idle'); // idle, loading, success, error
  const [callError, setCallError] = useStDr('');

  useEffDr(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const handleTriggerCall = async () => {
    setCallingState('loading');
    setCallError('');
    
    try {
      const response = await fetch('https://api.nugget.com/unified-support/api/v1/ticketing/external/voice/getOrCreateIssue', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Basic ZGVtb251Z2dldEBudWdnZXQuY29tOmQ0NG8yN2IyODg2czczYzZvcGJnLWQ2bnQ0bGNqaW5yYzczOTBjMHBn'
        },
        body: JSON.stringify({
          businessPhoneNumber: '918035341451',
          userPhoneNumber: '919910988218',
          callDirection: 'outbound',
          journeyId: 'loan-followup-v1',
          journeyVersion: '1.0'
        })
      });

      if (response.ok) {
        const data = await response.json();
        console.log('✅ Call triggered successfully:', data);
        setCallingState('success');
        setTimeout(() => {
          setCallingState('idle');
        }, 3000);
      } else {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || 'Failed to trigger call');
      }
    } catch (err) {
      console.error('❌ Error triggering call:', err);
      setCallError(err.message || 'Failed to trigger call. Please try again.');
      setCallingState('error');
      setTimeout(() => {
        setCallingState('idle');
      }, 3000);
    }
  };

  if (!lead) return null;

  const initials = lead.borrower.split(" ").map(w => w[0]).slice(0, 2).join("");
  const borrowerColor = ["#5684CC", "#A78BC7", "#4FA8A5", "#6BAE5B", "#D49A3A"][lead.id % 5];
  const agent = agents[lead.agentId];
  
  // Get pipeline step from lead data
  const pipelineStep = lead.pipelineStep || 0;
  const pipelineStages = window.LMS_DATA.pipelineStages || [];
  
  // Current stage label for badge
  const currentStageLabel = pipelineStages[pipelineStep]?.label || "Lead Created";
  
  // Action status based on pipeline step
  let actionStatus = "On track";
  let actionColor = "#3F7A33";
  if (pipelineStep === 7) {
    actionStatus = "Meeting confirmed";
    actionColor = "#3F7A33";
  } else if (lead.awaiting) {
    actionStatus = "Action pending";
    actionColor = "#8A6519";
  }
  
  // Activity log - build based on refresh count
  const activityLog = getActivityLog(pipelineStep, agent.name);

  return (
    <React.Fragment>
      <div onClick={onClose} className="drawerBackdrop" />
      <aside className="drawer" onClick={(e) => e.stopPropagation()}>
        {/* Sticky header */}
        <div style={{
          padding: "20px 24px 16px",
          borderBottom: "1px solid #ECECEA",
          background: "#fff",
          position: "sticky", top: 0, zIndex: 2,
        }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 14 }}>
            <span style={{ fontSize: 10.5, color: "#9CA3AF", letterSpacing: 0.5, textTransform: "uppercase" }}>
              Lead · NSF-{String(lead.id).padStart(4, "0")}
            </span>
            <button onClick={onClose} style={iconBtn} aria-label="Close"><Icons.x size={14} /></button>
          </div>
          <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
            <Avatar initials={initials} color={borrowerColor} size={48} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 17, fontWeight: 500, color: "#1F2433", letterSpacing: -0.3 }}>
                {lead.borrower}
              </div>
              <div style={{ fontSize: 12.5, color: "#6B7280", marginTop: 2 }}>
                {lead.business}
                <span style={{ margin: "0 7px", color: "#D4D4D2" }}>•</span>
                {lead.city}
              </div>
            </div>
          </div>

          <div style={{ display: "flex", gap: 6, marginTop: 14 }}>
            <a href={`tel:${lead.phone.replace(/\s/g, "")}`} onClick={(e) => e.preventDefault()} style={chipLink}>
              <Icons.phone size={12} />
              {lead.phone}
            </a>
            <a href={`mailto:${lead.email}`} onClick={(e) => e.preventDefault()} style={chipLink}>
              <Icons.mail size={12} />
              {lead.email}
            </a>
          </div>
        </div>

        {/* Body */}
        <div style={{ padding: "20px 24px", display: "flex", flexDirection: "column", gap: 22 }}>

          {/* Loan summary */}
          <section>
            <SectionHeader label="Loan details" />
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginTop: 10 }}>
              <Field label="Loan ask">
                <span style={{ fontSize: 22, fontWeight: 600, color: "#1F2433", letterSpacing: -0.4 }}>
                  {formatINR(lead.amount)}
                </span>
                <div style={{ fontSize: 11, color: "#9CA3AF", marginTop: 2, fontVariantNumeric: "tabular-nums" }}>
                  {formatINRFull(lead.amount)}
                </div>
              </Field>
              <Field label="Stage">
                <div style={{ marginTop: 2 }}>
                  <span style={{
                    display: "inline-flex", alignItems: "center", gap: 6,
                    padding: "4px 10px",
                    borderRadius: 999,
                    background: "#FBF4E6",
                    color: "#8A6519",
                    fontSize: 12,
                    fontWeight: 500,
                    lineHeight: 1.2,
                    whiteSpace: "nowrap",
                    border: "1px solid #8A65191f",
                  }}>
                    <span style={{ width: 6, height: 6, borderRadius: 999, background: "#D49A3A" }} />
                    {currentStageLabel}
                  </span>
                </div>
              </Field>
              <Field label="Business Type">
                <span style={{ fontSize: 13, color: "#1F2433" }}>{lead.sector}</span>
              </Field>
              <Field label="Years in Business">
                <span style={{ fontSize: 13, color: "#1F2433" }}>{lead.vintage}</span>
              </Field>
              <Field label="Action status">
                {lead.awaiting && pipelineStep < 7 ? (
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, color: "#8A6519", fontWeight: 500 }}>
                    <span className="pulseDot" style={{ width: 7, height: 7, borderRadius: 999, background: "#D49A3A" }} />
                    Action pending
                  </span>
                ) : (
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, color: actionColor, fontWeight: 500 }}>
                    <Icons.check size={13} /> {actionStatus}
                  </span>
                )}
              </Field>
            </div>
          </section>

          {/* 8-step Pipeline Progress */}
          <section>
            <SectionHeader label="Pipeline progress" />
            <div style={{ marginTop: 14, position: "relative", overflowX: "auto", paddingBottom: 8 }}>
              <div style={{ display: "flex", justifyContent: "space-between", minWidth: 800, gap: 4 }}>
                {pipelineStages.map((stage, i) => {
                  const isDone = i < pipelineStep;
                  const isCurrent = i === pipelineStep;
                  const isFuture = i > pipelineStep;
                  return (
                    <div key={i} style={{ 
                      display: "flex", 
                      flexDirection: "column", 
                      alignItems: "center", 
                      flex: 1, 
                      minWidth: 85,
                      gap: 8,
                      position: "relative"
                    }}>
                      {/* Connector line */}
                      {i < pipelineStages.length - 1 && (
                        <div style={{
                          position: "absolute",
                          top: 7,
                          left: "50%",
                          right: "-50%",
                          height: 2,
                          background: isDone ? "#D49A3A" : "#ECECEA",
                          zIndex: 0,
                        }} />
                      )}
                      
                      {/* Step indicator */}
                      <span style={{
                        width: 14, height: 14, borderRadius: 999,
                        background: (isDone || isCurrent) ? "#D49A3A" : "#fff",
                        border: "2px solid " + ((isDone || isCurrent) ? "#D49A3A" : "#ECECEA"),
                        transition: "all 200ms ease",
                        zIndex: 1,
                        position: "relative",
                      }} />
                      
                      {/* Label */}
                      <span style={{
                        fontSize: 9.5,
                        color: isCurrent ? "#1F2433" : (isDone ? "#6B7280" : "#9CA3AF"),
                        fontWeight: isCurrent ? 600 : 400,
                        textAlign: "center",
                        lineHeight: 1.3,
                        maxWidth: 80,
                      }}>{stage.label}</span>
                      
                      {/* Date */}
                      <span style={{ 
                        fontSize: 9.5, 
                        color: (isDone || isCurrent) ? "#6B7280" : "#D4D4D2",
                        fontVariantNumeric: "tabular-nums"
                      }}>{stage.date}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          </section>

          {/* Activity log - taller, no Notes */}
          <section>
            <SectionHeader label="Recent activity" />
            <div style={{ marginTop: 10, display: "flex", flexDirection: "column", gap: 12, maxHeight: 400, overflowY: "auto" }}>
              {activityLog.map((a, i) => (
                <div key={i} style={{ display: "flex", gap: 10 }}>
                  <Avatar initials={a.who === "System" ? "NS" : agent.initials} color={a.who === "System" ? "#1F2433" : agent.color} size={24} />
                  <div style={{ flex: 1, fontSize: 12, color: "#1F2433", lineHeight: 1.5 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8 }}>
                      <span style={{ fontWeight: 500 }}>{a.who}</span>
                      <span style={{ fontSize: 10.5, color: "#9CA3AF", whiteSpace: "nowrap" }}>{a.when}</span>
                    </div>
                    <div style={{ color: "#6B7280", marginTop: 1 }}>{a.text}</div>
                  </div>
                </div>
              ))}
            </div>
          </section>
        </div>

        {/* Sticky footer */}
        <div style={{
          position: "sticky", bottom: 0,
          padding: "14px 24px",
          background: "#fff",
          borderTop: "1px solid #ECECEA",
          display: "flex", gap: 8,
        }}>
          <button
            onClick={handleTriggerCall}
            disabled={callingState === 'loading'}
            style={{
              ...btnCallDrawer,
              flex: 1,
              opacity: callingState === 'loading' ? 0.7 : 1,
              cursor: callingState === 'loading' ? 'not-allowed' : 'pointer'
            }}
          >
            {callingState === 'loading' ? (
              <>
                <span style={{
                  display: 'inline-block',
                  width: 14,
                  height: 14,
                  border: '2px solid #fff',
                  borderTopColor: 'transparent',
                  borderRadius: '50%',
                  animation: 'spin 0.6s linear infinite'
                }} />
                Calling...
              </>
            ) : callingState === 'success' ? (
              <>
                <Icons.check size={13} />
                Call Triggered
              </>
            ) : callingState === 'error' ? (
              <>
                <Icons.x size={13} />
                Call Failed
              </>
            ) : (
              <>
                <Icons.phone size={13} />
                Trigger Call
              </>
            )}
          </button>
          <a href="timeline.html" target="_blank" style={{ ...btnDarkDrawer, flex: 1, textDecoration: "none" }}>
            View full application <Icons.arrow size={13} />
          </a>
        </div>
      </aside>
    </React.Fragment>
  );
}

// Generate activity log based on pipeline step
function getActivityLog(step, agentName) {
  const whatsappMessage = "Hello Mr. Dushyant,\n\nPlease find your loan application form on the link below. Kindly upload the required documents directly on the form to complete your application.\n\nLink: https://nugget-loan-form.vercel.app/\n\nRegards,\nNorthstar Fincorp";
  
  const baseActivities = [
    { who: agentName, when: "20 May, 11:02 AM", text: "Lead created via FOS visit. Borrower details logged via voice prompt." },
    { who: "System", when: "20 May, 11:18 AM", text: `Application form link sent to borrower via WhatsApp:\n\n${whatsappMessage}` },
    { who: "System", when: "20 May, 7:24 PM", text: "Voice agent call initiated. Form flagged as not filled after 8 hours." },
  ];
  
  const stepActivities = [
    { who: "System", when: "Just now", text: `Application form link sent to borrower via WhatsApp:\n\n${whatsappMessage}` },
    { who: "System", when: "Just now", text: "Voice agent call completed. Business profile and financial details captured successfully." },
    { who: "System", when: "Just now", text: "All 5 documents received. OCR extraction and verification initiated." },
    { who: "System", when: "Just now", text: "Borrower profile verified. Application forwarded to credit team for assessment." },
    { who: "System", when: "Just now", text: "Credit assessment complete. Loan plan generated — ₹40L at 15.5% p.a., 48 months." },
    { who: "System", when: "Just now", text: "Voice agent call completed. Loan plan presented. Rate negotiated from 17% to 15.5%." },
    { who: agentName, when: "Just now", text: "Meeting confirmed — Wednesday 29 May, 11:00 AM. Borrower briefed. Ready to close." },
  ];
  
  // Build activity log: new activities at top, aging timestamps
  const activities = [];
  
  // Add activities up to current step (in reverse order, newest first)
  for (let i = step - 1; i >= 0; i--) {
    const activity = { ...stepActivities[i] };
    // Age the timestamps
    const ageMinutes = (step - 1 - i) * 5;
    if (ageMinutes === 0) {
      activity.when = "Just now";
    } else if (ageMinutes < 60) {
      activity.when = `${ageMinutes} min ago`;
    } else {
      const hours = Math.floor(ageMinutes / 60);
      activity.when = `${hours}h ago`;
    }
    activities.push(activity);
  }
  
  // Add base activities at the end
  activities.push(...baseActivities);
  
  return activities;
}

function SectionHeader({ label, action }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
      <span style={{ fontSize: 10.5, color: "#9CA3AF", letterSpacing: 0.6, textTransform: "uppercase", fontWeight: 500 }}>{label}</span>
      {action}
    </div>
  );
}

function Field({ label, children }) {
  return (
    <div style={{ minWidth: 0 }}>
      <div style={{ fontSize: 10.5, color: "#9CA3AF", letterSpacing: 0.4, textTransform: "uppercase", marginBottom: 4 }}>{label}</div>
      <div style={{ minWidth: 0 }}>{children}</div>
    </div>
  );
}

const iconBtn = {
  width: 28, height: 28, borderRadius: 6,
  display: "inline-flex", alignItems: "center", justifyContent: "center",
  background: "#fff", border: "1px solid #ECECEA",
  cursor: "pointer", color: "#6B7280",
};
const chipLink = {
  display: "inline-flex", alignItems: "center", gap: 6,
  padding: "5px 10px", borderRadius: 6,
  background: "#FCFCFB", border: "1px solid #ECECEA",
  fontSize: 11.5, color: "#1F2433",
  textDecoration: "none", cursor: "pointer",
};
const btnDarkDrawer = {
  height: 38, border: "none", background: "#1F2433", color: "#fff",
  borderRadius: 8, fontSize: 12.5, fontWeight: 500,
  display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6,
  cursor: "pointer", fontFamily: "inherit",
};
const btnCallDrawer = {
  height: 38, border: "1px solid #4CAF50", background: "#fff", color: "#4CAF50",
  borderRadius: 8, fontSize: 12.5, fontWeight: 500,
  display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6,
  cursor: "pointer", fontFamily: "inherit",
  transition: "all 0.2s ease",
};

Object.assign(window, { LeadDrawer });
