#################################################################
# ILLUSTRATIVE EXAMPLE: Full PLS-SEM Workflow
# Package: PLSsemEngine
# Purpose: Demonstrates transparency, modularity, and diagnostics
#################################################################

# Assumes PLSsemEngine is already installed
library(PLSsemEngine)

# =============================================================
# 1. DATA GENERATION (Reproducible Synthetic Dataset)
# =============================================================
# Simulates a Service Marketing framework (N = 300)
set.seed(123)
n <- 300

# Theoretical latent constructs
Service_Quality <- rnorm(n)
Customer_Satisfaction <- 0.6 * Service_Quality + rnorm(n, sd = 0.6)
Customer_Loyalty <- 0.55 * Customer_Satisfaction + 0.25 * Service_Quality + rnorm(n, sd = 0.6)

# Transformation function: Latent scores to 7-point Likert items
latent_to_item <- function(latent, loading) {
  x <- loading * latent + rnorm(length(latent), sd = sqrt(1 - loading^2))
  x <- scale(x)
  as.numeric(cut(x, breaks = quantile(x, probs = seq(0, 1, length.out = 8)),
                 labels = 1:7, include.lowest = TRUE))
}

# Construct the dataframe SQ1-SQ3, CS1-CS3, CL1-CL3
simulated_data <- data.frame(
  SQ1 = latent_to_item(Service_Quality, 0.82), SQ2 = latent_to_item(Service_Quality, 0.78), SQ3 = latent_to_item(Service_Quality, 0.74),
  CS1 = latent_to_item(Customer_Satisfaction, 0.80), CS2 = latent_to_item(Customer_Satisfaction, 0.76), CS3 = latent_to_item(Customer_Satisfaction, 0.72),
  CL1 = latent_to_item(Customer_Loyalty, 0.81), CL2 = latent_to_item(Customer_Loyalty, 0.77), CL3 = latent_to_item(Customer_Loyalty, 0.73)
)

# =============================================================
# 2. MODEL SPECIFICATION (Native R Interface)
# =============================================================
# Defining the reflective measurement model
measurement_model <- list(
  Service_Quality = c("SQ1", "SQ2", "SQ3"),
  Customer_Satisfaction = c("CS1", "CS2", "CS3"),
  Customer_Loyalty = c("CL1", "CL2", "CL3")
)

# Defining the structural paths using R formulas
structural_model <- list(
  Customer_Satisfaction ~ Service_Quality,
  Customer_Loyalty ~ Customer_Satisfaction + Service_Quality
)

# =============================================================
# 3. MODEL EXECUTION
# =============================================================
# High-level wrapper coordinates estimation, bootstrap, and prediction
# nboot = 500 is used for stable inference as per SoftwareX standards
model <- pls_sem(
  data = simulated_data,
  measurement_model = measurement_model,
  structural_model = structural_model,
  nboot = 500,
  k = 5
)

# =============================================================
# 4. COMPREHENSIVE OUTPUTS (Aligned with Manuscript Tables)
# =============================================================

# 4.1 Measurement Model Assessment (Table 1)
# Includes Loadings, Composite Reliability (CR), AVE, and R2
print(model$measurement_model)

# 4.2 Discriminant Validity (Table 3)
# Includes both HTMT and HTMT2 for congeneric models
print(model$discriminant_validity$HTMT)
print(model$discriminant_validity$HTMT2)

# 4.3 Structural Model and Inference (Table 4)
# Includes Path Coefficients, Bootstrap CIs, and f2 Effect Sizes
print(model$structural_model)

# 4.4 Predictive Relevance (Table 5)
# PLSpredict results: RMSE, MAE, and Q2_predict
print(model$predictive_relevance)

# 4.5 Inferential Predictive Test: CVPAT (PLSsemEngine >= v1.3.0)
# Tests whether PLS predictions are significantly better than a naive LM benchmark
resultado_cvpat <- cvpat(model)
print(resultado_cvpat)

# =============================================================
# 5. ADVANCED DIAGNOSTICS & BRIDGES (Reviewer Requests)
# =============================================================

# 5.1 Common Method Bias (CMB)
# Full Collinearity VIF following Kock (2015)
print(model$diagnostics$common_method_bias)

# 5.2 Global Model Fit
# Indices: SRMR, d_ULS, and d_G
print(model$diagnostics$global_fit)

# 5.3 Indirect Effects (Mediation Analysis)
# Computed as the product of corresponding paths
PLSsemEngine:::get_indirect_effects(model)

# 5.4 Methodological Bridge: CB-SEM Syntax
# Automatically translates PLS specification to lavaan code
export_lavaan_syntax(measurement_model, structural_model)

# 5.5 Optional Structured Interpretive Layer
# Contextualizes metrics against established literature thresholds
interpret_model(model)

# =============================================================
# 6. VISUALIZATION
# =============================================================
# 6.1 Plot conceptual structural model
plot_structural_model(structural_model)

# 6.2 Plot final model with results (Beta values and R2)
plot_model_results(model, show_r2 = TRUE)

# 6.3 Export results for external reporting
export_scores(model, file.path(tempdir(), "latent_scores.csv"))
